blob: dcf3ef133981fc2504426411e87de723dfb38f1e [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"
Reid Kleckner98031782019-12-09 16:11:56 -080016#include "clang/AST/Attr.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000020#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000021#include "llvm/ADT/SmallPtrSet.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080022#include "llvm/IR/IntrinsicsNVPTX.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000023
24using namespace clang;
25using namespace CodeGen;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060026using namespace llvm::omp;
Samuel Antao45bfe4c2016-02-08 15:59:20 +000027
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000028namespace {
29enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000031 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000032 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000033 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000034 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000036 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000037 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000038 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
39 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000041 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000042 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000045 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000046 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000048 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
49 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_serialized_parallel,
52 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
53 /// global_tid);
54 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// int16_t lane_offset, int16_t warp_size);
60 OMPRTL_NVPTX__kmpc_shuffle_int64,
Alexey Bataev8e009032019-01-04 17:25:09 +000061 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000062 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
63 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
64 /// lane_offset, int16_t shortCircuit),
65 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
Alexey Bataev8061acd2019-02-20 16:36:22 +000066 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
67 /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
68 /// global_tid, void *global_buffer, int32_t num_of_records, void*
69 /// reduce_data,
70 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
71 /// lane_offset, int16_t shortCircuit),
72 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
73 /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
74 /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
75 /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
76 /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
77 /// *buffer, int idx, void *reduce_data));
78 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000080 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000082 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000083 /// Call to void __kmpc_data_sharing_init_stack_spmd();
84 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000085 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000087 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000088 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000089 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000091 /// size_t n_args);
92 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000093 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000094 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000095 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000096 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000097 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
98 /// global_tid);
99 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +0000100 /// Call to int8_t __kmpc_is_spmd_exec_mode();
101 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +0000102 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
103 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +0000104 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +0000105 /// Call to void __kmpc_restore_team_static_memory(int16_t
106 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +0000107 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000108 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000109 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000110 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
111 /// global_tid);
112 OMPRTL__kmpc_barrier_simple_spmd,
Alexey Bataev2cd7faf2019-08-26 19:07:48 +0000113 /// Call to int32_t __kmpc_warp_active_thread_mask(void);
114 OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
115 /// Call to void __kmpc_syncwarp(int32_t Mask);
116 OMPRTL_NVPTX__kmpc_syncwarp,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000117};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000118
119/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
120class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000121 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000122 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000123 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000124 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000125 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000126 llvm::BasicBlock *ContBlock = nullptr;
127
128public:
James Y Knight9871db02019-02-05 16:42:33 +0000129 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
130 ArrayRef<llvm::Value *> EnterArgs,
131 llvm::FunctionCallee ExitCallee,
132 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000133 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
134 ExitArgs(ExitArgs), Conditional(Conditional) {}
135 void Enter(CodeGenFunction &CGF) override {
136 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
137 if (Conditional) {
138 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
139 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
140 ContBlock = CGF.createBasicBlock("omp_if.end");
141 // Generate the branch (If-stmt)
142 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
143 CGF.EmitBlock(ThenBlock);
144 }
145 }
146 void Done(CodeGenFunction &CGF) {
147 // Emit the rest of blocks/branches
148 CGF.EmitBranch(ContBlock);
149 CGF.EmitBlock(ContBlock, true);
150 }
151 void Exit(CodeGenFunction &CGF) override {
152 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
153 }
154};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000155
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000156/// A class to track the execution mode when codegening directives within
157/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
158/// to the target region and used by containing directives such as 'parallel'
159/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000160class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000161private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000162 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
163 CGOpenMPRuntimeNVPTX::EM_Unknown;
164 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
165 bool SavedRuntimeMode = false;
166 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000167
168public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000169 /// Constructor for Non-SPMD mode.
170 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
171 : ExecMode(ExecMode) {
172 SavedExecMode = ExecMode;
173 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000174 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000175 /// Constructor for SPMD mode.
176 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
177 bool &RuntimeMode, bool FullRuntimeMode)
178 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
179 SavedExecMode = ExecMode;
180 SavedRuntimeMode = RuntimeMode;
181 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
182 RuntimeMode = FullRuntimeMode;
183 }
184 ~ExecutionRuntimeModesRAII() {
185 ExecMode = SavedExecMode;
186 if (RuntimeMode)
187 *RuntimeMode = SavedRuntimeMode;
188 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000189};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000190
191/// GPU Configuration: This information can be derived from cuda registers,
192/// however, providing compile time constants helps generate more efficient
193/// code. For all practical purposes this is fine because the configuration
194/// is the same for all known NVPTX architectures.
195enum MachineConfiguration : unsigned {
196 WarpSize = 32,
197 /// Number of bits required to represent a lane identifier, which is
198 /// computed as log_2(WarpSize).
199 LaneIDBits = 5,
200 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000201
202 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000203 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000204
205 /// Maximal size of the shared memory buffer.
206 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000207};
208
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000209static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
210 RefExpr = RefExpr->IgnoreParens();
211 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
212 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
213 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
214 Base = TempASE->getBase()->IgnoreParenImpCasts();
215 RefExpr = Base;
216 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
217 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
218 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
219 Base = TempOASE->getBase()->IgnoreParenImpCasts();
220 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
221 Base = TempASE->getBase()->IgnoreParenImpCasts();
222 RefExpr = Base;
223 }
224 RefExpr = RefExpr->IgnoreParenImpCasts();
225 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
226 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
227 const auto *ME = cast<MemberExpr>(RefExpr);
228 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
229}
230
Alexey Bataev2adecff2018-09-21 14:22:53 +0000231
232static RecordDecl *buildRecordForGlobalizedVars(
233 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000234 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000235 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000236 &MappedDeclsFields, int BufSize) {
Fangrui Song899d1392019-04-24 14:43:05 +0000237 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000238 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000239 return nullptr;
240 SmallVector<VarsDataTy, 4> GlobalizedVars;
241 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000242 GlobalizedVars.emplace_back(
243 CharUnits::fromQuantity(std::max(
244 C.getDeclAlign(D).getQuantity(),
245 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
246 D);
247 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000248 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
Fangrui Song899d1392019-04-24 14:43:05 +0000249 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
250 return L.first > R.first;
251 });
252
Alexey Bataev2adecff2018-09-21 14:22:53 +0000253 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000254 // /* globalized vars */[WarSize] align (max(decl_align,
255 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000256 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000257 // };
258 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
259 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000260 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
261 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000262 for (const auto &Pair : GlobalizedVars) {
263 const ValueDecl *VD = Pair.second;
264 QualType Type = VD->getType();
265 if (Type->isLValueReferenceType())
266 Type = C.getPointerType(Type.getNonReferenceType());
267 else
268 Type = Type.getNonReferenceType();
269 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000270 FieldDecl *Field;
271 if (SingleEscaped.count(VD)) {
272 Field = FieldDecl::Create(
273 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
274 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
275 /*BW=*/nullptr, /*Mutable=*/false,
276 /*InitStyle=*/ICIS_NoInit);
277 Field->setAccess(AS_public);
278 if (VD->hasAttrs()) {
279 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
280 E(VD->getAttrs().end());
281 I != E; ++I)
282 Field->addAttr(*I);
283 }
284 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000285 llvm::APInt ArraySize(32, BufSize);
Richard Smith772e2662019-10-04 01:25:59 +0000286 Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
287 0);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000288 Field = FieldDecl::Create(
289 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
290 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
291 /*BW=*/nullptr, /*Mutable=*/false,
292 /*InitStyle=*/ICIS_NoInit);
293 Field->setAccess(AS_public);
294 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
295 static_cast<CharUnits::QuantityType>(
296 GlobalMemoryAlignment)));
297 Field->addAttr(AlignedAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +0000298 C, /*IsAlignmentExpr=*/true,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000299 IntegerLiteral::Create(C, Align,
300 C.getIntTypeForBitwidth(32, /*Signed=*/0),
Erich Keane6a24e802019-09-13 17:39:31 +0000301 SourceLocation()),
302 {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000303 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000304 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000305 MappedDeclsFields.try_emplace(VD, Field);
306 }
307 GlobalizedRD->completeDefinition();
308 return GlobalizedRD;
309}
310
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000311/// Get the list of variables that can escape their declaration context.
312class CheckVarsEscapingDeclContext final
313 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
314 CodeGenFunction &CGF;
315 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000316 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000317 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000318 RecordDecl *GlobalizedRD = nullptr;
319 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000320 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000321 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000322
323 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000324 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000325 if (!isa<VarDecl>(VD) ||
326 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000327 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000328 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000329 // Use user-specified allocation.
330 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
331 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000332 // Variables captured by value must be globalized.
333 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000334 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000335 // Check if need to capture the variable that was already captured by
336 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000337 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000338 if (!FD->hasAttrs())
339 return;
340 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
341 if (!Attr)
342 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000343 if (((Attr->getCaptureKind() != OMPC_map) &&
344 !isOpenMPPrivate(
345 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
346 ((Attr->getCaptureKind() == OMPC_map) &&
347 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000348 return;
349 }
350 if (!FD->getType()->isReferenceType()) {
351 assert(!VD->getType()->isVariablyModifiedType() &&
352 "Parameter captured by value with variably modified type");
353 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000354 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000356 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000357 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000358 }
359 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000360 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000361 VD->getType()->isReferenceType())
362 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000363 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000364 if (VD->getType()->isVariablyModifiedType())
365 EscapedVariableLengthDecls.insert(VD);
366 else
367 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 }
369
370 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000371 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000372 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000373 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
374 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
375 const bool SavedAllEscaped = AllEscaped;
376 AllEscaped = VD->getType()->isLValueReferenceType();
377 Visit(VarD->getInit());
378 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000379 }
380 }
381 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000382 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
383 ArrayRef<OMPClause *> Clauses,
384 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 if (!S)
386 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000387 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000388 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
389 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000390 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
391 if (IsCombinedParallelRegion) {
392 // Check if the variable is privatized in the combined construct and
393 // those private copies must be shared in the inner parallel
394 // directive.
395 IsForCombinedParallelRegion = false;
396 for (const OMPClause *C : Clauses) {
397 if (!isOpenMPPrivate(C->getClauseKind()) ||
398 C->getClauseKind() == OMPC_reduction ||
399 C->getClauseKind() == OMPC_linear ||
400 C->getClauseKind() == OMPC_private)
401 continue;
402 ArrayRef<const Expr *> Vars;
403 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
404 Vars = PC->getVarRefs();
405 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
406 Vars = PC->getVarRefs();
407 else
408 llvm_unreachable("Unexpected clause.");
409 for (const auto *E : Vars) {
410 const Decl *D =
411 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
412 if (D == VD->getCanonicalDecl()) {
413 IsForCombinedParallelRegion = true;
414 break;
415 }
416 }
417 if (IsForCombinedParallelRegion)
418 break;
419 }
420 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000421 markAsEscaped(VD);
422 if (isa<OMPCapturedExprDecl>(VD))
423 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000424 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000425 }
426 }
427 }
428
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000429 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000430 assert(!GlobalizedRD &&
431 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000432 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000433 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000434 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
435 else
436 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000437 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000438 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000439 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000440 }
441
442public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000443 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
444 ArrayRef<const ValueDecl *> TeamsReductions)
445 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
446 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000447 virtual ~CheckVarsEscapingDeclContext() = default;
448 void VisitDeclStmt(const DeclStmt *S) {
449 if (!S)
450 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000451 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000452 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
453 VisitValueDecl(VD);
454 }
455 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
456 if (!D)
457 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000458 if (!D->hasAssociatedStmt())
459 return;
460 if (const auto *S =
461 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
462 // Do not analyze directives that do not actually require capturing,
463 // like `omp for` or `omp simd` directives.
464 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
465 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
466 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
467 VisitStmt(S->getCapturedStmt());
468 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000469 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000470 VisitOpenMPCapturedStmt(
471 S, D->clauses(),
472 CaptureRegions.back() == OMPD_parallel &&
473 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000474 }
475 }
476 void VisitCapturedStmt(const CapturedStmt *S) {
477 if (!S)
478 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000479 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000480 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
481 const ValueDecl *VD = C.getCapturedVar();
482 markAsEscaped(VD);
483 if (isa<OMPCapturedExprDecl>(VD))
484 VisitValueDecl(VD);
485 }
486 }
487 }
488 void VisitLambdaExpr(const LambdaExpr *E) {
489 if (!E)
490 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000491 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000492 if (C.capturesVariable()) {
493 if (C.getCaptureKind() == LCK_ByRef) {
494 const ValueDecl *VD = C.getCapturedVar();
495 markAsEscaped(VD);
496 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
497 VisitValueDecl(VD);
498 }
499 }
500 }
501 }
502 void VisitBlockExpr(const BlockExpr *E) {
503 if (!E)
504 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000505 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000506 if (C.isByRef()) {
507 const VarDecl *VD = C.getVariable();
508 markAsEscaped(VD);
509 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
510 VisitValueDecl(VD);
511 }
512 }
513 }
514 void VisitCallExpr(const CallExpr *E) {
515 if (!E)
516 return;
517 for (const Expr *Arg : E->arguments()) {
518 if (!Arg)
519 continue;
520 if (Arg->isLValue()) {
521 const bool SavedAllEscaped = AllEscaped;
522 AllEscaped = true;
523 Visit(Arg);
524 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000525 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000526 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000527 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000528 }
529 Visit(E->getCallee());
530 }
531 void VisitDeclRefExpr(const DeclRefExpr *E) {
532 if (!E)
533 return;
534 const ValueDecl *VD = E->getDecl();
535 if (AllEscaped)
536 markAsEscaped(VD);
537 if (isa<OMPCapturedExprDecl>(VD))
538 VisitValueDecl(VD);
539 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
540 if (VarD->isInitCapture())
541 VisitValueDecl(VD);
542 }
543 void VisitUnaryOperator(const UnaryOperator *E) {
544 if (!E)
545 return;
546 if (E->getOpcode() == UO_AddrOf) {
547 const bool SavedAllEscaped = AllEscaped;
548 AllEscaped = true;
549 Visit(E->getSubExpr());
550 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000551 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000552 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000553 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000554 }
555 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
556 if (!E)
557 return;
558 if (E->getCastKind() == CK_ArrayToPointerDecay) {
559 const bool SavedAllEscaped = AllEscaped;
560 AllEscaped = true;
561 Visit(E->getSubExpr());
562 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000563 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000564 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000565 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000566 }
567 void VisitExpr(const Expr *E) {
568 if (!E)
569 return;
570 bool SavedAllEscaped = AllEscaped;
571 if (!E->isLValue())
572 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000573 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000574 if (Child)
575 Visit(Child);
576 AllEscaped = SavedAllEscaped;
577 }
578 void VisitStmt(const Stmt *S) {
579 if (!S)
580 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000581 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000582 if (Child)
583 Visit(Child);
584 }
585
Alexey Bataevc99042b2018-03-15 18:10:54 +0000586 /// Returns the record that handles all the escaped local variables and used
587 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000588 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000589 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000590 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000591 return GlobalizedRD;
592 }
593
Alexey Bataevc99042b2018-03-15 18:10:54 +0000594 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000595 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
596 assert(GlobalizedRD &&
597 "Record for globalized variables must be generated already.");
598 auto I = MappedDeclsFields.find(VD);
599 if (I == MappedDeclsFields.end())
600 return nullptr;
601 return I->getSecond();
602 }
603
Alexey Bataevc99042b2018-03-15 18:10:54 +0000604 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000605 ArrayRef<const ValueDecl *> getEscapedDecls() const {
606 return EscapedDecls.getArrayRef();
607 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000608
609 /// Checks if the escaped local variable is actually a parameter passed by
610 /// value.
611 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
612 return EscapedParameters;
613 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000614
615 /// Returns the list of the escaped variables with the variably modified
616 /// types.
617 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
618 return EscapedVariableLengthDecls.getArrayRef();
619 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000620};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000621} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000622
623/// Get the GPU warp size.
624static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000625 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000627 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000628 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000629}
630
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000631/// Get the id of the current thread on the GPU.
632static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000633 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000634 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000635 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000636 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000637}
638
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000639/// Get the id of the warp in the block.
640/// We assume that the warp size is 32, which is always the case
641/// on the NVPTX device, to generate more efficient code.
642static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
643 CGBuilderTy &Bld = CGF.Builder;
644 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
645}
646
647/// Get the id of the current lane in the Warp.
648/// We assume that the warp size is 32, which is always the case
649/// on the NVPTX device, to generate more efficient code.
650static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
651 CGBuilderTy &Bld = CGF.Builder;
652 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
653 "nvptx_lane_id");
654}
655
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000656/// Get the maximum number of threads in a block of the GPU.
657static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000658 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000659 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000660 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000661 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000662}
663
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000664/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000665/// For the 'generic' execution mode, the runtime encodes thread_limit in
666/// the launch parameters, always starting thread_limit+warpSize threads per
667/// CTA. The threads in the last warp are reserved for master execution.
668/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
669static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000670 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000671 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000672 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000673 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000674 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
675 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000676}
677
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000678/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000679/// The master thread id is the first thread (lane) of the last warp in the
680/// GPU block. Warp size is assumed to be some power of 2.
681/// Thread id is 0 indexed.
682/// E.g: If NumThreads is 33, master id is 32.
683/// If NumThreads is 64, master id is 32.
684/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000685static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000686 CGBuilderTy &Bld = CGF.Builder;
687 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
688
689 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000690 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691
Alexey Bataeve290ec02018-04-06 16:03:36 +0000692 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000693 Bld.CreateNot(Mask), "master_tid");
694}
695
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000696CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000697 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000698 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
699 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000700 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000701}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000702
703void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
704 CodeGenModule &CGM) {
705 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000706
707 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000708 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000709 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000710 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000711 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000712}
713
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000714CGOpenMPRuntimeNVPTX::ExecutionMode
715CGOpenMPRuntimeNVPTX::getExecutionMode() const {
716 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000717}
718
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000719static CGOpenMPRuntimeNVPTX::DataSharingMode
720getDataSharingMode(CodeGenModule &CGM) {
721 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
722 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000723}
724
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000725/// Check for inner (nested) SPMD construct, if any
726static bool hasNestedSPMDDirective(ASTContext &Ctx,
727 const OMPExecutableDirective &D) {
728 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000729 const auto *Body =
730 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000731 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000732
Alexey Bataev5c427362019-04-10 19:11:33 +0000733 if (const auto *NestedDir =
734 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000735 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000736 switch (D.getDirectiveKind()) {
737 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000738 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000740 if (DKind == OMPD_teams) {
741 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
742 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000743 if (!Body)
744 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000745 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
746 if (const auto *NND =
747 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000748 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000749 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000750 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000751 }
752 }
753 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000754 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000755 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000756 case OMPD_target_simd:
757 case OMPD_target_parallel:
758 case OMPD_target_parallel_for:
759 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000760 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000761 case OMPD_target_teams_distribute_simd:
762 case OMPD_target_teams_distribute_parallel_for:
763 case OMPD_target_teams_distribute_parallel_for_simd:
764 case OMPD_parallel:
765 case OMPD_for:
766 case OMPD_parallel_for:
cchen47d60942019-12-05 13:43:48 -0500767 case OMPD_parallel_master:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000768 case OMPD_parallel_sections:
769 case OMPD_for_simd:
770 case OMPD_parallel_for_simd:
771 case OMPD_cancel:
772 case OMPD_cancellation_point:
773 case OMPD_ordered:
774 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000775 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000776 case OMPD_task:
777 case OMPD_simd:
778 case OMPD_sections:
779 case OMPD_section:
780 case OMPD_single:
781 case OMPD_master:
782 case OMPD_critical:
783 case OMPD_taskyield:
784 case OMPD_barrier:
785 case OMPD_taskwait:
786 case OMPD_taskgroup:
787 case OMPD_atomic:
788 case OMPD_flush:
Alexey Bataevc112e942020-02-28 09:52:15 -0500789 case OMPD_depobj:
Alexey Bataevfcba7c32020-03-20 07:03:01 -0400790 case OMPD_scan:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000791 case OMPD_teams:
792 case OMPD_target_data:
793 case OMPD_target_exit_data:
794 case OMPD_target_enter_data:
795 case OMPD_distribute:
796 case OMPD_distribute_simd:
797 case OMPD_distribute_parallel_for:
798 case OMPD_distribute_parallel_for_simd:
799 case OMPD_teams_distribute:
800 case OMPD_teams_distribute_simd:
801 case OMPD_teams_distribute_parallel_for:
802 case OMPD_teams_distribute_parallel_for_simd:
803 case OMPD_target_update:
804 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000805 case OMPD_declare_variant:
Johannes Doerfert095cecb2020-02-20 19:50:47 -0600806 case OMPD_begin_declare_variant:
807 case OMPD_end_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000808 case OMPD_declare_target:
809 case OMPD_end_declare_target:
810 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000811 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000812 case OMPD_taskloop:
813 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000814 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +0000815 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000816 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -0400817 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000818 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 case OMPD_unknown:
820 llvm_unreachable("Unexpected directive.");
821 }
822 }
823
824 return false;
825}
826
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000827static bool supportsSPMDExecutionMode(ASTContext &Ctx,
828 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000829 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
830 switch (DirectiveKind) {
831 case OMPD_target:
832 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000833 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000834 case OMPD_target_parallel:
835 case OMPD_target_parallel_for:
836 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000837 case OMPD_target_teams_distribute_parallel_for:
838 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000839 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000840 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000841 return true;
842 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000843 return false;
844 case OMPD_parallel:
845 case OMPD_for:
846 case OMPD_parallel_for:
cchen47d60942019-12-05 13:43:48 -0500847 case OMPD_parallel_master:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000848 case OMPD_parallel_sections:
849 case OMPD_for_simd:
850 case OMPD_parallel_for_simd:
851 case OMPD_cancel:
852 case OMPD_cancellation_point:
853 case OMPD_ordered:
854 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000855 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000856 case OMPD_task:
857 case OMPD_simd:
858 case OMPD_sections:
859 case OMPD_section:
860 case OMPD_single:
861 case OMPD_master:
862 case OMPD_critical:
863 case OMPD_taskyield:
864 case OMPD_barrier:
865 case OMPD_taskwait:
866 case OMPD_taskgroup:
867 case OMPD_atomic:
868 case OMPD_flush:
Alexey Bataevc112e942020-02-28 09:52:15 -0500869 case OMPD_depobj:
Alexey Bataevfcba7c32020-03-20 07:03:01 -0400870 case OMPD_scan:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_teams:
872 case OMPD_target_data:
873 case OMPD_target_exit_data:
874 case OMPD_target_enter_data:
875 case OMPD_distribute:
876 case OMPD_distribute_simd:
877 case OMPD_distribute_parallel_for:
878 case OMPD_distribute_parallel_for_simd:
879 case OMPD_teams_distribute:
880 case OMPD_teams_distribute_simd:
881 case OMPD_teams_distribute_parallel_for:
882 case OMPD_teams_distribute_parallel_for_simd:
883 case OMPD_target_update:
884 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000885 case OMPD_declare_variant:
Johannes Doerfert095cecb2020-02-20 19:50:47 -0600886 case OMPD_begin_declare_variant:
887 case OMPD_end_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000888 case OMPD_declare_target:
889 case OMPD_end_declare_target:
890 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000891 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000892 case OMPD_taskloop:
893 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000894 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +0000895 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000896 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -0400897 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000898 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000899 case OMPD_unknown:
900 break;
901 }
902 llvm_unreachable(
903 "Unknown programming model for OpenMP directive on NVPTX target.");
904}
905
906/// Check if the directive is loops based and has schedule clause at all or has
907/// static scheduling.
908static bool hasStaticScheduling(const OMPExecutableDirective &D) {
909 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
910 isOpenMPLoopDirective(D.getDirectiveKind()) &&
911 "Expected loop-based directive.");
912 return !D.hasClausesOfKind<OMPOrderedClause>() &&
913 (!D.hasClausesOfKind<OMPScheduleClause>() ||
914 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
915 [](const OMPScheduleClause *C) {
916 return C->getScheduleKind() == OMPC_SCHEDULE_static;
917 }));
918}
919
920/// Check for inner (nested) lightweight runtime construct, if any
921static bool hasNestedLightweightDirective(ASTContext &Ctx,
922 const OMPExecutableDirective &D) {
923 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
924 const auto *CS = D.getInnermostCapturedStmt();
925 const auto *Body =
926 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000927 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000928
Alexey Bataev5c427362019-04-10 19:11:33 +0000929 if (const auto *NestedDir =
930 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000931 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
932 switch (D.getDirectiveKind()) {
933 case OMPD_target:
934 if (isOpenMPParallelDirective(DKind) &&
935 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
936 hasStaticScheduling(*NestedDir))
937 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000938 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
939 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000940 if (DKind == OMPD_parallel) {
941 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
942 /*IgnoreCaptured=*/true);
943 if (!Body)
944 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000945 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
946 if (const auto *NND =
947 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000948 DKind = NND->getDirectiveKind();
949 if (isOpenMPWorksharingDirective(DKind) &&
950 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
951 return true;
952 }
953 } else if (DKind == OMPD_teams) {
954 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
955 /*IgnoreCaptured=*/true);
956 if (!Body)
957 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000958 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
959 if (const auto *NND =
960 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000961 DKind = NND->getDirectiveKind();
962 if (isOpenMPParallelDirective(DKind) &&
963 isOpenMPWorksharingDirective(DKind) &&
964 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
965 return true;
966 if (DKind == OMPD_parallel) {
967 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
968 /*IgnoreCaptured=*/true);
969 if (!Body)
970 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000971 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
972 if (const auto *NND =
973 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000974 DKind = NND->getDirectiveKind();
975 if (isOpenMPWorksharingDirective(DKind) &&
976 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
977 return true;
978 }
979 }
980 }
981 }
982 return false;
983 case OMPD_target_teams:
984 if (isOpenMPParallelDirective(DKind) &&
985 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
986 hasStaticScheduling(*NestedDir))
987 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000988 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
989 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000990 if (DKind == OMPD_parallel) {
991 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
992 /*IgnoreCaptured=*/true);
993 if (!Body)
994 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000995 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
996 if (const auto *NND =
997 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000998 DKind = NND->getDirectiveKind();
999 if (isOpenMPWorksharingDirective(DKind) &&
1000 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1001 return true;
1002 }
1003 }
1004 return false;
1005 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +00001006 if (DKind == OMPD_simd)
1007 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001008 return isOpenMPWorksharingDirective(DKind) &&
1009 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1010 case OMPD_target_teams_distribute:
1011 case OMPD_target_simd:
1012 case OMPD_target_parallel_for:
1013 case OMPD_target_parallel_for_simd:
1014 case OMPD_target_teams_distribute_simd:
1015 case OMPD_target_teams_distribute_parallel_for:
1016 case OMPD_target_teams_distribute_parallel_for_simd:
1017 case OMPD_parallel:
1018 case OMPD_for:
1019 case OMPD_parallel_for:
cchen47d60942019-12-05 13:43:48 -05001020 case OMPD_parallel_master:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001021 case OMPD_parallel_sections:
1022 case OMPD_for_simd:
1023 case OMPD_parallel_for_simd:
1024 case OMPD_cancel:
1025 case OMPD_cancellation_point:
1026 case OMPD_ordered:
1027 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001028 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001029 case OMPD_task:
1030 case OMPD_simd:
1031 case OMPD_sections:
1032 case OMPD_section:
1033 case OMPD_single:
1034 case OMPD_master:
1035 case OMPD_critical:
1036 case OMPD_taskyield:
1037 case OMPD_barrier:
1038 case OMPD_taskwait:
1039 case OMPD_taskgroup:
1040 case OMPD_atomic:
1041 case OMPD_flush:
Alexey Bataevc112e942020-02-28 09:52:15 -05001042 case OMPD_depobj:
Alexey Bataevfcba7c32020-03-20 07:03:01 -04001043 case OMPD_scan:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001044 case OMPD_teams:
1045 case OMPD_target_data:
1046 case OMPD_target_exit_data:
1047 case OMPD_target_enter_data:
1048 case OMPD_distribute:
1049 case OMPD_distribute_simd:
1050 case OMPD_distribute_parallel_for:
1051 case OMPD_distribute_parallel_for_simd:
1052 case OMPD_teams_distribute:
1053 case OMPD_teams_distribute_simd:
1054 case OMPD_teams_distribute_parallel_for:
1055 case OMPD_teams_distribute_parallel_for_simd:
1056 case OMPD_target_update:
1057 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001058 case OMPD_declare_variant:
Johannes Doerfert095cecb2020-02-20 19:50:47 -06001059 case OMPD_begin_declare_variant:
1060 case OMPD_end_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001061 case OMPD_declare_target:
1062 case OMPD_end_declare_target:
1063 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001064 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001065 case OMPD_taskloop:
1066 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001067 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00001068 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001069 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -04001070 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001071 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001072 case OMPD_unknown:
1073 llvm_unreachable("Unexpected directive.");
1074 }
1075 }
1076
1077 return false;
1078}
1079
1080/// Checks if the construct supports lightweight runtime. It must be SPMD
1081/// construct + inner loop-based construct with static scheduling.
1082static bool supportsLightweightRuntime(ASTContext &Ctx,
1083 const OMPExecutableDirective &D) {
1084 if (!supportsSPMDExecutionMode(Ctx, D))
1085 return false;
1086 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1087 switch (DirectiveKind) {
1088 case OMPD_target:
1089 case OMPD_target_teams:
1090 case OMPD_target_parallel:
1091 return hasNestedLightweightDirective(Ctx, D);
1092 case OMPD_target_parallel_for:
1093 case OMPD_target_parallel_for_simd:
1094 case OMPD_target_teams_distribute_parallel_for:
1095 case OMPD_target_teams_distribute_parallel_for_simd:
1096 // (Last|First)-privates must be shared in parallel region.
1097 return hasStaticScheduling(D);
1098 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001099 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001100 return true;
1101 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001102 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001103 case OMPD_parallel:
1104 case OMPD_for:
1105 case OMPD_parallel_for:
cchen47d60942019-12-05 13:43:48 -05001106 case OMPD_parallel_master:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001107 case OMPD_parallel_sections:
1108 case OMPD_for_simd:
1109 case OMPD_parallel_for_simd:
1110 case OMPD_cancel:
1111 case OMPD_cancellation_point:
1112 case OMPD_ordered:
1113 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001114 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001115 case OMPD_task:
1116 case OMPD_simd:
1117 case OMPD_sections:
1118 case OMPD_section:
1119 case OMPD_single:
1120 case OMPD_master:
1121 case OMPD_critical:
1122 case OMPD_taskyield:
1123 case OMPD_barrier:
1124 case OMPD_taskwait:
1125 case OMPD_taskgroup:
1126 case OMPD_atomic:
1127 case OMPD_flush:
Alexey Bataevc112e942020-02-28 09:52:15 -05001128 case OMPD_depobj:
Alexey Bataevfcba7c32020-03-20 07:03:01 -04001129 case OMPD_scan:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001130 case OMPD_teams:
1131 case OMPD_target_data:
1132 case OMPD_target_exit_data:
1133 case OMPD_target_enter_data:
1134 case OMPD_distribute:
1135 case OMPD_distribute_simd:
1136 case OMPD_distribute_parallel_for:
1137 case OMPD_distribute_parallel_for_simd:
1138 case OMPD_teams_distribute:
1139 case OMPD_teams_distribute_simd:
1140 case OMPD_teams_distribute_parallel_for:
1141 case OMPD_teams_distribute_parallel_for_simd:
1142 case OMPD_target_update:
1143 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001144 case OMPD_declare_variant:
Johannes Doerfert095cecb2020-02-20 19:50:47 -06001145 case OMPD_begin_declare_variant:
1146 case OMPD_end_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001147 case OMPD_declare_target:
1148 case OMPD_end_declare_target:
1149 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001150 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001151 case OMPD_taskloop:
1152 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001153 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00001154 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001155 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -04001156 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001157 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001158 case OMPD_unknown:
1159 break;
1160 }
1161 llvm_unreachable(
1162 "Unknown programming model for OpenMP directive on NVPTX target.");
1163}
1164
1165void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001166 StringRef ParentName,
1167 llvm::Function *&OutlinedFn,
1168 llvm::Constant *&OutlinedFnID,
1169 bool IsOffloadEntry,
1170 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001171 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001172 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001173 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001174 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001175 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001176
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001177 // Emit target region as a standalone region.
1178 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001179 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1180 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001181
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001183 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001185 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001186 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001187 auto &RT =
1188 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001189 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1190 // Skip target region initialization.
1191 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192 }
1193 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001194 auto &RT =
1195 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001196 RT.clearLocThreadIdInsertPt(CGF);
1197 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001199 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001200 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001201 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001202 // Reserve place for the globalized memory.
1203 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001204 if (!KernelStaticGlobalized) {
1205 KernelStaticGlobalized = new llvm::GlobalVariable(
1206 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1207 llvm::GlobalValue::InternalLinkage,
1208 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1209 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1210 llvm::GlobalValue::NotThreadLocal,
1211 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1212 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1214 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001215 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001216
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217 // Now change the name of the worker function to correspond to this target
1218 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001219 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001220
1221 // Create the worker function
1222 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001223}
1224
1225// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001226void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227 EntryFunctionState &EST,
1228 WorkerFunctionState &WST) {
1229 CGBuilderTy &Bld = CGF.Builder;
1230
1231 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1232 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1233 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1234 EST.ExitBB = CGF.createBasicBlock(".exit");
1235
Alexey Bataev9ff80832018-04-16 20:16:21 +00001236 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001237 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1238 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1239
1240 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001241 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001242 CGF.EmitBranch(EST.ExitBB);
1243
1244 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001245 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001246 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1247 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1248
1249 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001250 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001251 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001252 // First action in sequential region:
1253 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001254 // TODO: Optimize runtime initialization and pass in correct value.
1255 llvm::Value *Args[] = {getThreadLimit(CGF),
1256 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001257 CGF.EmitRuntimeCall(
1258 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001259
1260 // For data sharing, we need to initialize the stack.
1261 CGF.EmitRuntimeCall(
1262 createNVPTXRuntimeFunction(
1263 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1264
Alexey Bataevc99042b2018-03-15 18:10:54 +00001265 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001266}
1267
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001268void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001269 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001270 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001271 if (!CGF.HaveInsertPoint())
1272 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001273
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001274 emitGenericVarsEpilog(CGF);
1275
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001276 if (!EST.ExitBB)
1277 EST.ExitBB = CGF.createBasicBlock(".exit");
1278
1279 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1280 CGF.EmitBranch(TerminateBB);
1281
1282 CGF.EmitBlock(TerminateBB);
1283 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001284 // TODO: Optimize runtime initialization and pass in correct value.
1285 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001286 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001287 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001288 // Barrier to terminate worker threads.
1289 syncCTAThreads(CGF);
1290 // Master thread jumps to exit point.
1291 CGF.EmitBranch(EST.ExitBB);
1292
1293 CGF.EmitBlock(EST.ExitBB);
1294 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001295}
1296
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001297void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001298 StringRef ParentName,
1299 llvm::Function *&OutlinedFn,
1300 llvm::Constant *&OutlinedFnID,
1301 bool IsOffloadEntry,
1302 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001303 ExecutionRuntimeModesRAII ModeRAII(
1304 CurrentExecutionMode, RequiresFullRuntime,
1305 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1306 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001307 EntryFunctionState EST;
1308
1309 // Emit target region as a standalone region.
1310 class NVPTXPrePostActionTy : public PrePostActionTy {
1311 CGOpenMPRuntimeNVPTX &RT;
1312 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1313 const OMPExecutableDirective &D;
1314
1315 public:
1316 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1317 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1318 const OMPExecutableDirective &D)
1319 : RT(RT), EST(EST), D(D) {}
1320 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001321 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001322 // Skip target region initialization.
1323 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001324 }
1325 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001326 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001327 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001328 }
1329 } Action(*this, EST, D);
1330 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001331 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001332 // Reserve place for the globalized memory.
1333 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001334 if (!KernelStaticGlobalized) {
1335 KernelStaticGlobalized = new llvm::GlobalVariable(
1336 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1337 llvm::GlobalValue::InternalLinkage,
1338 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1339 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1340 llvm::GlobalValue::NotThreadLocal,
1341 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1342 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001343 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1344 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001345 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001346}
1347
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001348void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001349 CodeGenFunction &CGF, EntryFunctionState &EST,
1350 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001351 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001352
1353 // Setup BBs in entry function.
1354 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1355 EST.ExitBB = CGF.createBasicBlock(".exit");
1356
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001357 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1358 /*RequiresOMPRuntime=*/
1359 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1360 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001361 CGF.EmitRuntimeCall(
1362 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001363
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001364 if (RequiresFullRuntime) {
1365 // For data sharing, we need to initialize the stack.
1366 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1367 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1368 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001369
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001370 CGF.EmitBranch(ExecuteBB);
1371
1372 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001373
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001374 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001375}
1376
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001377void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001378 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001379 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001380 if (!CGF.HaveInsertPoint())
1381 return;
1382
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001383 if (!EST.ExitBB)
1384 EST.ExitBB = CGF.createBasicBlock(".exit");
1385
1386 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1387 CGF.EmitBranch(OMPDeInitBB);
1388
1389 CGF.EmitBlock(OMPDeInitBB);
1390 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001391 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1392 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001393 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001394 createNVPTXRuntimeFunction(
1395 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001396 CGF.EmitBranch(EST.ExitBB);
1397
1398 CGF.EmitBlock(EST.ExitBB);
1399 EST.ExitBB = nullptr;
1400}
1401
1402// Create a unique global variable to indicate the execution mode of this target
1403// region. The execution mode is either 'generic', or 'spmd' depending on the
1404// target directive. This variable is picked up by the offload library to setup
1405// the device appropriately before kernel launch. If the execution mode is
1406// 'generic', the runtime reserves one warp for the master, otherwise, all
1407// warps participate in parallel work.
1408static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001409 bool Mode) {
1410 auto *GVMode =
1411 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1412 llvm::GlobalValue::WeakAnyLinkage,
1413 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1414 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001415 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001416}
1417
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001418void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001419 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001420
1421 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001422 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001423 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001424 emitWorkerLoop(CGF, WST);
1425 CGF.FinishFunction();
1426}
1427
1428void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1429 WorkerFunctionState &WST) {
1430 //
1431 // The workers enter this loop and wait for parallel work from the master.
1432 // When the master encounters a parallel region it sets up the work + variable
1433 // arguments, and wakes up the workers. The workers first check to see if
1434 // they are required for the parallel region, i.e., within the # of requested
1435 // parallel threads. The activated workers load the variable arguments and
1436 // execute the parallel work.
1437 //
1438
1439 CGBuilderTy &Bld = CGF.Builder;
1440
1441 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1442 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1443 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1444 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1445 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1446 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1447
1448 CGF.EmitBranch(AwaitBB);
1449
1450 // Workers wait for work from master.
1451 CGF.EmitBlock(AwaitBB);
1452 // Wait for parallel work
1453 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001454
1455 Address WorkFn =
1456 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1457 Address ExecStatus =
1458 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1459 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1460 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1461
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001462 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001463 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001464 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001465 llvm::Value *Ret = CGF.EmitRuntimeCall(
1466 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1467 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001468
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001469 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001470 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1471 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001472 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1473
1474 // Activate requested workers.
1475 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001476 llvm::Value *IsActive =
1477 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1478 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001479
1480 // Signal start of parallel region.
1481 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001482 // Skip initialization.
1483 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001484
1485 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001486 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001487 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001488 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001489
1490 llvm::Value *WorkFnMatch =
1491 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1492
1493 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1494 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1495 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1496
1497 // Execute this outlined function.
1498 CGF.EmitBlock(ExecuteFNBB);
1499
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001500 // Insert call to work function via shared wrapper. The shared
1501 // wrapper takes two arguments:
1502 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001503 // - the thread ID;
1504 emitCall(CGF, WST.Loc, W,
1505 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001506
1507 // Go to end of parallel region.
1508 CGF.EmitBranch(TerminateBB);
1509
1510 CGF.EmitBlock(CheckNextBB);
1511 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001512 // Default case: call to outlined function through pointer if the target
1513 // region makes a declare target call that may contain an orphaned parallel
1514 // directive.
1515 auto *ParallelFnTy =
1516 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001517 /*isVarArg=*/false);
1518 llvm::Value *WorkFnCast =
1519 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001520 // Insert call to work function via shared wrapper. The shared
1521 // wrapper takes two arguments:
1522 // - the parallelism level;
1523 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001524 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001525 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1526 // Go to end of parallel region.
1527 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001528
1529 // Signal end of parallel region.
1530 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001531 CGF.EmitRuntimeCall(
1532 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1533 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001534 CGF.EmitBranch(BarrierBB);
1535
1536 // All active and inactive workers wait at a barrier after parallel region.
1537 CGF.EmitBlock(BarrierBB);
1538 // Barrier after parallel region.
1539 syncCTAThreads(CGF);
1540 CGF.EmitBranch(AwaitBB);
1541
1542 // Exit target region.
1543 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001544 // Skip initialization.
1545 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001546}
1547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001548/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001549/// implementation. Specialized for the NVPTX device.
1550/// \param Function OpenMP runtime function.
1551/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001552llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001553CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001554 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001555 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1556 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001557 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1558 // RequiresOMPRuntime);
1559 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001560 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1562 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1563 break;
1564 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001565 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001566 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1567 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001568 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001569 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1571 break;
1572 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001573 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1574 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001575 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001576 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001577 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001578 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1580 break;
1581 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001582 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1583 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1584 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001585 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001586 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001588 break;
1589 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001590 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1591 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001592 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001593 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001594 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001595 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1596 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1597 break;
1598 }
1599 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001600 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1601 /// int16_t IsOMPRuntimeInitialized);
1602 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001603 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001604 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001605 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1606 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1607 break;
1608 }
1609 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1610 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001611 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001612 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1614 break;
1615 }
1616 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1617 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1618 // global_tid);
1619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001620 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001621 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1622 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1623 break;
1624 }
1625 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1626 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1627 // global_tid);
1628 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001629 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001630 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1631 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1632 break;
1633 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001634 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1635 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1636 // int16_t lane_offset, int16_t warp_size);
1637 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001638 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001639 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1641 break;
1642 }
1643 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1644 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1645 // int16_t lane_offset, int16_t warp_size);
1646 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001647 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001648 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1650 break;
1651 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001652 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001653 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1654 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1655 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1656 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1657 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001658 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1659 CGM.Int16Ty, CGM.Int16Ty};
1660 auto *ShuffleReduceFnTy =
1661 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1662 /*isVarArg=*/false);
1663 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1664 auto *InterWarpCopyFnTy =
1665 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1666 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001667 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1668 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001669 CGM.Int32Ty,
1670 CGM.SizeTy,
1671 CGM.VoidPtrTy,
1672 ShuffleReduceFnTy->getPointerTo(),
1673 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001674 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001675 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1676 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001677 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001678 break;
1679 }
1680 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1681 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1682 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001683 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001684 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1685 RTLFn = CGM.CreateRuntimeFunction(
1686 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1687 break;
1688 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001689 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1690 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1691 // global_tid, void *global_buffer, int32_t num_of_records, void*
1692 // reduce_data,
1693 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1694 // lane_offset, int16_t shortCircuit),
1695 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1696 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1697 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1698 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1699 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1700 // *buffer, int idx, void *reduce_data));
1701 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1702 CGM.Int16Ty, CGM.Int16Ty};
1703 auto *ShuffleReduceFnTy =
1704 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1705 /*isVarArg=*/false);
1706 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1707 auto *InterWarpCopyFnTy =
1708 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1709 /*isVarArg=*/false);
1710 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1711 CGM.VoidPtrTy};
1712 auto *GlobalListFnTy =
1713 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1714 /*isVarArg=*/false);
1715 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1716 CGM.Int32Ty,
1717 CGM.VoidPtrTy,
1718 CGM.Int32Ty,
1719 CGM.VoidPtrTy,
1720 ShuffleReduceFnTy->getPointerTo(),
1721 InterWarpCopyFnTy->getPointerTo(),
1722 GlobalListFnTy->getPointerTo(),
1723 GlobalListFnTy->getPointerTo(),
1724 GlobalListFnTy->getPointerTo(),
1725 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001726 auto *FnTy =
1727 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1728 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001729 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001730 break;
1731 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001732 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1733 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001734 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001735 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1736 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1737 break;
1738 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001739 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1740 /// Build void __kmpc_data_sharing_init_stack_spmd();
1741 auto *FnTy =
1742 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001743 RTLFn =
1744 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001745 break;
1746 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001747 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1748 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001749 // int16_t UseSharedMemory);
1750 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001751 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001752 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1753 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001754 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001755 break;
1756 }
1757 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1758 // Build void __kmpc_data_sharing_pop_stack(void *a);
1759 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001760 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001761 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1763 /*Name=*/"__kmpc_data_sharing_pop_stack");
1764 break;
1765 }
1766 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1767 /// Build void __kmpc_begin_sharing_variables(void ***args,
1768 /// size_t n_args);
1769 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001770 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1773 break;
1774 }
1775 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1776 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001777 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001778 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1780 break;
1781 }
1782 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1783 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1784 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001785 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1788 break;
1789 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001790 case OMPRTL_NVPTX__kmpc_parallel_level: {
1791 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1792 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1793 auto *FnTy =
1794 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1795 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1796 break;
1797 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001798 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1799 // Build int8_t __kmpc_is_spmd_exec_mode();
1800 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1801 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1802 break;
1803 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001804 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001805 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1806 // const void *buf, size_t size, int16_t is_shared, const void **res);
1807 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1808 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001809 auto *FnTy =
1810 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1811 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1812 break;
1813 }
1814 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001815 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1816 // int16_t is_shared);
1817 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001818 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001819 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001820 RTLFn =
1821 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1822 break;
1823 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001824 case OMPRTL__kmpc_barrier: {
1825 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1826 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1827 auto *FnTy =
1828 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Matt Arsenault40ab8ae2019-10-27 14:17:40 -07001829 RTLFn =
1830 CGM.CreateConvergentRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001831 break;
1832 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001833 case OMPRTL__kmpc_barrier_simple_spmd: {
1834 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1835 // global_tid);
1836 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1837 auto *FnTy =
1838 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Matt Arsenault40ab8ae2019-10-27 14:17:40 -07001839 RTLFn = CGM.CreateConvergentRuntimeFunction(
1840 FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
Alexey Bataeva3924b52019-01-03 16:25:35 +00001841 break;
1842 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001843 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1844 // Build int32_t __kmpc_warp_active_thread_mask(void);
1845 auto *FnTy =
1846 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
Matt Arsenault56a503b2019-10-27 15:09:49 -07001847 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001848 break;
1849 }
1850 case OMPRTL_NVPTX__kmpc_syncwarp: {
1851 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1852 auto *FnTy =
1853 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
Matt Arsenault56a503b2019-10-27 15:09:49 -07001854 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_syncwarp");
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001855 break;
1856 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001857 }
1858 return RTLFn;
1859}
1860
1861void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1862 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001863 uint64_t Size, int32_t,
1864 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001865 // TODO: Add support for global variables on the device after declare target
1866 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001867 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001868 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001869 llvm::Module &M = CGM.getModule();
1870 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001871
1872 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001873 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001874
1875 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001876 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001877 llvm::ConstantAsMetadata::get(
1878 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1879 // Append metadata to nvvm.annotations
1880 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1881}
1882
1883void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1884 const OMPExecutableDirective &D, StringRef ParentName,
1885 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001886 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001887 if (!IsOffloadEntry) // Nothing to do.
1888 return;
1889
1890 assert(!ParentName.empty() && "Invalid target region parent name!");
1891
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001892 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001893 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001894 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001895 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001896 else
1897 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1898 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001899
1900 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001901}
1902
Alexey Bataevceeaa482018-11-21 21:04:34 +00001903namespace {
1904LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1905/// Enum for accesseing the reserved_2 field of the ident_t struct.
1906enum ModeFlagsTy : unsigned {
1907 /// Bit set to 1 when in SPMD mode.
1908 KMP_IDENT_SPMD_MODE = 0x01,
1909 /// Bit set to 1 when a simplified runtime is used.
1910 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1911 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1912};
1913
1914/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1915static const ModeFlagsTy UndefinedMode =
1916 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1917} // anonymous namespace
1918
1919unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001920 switch (getExecutionMode()) {
1921 case EM_SPMD:
1922 if (requiresFullRuntime())
1923 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1924 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1925 case EM_NonSPMD:
1926 assert(requiresFullRuntime() && "Expected full runtime.");
1927 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1928 case EM_Unknown:
1929 return UndefinedMode;
1930 }
1931 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001932}
1933
Alexey Bataevc2cd2d42019-10-10 17:28:10 +00001934bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1935 const GlobalDecl &OldGD,
1936 llvm::GlobalValue *OrigAddr,
1937 bool IsForDefinition) {
1938 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1939 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1940 if (NewFD->isDefined()) {
1941 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1942 return true;
1943 }
1944 return false;
1945}
1946
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001947CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001948 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001949 if (!CGM.getLangOpts().OpenMPIsDevice)
1950 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001951}
Carlo Bertollic6872252016-04-04 15:55:02 +00001952
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001953void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -06001954 ProcBindKind ProcBind,
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001955 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001956 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001957 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001958 return;
1959
1960 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1961}
1962
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001963void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1964 llvm::Value *NumThreads,
1965 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001966 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001967 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001968 return;
1969
1970 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1971}
1972
Carlo Bertollic6872252016-04-04 15:55:02 +00001973void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1974 const Expr *NumTeams,
1975 const Expr *ThreadLimit,
1976 SourceLocation Loc) {}
1977
James Y Knight9871db02019-02-05 16:42:33 +00001978llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001979 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1980 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001981 // Emit target region as a standalone region.
1982 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001983 bool &IsInParallelRegion;
1984 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001985
1986 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001987 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1988 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001989 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001990 PrevIsInParallelRegion = IsInParallelRegion;
1991 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001992 }
1993 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001994 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001995 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001996 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001997 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001998 bool PrevIsInTTDRegion = IsInTTDRegion;
1999 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002000 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
2001 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002002 auto *OutlinedFun =
2003 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
2004 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002005 if (CGM.getLangOpts().Optimize) {
2006 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2007 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2008 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2009 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002010 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00002011 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002012 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
2013 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002014 llvm::Function *WrapperFun =
2015 createParallelDataSharingWrapper(OutlinedFun, D);
2016 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
2017 }
2018
2019 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002020}
2021
Alexey Bataev2adecff2018-09-21 14:22:53 +00002022/// Get list of lastprivate variables from the teams distribute ... or
2023/// teams {distribute ...} directives.
2024static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002025getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002026 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2027 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2028 "expected teams directive.");
2029 const OMPExecutableDirective *Dir = &D;
2030 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002031 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002032 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2034 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002035 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002036 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2037 Dir = nullptr;
2038 }
2039 }
2040 if (!Dir)
2041 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002042 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002043 for (const Expr *E : C->getVarRefs())
2044 Vars.push_back(getPrivateItem(E));
2045 }
2046}
2047
2048/// Get list of reduction variables from the teams ... directives.
2049static void
2050getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2051 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2052 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2053 "expected teams directive.");
2054 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2055 for (const Expr *E : C->privates())
2056 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002057 }
2058}
2059
James Y Knight9871db02019-02-05 16:42:33 +00002060llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002061 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2062 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002063 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002064
Alexey Bataev2adecff2018-09-21 14:22:53 +00002065 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002066 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002067 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002068 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002069 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2070 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002071 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002072 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2073 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002074 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002075 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002076 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002077 }
2078 } else if (!LastPrivatesReductions.empty()) {
2079 assert(!TeamAndReductions.first &&
2080 "Previous team declaration is not expected.");
2081 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2082 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002083 }
2084
Alexey Bataevc99042b2018-03-15 18:10:54 +00002085 // Emit target region as a standalone region.
2086 class NVPTXPrePostActionTy : public PrePostActionTy {
2087 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002088 const RecordDecl *GlobalizedRD;
2089 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2090 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002091
2092 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002093 NVPTXPrePostActionTy(
2094 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2095 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2096 &MappedDeclsFields)
2097 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2098 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002099 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002100 auto &Rt =
2101 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2102 if (GlobalizedRD) {
2103 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2104 I->getSecond().GlobalRecord = GlobalizedRD;
2105 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002106 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002107 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2108 for (const auto &Pair : MappedDeclsFields) {
2109 assert(Pair.getFirst()->isCanonicalDecl() &&
2110 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002111 Data.insert(std::make_pair(Pair.getFirst(),
2112 MappedVarData(Pair.getSecond(),
2113 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002114 }
2115 }
2116 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002117 }
2118 void Exit(CodeGenFunction &CGF) override {
2119 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2120 .emitGenericVarsEpilog(CGF);
2121 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002122 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2123 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002124 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002125 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002126 if (CGM.getLangOpts().Optimize) {
2127 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2128 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2129 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2130 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002131
2132 return OutlinedFun;
2133}
2134
Alexey Bataevc99042b2018-03-15 18:10:54 +00002135void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002136 SourceLocation Loc,
2137 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002138 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2139 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002140 return;
2141
Alexey Bataevc99042b2018-03-15 18:10:54 +00002142 CGBuilderTy &Bld = CGF.Builder;
2143
2144 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2145 if (I == FunctionGlobalizedDecls.end())
2146 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002147 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002148 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002149 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002150
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002151 // Recover pointer to this function's global record. The runtime will
2152 // handle the specifics of the allocation of the memory.
2153 // Use actual memory size of the record including the padding
2154 // for alignment purposes.
2155 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002156 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002157 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002158 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002159 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002160
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002161 llvm::PointerType *GlobalRecPtrTy =
2162 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002163 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002164 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002165 if (!IsInTTDRegion &&
2166 (WithSPMDCheck ||
2167 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002168 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2169 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2170 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002171 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2172 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2173 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2174 llvm::Value *PL = CGF.EmitRuntimeCall(
2175 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2176 {RTLoc, ThreadID});
2177 IsTTD = Bld.CreateIsNull(PL);
2178 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002179 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2180 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2181 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2182 // There is no need to emit line number for unconditional branch.
2183 (void)ApplyDebugLocation::CreateEmpty(CGF);
2184 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002185 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2186 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002187 CGF.EmitBranch(ExitBB);
2188 // There is no need to emit line number for unconditional branch.
2189 (void)ApplyDebugLocation::CreateEmpty(CGF);
2190 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002191 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2192 if (const RecordDecl *SecGlobalizedVarsRecord =
2193 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2194 SecGlobalRecTy =
2195 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2196
2197 // Recover pointer to this function's global record. The runtime will
2198 // handle the specifics of the allocation of the memory.
2199 // Use actual memory size of the record including the padding
2200 // for alignment purposes.
2201 unsigned Alignment =
2202 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2203 unsigned GlobalRecordSize =
2204 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2205 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2206 Size = Bld.CreateSelect(
2207 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2208 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002209 // TODO: allow the usage of shared memory to be controlled by
2210 // the user, for now, default to global.
2211 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002212 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002213 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2214 createNVPTXRuntimeFunction(
2215 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2216 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002217 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002218 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002219 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002220 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002221 /*NumReservedValues=*/2, "_select_stack");
2222 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2223 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2224 GlobalRecCastAddr = Phi;
2225 I->getSecond().GlobalRecordAddr = Phi;
2226 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002227 } else if (IsInTTDRegion) {
2228 assert(GlobalizedRecords.back().Records.size() < 2 &&
2229 "Expected less than 2 globalized records: one for target and one "
2230 "for teams.");
2231 unsigned Offset = 0;
2232 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2233 QualType RDTy = CGM.getContext().getRecordType(RD);
2234 unsigned Alignment =
2235 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2236 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2237 Offset =
2238 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2239 }
2240 unsigned Alignment =
2241 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2242 Offset = llvm::alignTo(Offset, Alignment);
2243 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2244 ++GlobalizedRecords.back().RegionCounter;
2245 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002246 assert(KernelStaticGlobalized &&
2247 "Kernel static pointer must be initialized already.");
2248 auto *UseSharedMemory = new llvm::GlobalVariable(
2249 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2250 llvm::GlobalValue::InternalLinkage, nullptr,
2251 "_openmp_static_kernel$is_shared");
2252 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2253 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2254 /*DestWidth=*/16, /*Signed=*/0);
2255 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2256 Address(UseSharedMemory,
2257 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2258 /*Volatile=*/false, Int16Ty, Loc);
2259 auto *StaticGlobalized = new llvm::GlobalVariable(
2260 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002261 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002262 auto *RecSize = new llvm::GlobalVariable(
2263 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2264 llvm::GlobalValue::InternalLinkage, nullptr,
2265 "_openmp_static_kernel$size");
2266 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2267 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002268 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002269 CGM.getContext().getSizeType(), Loc);
2270 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2271 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002272 llvm::Value *GlobalRecordSizeArg[] = {
2273 llvm::ConstantInt::get(
2274 CGM.Int16Ty,
2275 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2276 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002277 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2278 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2279 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002280 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002281 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002282 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2283 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002284 }
2285 assert(KernelStaticGlobalized && "Global address must be set already.");
2286 Address FrameAddr = CGF.EmitLoadOfPointer(
2287 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2288 CGM.getContext()
2289 .getPointerType(CGM.getContext().VoidPtrTy)
2290 .castAs<PointerType>());
2291 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002292 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002293 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2294 I->getSecond().IsInSPMDModeFlag = nullptr;
2295 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2296 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002297 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002298 // TODO: allow the usage of shared memory to be controlled by
2299 // the user, for now, default to global.
2300 llvm::Value *GlobalRecordSizeArg[] = {
2301 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2302 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002303 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2304 createNVPTXRuntimeFunction(
2305 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2306 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002307 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002308 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002309 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2310 I->getSecond().IsInSPMDModeFlag = nullptr;
2311 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002312 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002313 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002314
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002315 // Emit the "global alloca" which is a GEP from the global declaration
2316 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002317 LValue SecBase;
2318 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2319 if (IsTTD) {
2320 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2321 llvm::PointerType *SecGlobalRecPtrTy =
2322 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2323 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2324 Bld.CreatePointerBitCastOrAddrSpaceCast(
2325 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2326 SecGlobalRecTy);
2327 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002328 for (auto &Rec : I->getSecond().LocalVarData) {
2329 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2330 llvm::Value *ParValue;
2331 if (EscapedParam) {
2332 const auto *VD = cast<VarDecl>(Rec.first);
2333 LValue ParLVal =
2334 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2335 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2336 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002337 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2338 // Emit VarAddr basing on lane-id if required.
2339 QualType VarTy;
2340 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002341 VarTy = Rec.second.FD->getType();
2342 } else {
2343 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002344 VarAddr.getAddress(CGF).getPointer(),
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002345 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002346 VarTy =
2347 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002348 VarAddr = CGF.MakeAddrLValue(
2349 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2350 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002351 }
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002352 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
Alexey Bataeve4090182018-11-02 14:54:07 +00002353 if (!IsInTTDRegion &&
2354 (WithSPMDCheck ||
2355 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002356 assert(I->getSecond().IsInSPMDModeFlag &&
2357 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002358 if (IsTTD) {
2359 assert(SecIt->second.IsOnePerTeam &&
2360 "Secondary glob data must be one per team.");
2361 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2362 VarAddr.setAddress(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002363 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(CGF),
2364 VarAddr.getPointer(CGF)),
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002365 VarAddr.getAlignment()));
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002366 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002367 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002368 Address GlobalPtr = Rec.second.PrivateAddr;
2369 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2370 Rec.second.PrivateAddr = Address(
2371 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2372 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2373 LocalAddr.getAlignment());
2374 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002375 if (EscapedParam) {
2376 const auto *VD = cast<VarDecl>(Rec.first);
2377 CGF.EmitStoreOfScalar(ParValue, VarAddr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002378 I->getSecond().MappedParams->setVarAddr(CGF, VD,
2379 VarAddr.getAddress(CGF));
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002380 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002381 if (IsTTD)
2382 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002383 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002384 }
2385 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2386 // Recover pointer to this function's global record. The runtime will
2387 // handle the specifics of the allocation of the memory.
2388 // Use actual memory size of the record including the padding
2389 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002390 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002391 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2392 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2393 Size = Bld.CreateNUWAdd(
2394 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2395 llvm::Value *AlignVal =
2396 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2397 Size = Bld.CreateUDiv(Size, AlignVal);
2398 Size = Bld.CreateNUWMul(Size, AlignVal);
2399 // TODO: allow the usage of shared memory to be controlled by
2400 // the user, for now, default to global.
2401 llvm::Value *GlobalRecordSizeArg[] = {
2402 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2403 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002404 createNVPTXRuntimeFunction(
2405 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002406 GlobalRecordSizeArg);
2407 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2408 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2409 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2410 CGM.getContext().getDeclAlign(VD),
2411 AlignmentSource::Decl);
2412 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002413 Base.getAddress(CGF));
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002414 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002415 }
2416 I->getSecond().MappedParams->apply(CGF);
2417}
2418
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002419void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2420 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002421 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2422 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002423 return;
2424
Alexey Bataevc99042b2018-03-15 18:10:54 +00002425 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002426 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002427 I->getSecond().MappedParams->restore(CGF);
2428 if (!CGF.HaveInsertPoint())
2429 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002430 for (llvm::Value *Addr :
2431 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2432 CGF.EmitRuntimeCall(
2433 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2434 Addr);
2435 }
2436 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002437 if (!IsInTTDRegion &&
2438 (WithSPMDCheck ||
2439 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002440 CGBuilderTy &Bld = CGF.Builder;
2441 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2442 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2443 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2444 // There is no need to emit line number for unconditional branch.
2445 (void)ApplyDebugLocation::CreateEmpty(CGF);
2446 CGF.EmitBlock(NonSPMDBB);
2447 CGF.EmitRuntimeCall(
2448 createNVPTXRuntimeFunction(
2449 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2450 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2451 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002452 } else if (IsInTTDRegion) {
2453 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2454 "region counter must be > 0.");
2455 --GlobalizedRecords.back().RegionCounter;
2456 // Emit the restore function only in the target region.
2457 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002458 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2459 /*DestWidth=*/16, /*Signed=*/0);
2460 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2461 Address(GlobalizedRecords.back().UseSharedMemory,
2462 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2463 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002464 llvm::Value *Args[] = {
2465 llvm::ConstantInt::get(
2466 CGM.Int16Ty,
2467 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2468 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002469 CGF.EmitRuntimeCall(
2470 createNVPTXRuntimeFunction(
2471 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002472 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002473 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002474 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002475 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2476 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2477 I->getSecond().GlobalRecordAddr);
2478 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002479 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002480 }
2481}
2482
Carlo Bertollic6872252016-04-04 15:55:02 +00002483void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2484 const OMPExecutableDirective &D,
2485 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002486 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002487 ArrayRef<llvm::Value *> CapturedVars) {
2488 if (!CGF.HaveInsertPoint())
2489 return;
2490
Alexey Bataevf89cf212019-10-16 16:59:01 +00002491 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2492 /*Name=*/".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002493 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2494 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002495 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002496 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2497 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002498 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002499}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002500
2501void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002502 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002503 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2504 if (!CGF.HaveInsertPoint())
2505 return;
2506
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002507 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002508 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002509 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002510 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002511}
2512
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002513void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002514 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2515 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2516 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002517
2518 // Force inline this outlined function at its call site.
2519 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2520
Alexey Bataevf89cf212019-10-16 16:59:01 +00002521 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2522 /*Name=*/".zero.addr");
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002523 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002524 // ThreadId for serialized parallels is 0.
2525 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002526 auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002527 CodeGenFunction &CGF, PrePostActionTy &Action) {
2528 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002529
Alexey Bataevf89cf212019-10-16 16:59:01 +00002530 Address ZeroAddr =
2531 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2532 /*Name=*/".bound.zero.addr");
2533 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002534 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2535 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2536 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2537 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2538 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2539 };
2540 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2541 PrePostActionTy &) {
2542
2543 RegionCodeGenTy RCG(CodeGen);
2544 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2545 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2546 llvm::Value *Args[] = {RTLoc, ThreadID};
2547
2548 NVPTXActionTy Action(
2549 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2550 Args,
2551 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2552 Args);
2553 RCG.setAction(Action);
2554 RCG(CGF);
2555 };
2556
2557 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2558 PrePostActionTy &Action) {
2559 CGBuilderTy &Bld = CGF.Builder;
2560 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2561 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002562 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2563
2564 // Prepare for parallel region. Indicate the outlined function.
2565 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002566 CGF.EmitRuntimeCall(
2567 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2568 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002569
2570 // Create a private scope that will globalize the arguments
2571 // passed from the outside of the target region.
2572 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2573
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002574 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002575 if (!CapturedVars.empty()) {
2576 // Prepare for parallel region. Indicate the outlined function.
2577 Address SharedArgs =
2578 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2579 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2580
2581 llvm::Value *DataSharingArgs[] = {
2582 SharedArgsPtr,
2583 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2584 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2585 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2586 DataSharingArgs);
2587
2588 // Store variable address in a list of references to pass to workers.
2589 unsigned Idx = 0;
2590 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002591 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2592 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2593 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002594 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002595 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002596 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002597 if (V->getType()->isIntegerTy())
2598 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2599 else
2600 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002601 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2602 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002603 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002604 }
2605 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002606
2607 // Activate workers. This barrier is used by the master to signal
2608 // work for the workers.
2609 syncCTAThreads(CGF);
2610
2611 // OpenMP [2.5, Parallel Construct, p.49]
2612 // There is an implied barrier at the end of a parallel region. After the
2613 // end of a parallel region, only the master thread of the team resumes
2614 // execution of the enclosing task region.
2615 //
2616 // The master waits at this barrier until all workers are done.
2617 syncCTAThreads(CGF);
2618
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002619 if (!CapturedVars.empty())
2620 CGF.EmitRuntimeCall(
2621 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2622
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002623 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002624 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002625 };
2626
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002627 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2628 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002629 if (IsInParallelRegion) {
2630 SeqGen(CGF, Action);
2631 } else if (IsInTargetMasterThreadRegion) {
2632 L0ParallelGen(CGF, Action);
2633 } else {
2634 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002635 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002636 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002637 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002638 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002639 // }
2640 CGBuilderTy &Bld = CGF.Builder;
2641 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002642 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2643 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002644 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002645 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2646 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002647 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002648 // There is no need to emit line number for unconditional branch.
2649 (void)ApplyDebugLocation::CreateEmpty(CGF);
2650 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002651 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2652 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2653 llvm::Value *PL = CGF.EmitRuntimeCall(
2654 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2655 {RTLoc, ThreadID});
2656 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002657 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002658 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002659 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002660 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002661 // There is no need to emit line number for unconditional branch.
2662 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002663 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002664 L0ParallelGen(CGF, Action);
2665 CGF.EmitBranch(ExitBB);
2666 // There is no need to emit line number for unconditional branch.
2667 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002668 // Emit the continuation block for code after the if.
2669 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2670 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002671 };
2672
Alexey Bataev9ff80832018-04-16 20:16:21 +00002673 if (IfCond) {
Alexey Bataev1d943ae2019-11-19 12:12:23 -05002674 emitIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002675 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002676 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002677 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002678 ThenRCG(CGF);
2679 }
2680}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002681
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002682void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002683 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002684 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2685 // Just call the outlined function to execute the parallel region.
2686 // OutlinedFn(&GTid, &zero, CapturedStruct);
2687 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002688 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002689
Alexey Bataevf89cf212019-10-16 16:59:01 +00002690 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2691 /*Name=*/".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002692 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002693 // ThreadId for serialized parallels is 0.
2694 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002695 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2696 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002697 Action.Enter(CGF);
2698
Alexey Bataevf89cf212019-10-16 16:59:01 +00002699 Address ZeroAddr =
2700 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2701 /*Name=*/".bound.zero.addr");
2702 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002703 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2704 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2705 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2706 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2707 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2708 };
2709 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2710 PrePostActionTy &) {
2711
2712 RegionCodeGenTy RCG(CodeGen);
2713 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2714 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2715 llvm::Value *Args[] = {RTLoc, ThreadID};
2716
2717 NVPTXActionTy Action(
2718 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2719 Args,
2720 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2721 Args);
2722 RCG.setAction(Action);
2723 RCG(CGF);
2724 };
2725
2726 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002727 // In the worker need to use the real thread id.
2728 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002729 RegionCodeGenTy RCG(CodeGen);
2730 RCG(CGF);
2731 } else {
2732 // If we are not in the target region, it is definitely L2 parallelism or
2733 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2734 // need to check for orphaned directives.
2735 RegionCodeGenTy RCG(SeqGen);
2736 RCG(CGF);
2737 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002738}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002739
Alexey Bataeva3924b52019-01-03 16:25:35 +00002740void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2741 // Always emit simple barriers!
2742 if (!CGF.HaveInsertPoint())
2743 return;
2744 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2745 // This function does not use parameters, so we can emit just default values.
2746 llvm::Value *Args[] = {
2747 llvm::ConstantPointerNull::get(
2748 cast<llvm::PointerType>(getIdentTyPointerTy())),
2749 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002750 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002751 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002752 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002753}
2754
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002755void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2756 SourceLocation Loc,
2757 OpenMPDirectiveKind Kind, bool,
2758 bool) {
2759 // Always emit simple barriers!
2760 if (!CGF.HaveInsertPoint())
2761 return;
2762 // Build call __kmpc_cancel_barrier(loc, thread_id);
2763 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2764 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2765 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002766 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2767 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2768 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002769}
2770
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002771void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2772 CodeGenFunction &CGF, StringRef CriticalName,
2773 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2774 const Expr *Hint) {
2775 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2776 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2777 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2778 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2779 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2780
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002781 // Get the mask of active threads in the warp.
2782 llvm::Value *Mask = CGF.EmitRuntimeCall(
2783 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002784 // Fetch team-local id of the thread.
2785 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2786
2787 // Get the width of the team.
2788 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2789
2790 // Initialize the counter variable for the loop.
2791 QualType Int32Ty =
2792 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2793 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2794 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2795 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2796 /*isInit=*/true);
2797
2798 // Block checks if loop counter exceeds upper bound.
2799 CGF.EmitBlock(LoopBB);
2800 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2801 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2802 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2803
2804 // Block tests which single thread should execute region, and which threads
2805 // should go straight to synchronisation point.
2806 CGF.EmitBlock(TestBB);
2807 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2808 llvm::Value *CmpThreadToCounter =
2809 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2810 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2811
2812 // Block emits the body of the critical region.
2813 CGF.EmitBlock(BodyBB);
2814
2815 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002816 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2817 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002818
2819 // After the body surrounded by the critical region, the single executing
2820 // thread will jump to the synchronisation point.
2821 // Block waits for all threads in current team to finish then increments the
2822 // counter variable and returns to the loop.
2823 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002824 // Reconverge active threads in the warp.
2825 (void)CGF.EmitRuntimeCall(
2826 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002827
2828 llvm::Value *IncCounterVal =
2829 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2830 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2831 CGF.EmitBranch(LoopBB);
2832
2833 // Block that is reached when all threads in the team complete the region.
2834 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2835}
2836
Alexey Bataevb2575932018-01-04 20:18:55 +00002837/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002838static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2839 QualType ValTy, QualType CastTy,
2840 SourceLocation Loc) {
2841 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2842 "Cast type must sized.");
2843 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2844 "Val type must sized.");
2845 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2846 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002847 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002848 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2849 CGF.getContext().getTypeSizeInChars(CastTy))
2850 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2851 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2852 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2853 CastTy->hasSignedIntegerRepresentation());
2854 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002855 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2856 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002857 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2858 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002859}
2860
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002861/// This function creates calls to one of two shuffle functions to copy
2862/// variables between lanes in a warp.
2863static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002864 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002865 QualType ElemType,
2866 llvm::Value *Offset,
2867 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002868 CodeGenModule &CGM = CGF.CGM;
2869 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002870 CGOpenMPRuntimeNVPTX &RT =
2871 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2872
Alexey Bataeva453f362018-03-19 17:53:56 +00002873 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2874 assert(Size.getQuantity() <= 8 &&
2875 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002876
Alexey Bataeva453f362018-03-19 17:53:56 +00002877 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002878 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2879 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2880
2881 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002882 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2883 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2884 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002885 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002886 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002887
Alexey Bataev9ff80832018-04-16 20:16:21 +00002888 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2889 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002890
Alexey Bataeva453f362018-03-19 17:53:56 +00002891 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002892}
2893
Alexey Bataev12c62902018-06-22 19:10:38 +00002894static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2895 Address DestAddr, QualType ElemType,
2896 llvm::Value *Offset, SourceLocation Loc) {
2897 CGBuilderTy &Bld = CGF.Builder;
2898
2899 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2900 // Create the loop over the big sized data.
2901 // ptr = (void*)Elem;
2902 // ptrEnd = (void*) Elem + 1;
2903 // Step = 8;
2904 // while (ptr + Step < ptrEnd)
2905 // shuffle((int64_t)*ptr);
2906 // Step = 4;
2907 // while (ptr + Step < ptrEnd)
2908 // shuffle((int32_t)*ptr);
2909 // ...
2910 Address ElemPtr = DestAddr;
2911 Address Ptr = SrcAddr;
2912 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002913 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002914 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2915 if (Size < CharUnits::fromQuantity(IntSize))
2916 continue;
2917 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2918 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2919 /*Signed=*/1);
2920 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2921 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2922 ElemPtr =
2923 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2924 if (Size.getQuantity() / IntSize > 1) {
2925 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2926 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2927 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2928 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2929 CGF.EmitBlock(PreCondBB);
2930 llvm::PHINode *PhiSrc =
2931 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2932 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2933 llvm::PHINode *PhiDest =
2934 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2935 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2936 Ptr = Address(PhiSrc, Ptr.getAlignment());
2937 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2938 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2939 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2940 Ptr.getPointer(), CGF.VoidPtrTy));
2941 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2942 ThenBB, ExitBB);
2943 CGF.EmitBlock(ThenBB);
2944 llvm::Value *Res = createRuntimeShuffleFunction(
2945 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2946 IntType, Offset, Loc);
2947 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002948 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2949 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002950 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2951 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002952 CGF.EmitBranch(PreCondBB);
2953 CGF.EmitBlock(ExitBB);
2954 } else {
2955 llvm::Value *Res = createRuntimeShuffleFunction(
2956 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2957 IntType, Offset, Loc);
2958 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002959 Ptr = Bld.CreateConstGEP(Ptr, 1);
2960 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002961 }
2962 Size = Size % IntSize;
2963 }
2964}
2965
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966namespace {
2967enum CopyAction : unsigned {
2968 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2969 // the warp using shuffle instructions.
2970 RemoteLaneToThread,
2971 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2972 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002973 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2974 ThreadToScratchpad,
2975 // ScratchpadToThread: Copy from a scratchpad array in global memory
2976 // containing team-reduced data to a thread's stack.
2977 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002978};
2979} // namespace
2980
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002981struct CopyOptionsTy {
2982 llvm::Value *RemoteLaneOffset;
2983 llvm::Value *ScratchpadIndex;
2984 llvm::Value *ScratchpadWidth;
2985};
2986
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002987/// Emit instructions to copy a Reduce list, which contains partially
2988/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002989static void emitReductionListCopy(
2990 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2991 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2992 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002993
Alexey Bataev9ff80832018-04-16 20:16:21 +00002994 CodeGenModule &CGM = CGF.CGM;
2995 ASTContext &C = CGM.getContext();
2996 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002997
Alexey Bataev9ff80832018-04-16 20:16:21 +00002998 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2999 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
3000 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003001
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003002 // Iterates, element-by-element, through the source Reduce list and
3003 // make a copy.
3004 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003005 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003006 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003007 Address SrcElementAddr = Address::invalid();
3008 Address DestElementAddr = Address::invalid();
3009 Address DestElementPtrAddr = Address::invalid();
3010 // Should we shuffle in an element from a remote lane?
3011 bool ShuffleInElement = false;
3012 // Set to true to update the pointer in the dest Reduce list to a
3013 // newly created element.
3014 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003015 // Increment the src or dest pointer to the scratchpad, for each
3016 // new element.
3017 bool IncrScratchpadSrc = false;
3018 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003019
3020 switch (Action) {
3021 case RemoteLaneToThread: {
3022 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003023 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003024 SrcElementAddr = CGF.EmitLoadOfPointer(
3025 SrcElementPtrAddr,
3026 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003027
3028 // Step 1.2: Create a temporary to store the element in the destination
3029 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003030 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003031 DestElementAddr =
3032 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3033 ShuffleInElement = true;
3034 UpdateDestListPtr = true;
3035 break;
3036 }
3037 case ThreadCopy: {
3038 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003039 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003040 SrcElementAddr = CGF.EmitLoadOfPointer(
3041 SrcElementPtrAddr,
3042 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003043
3044 // Step 1.2: Get the address for dest element. The destination
3045 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003046 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003047 DestElementAddr = CGF.EmitLoadOfPointer(
3048 DestElementPtrAddr,
3049 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003050 break;
3051 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003052 case ThreadToScratchpad: {
3053 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003054 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003055 SrcElementAddr = CGF.EmitLoadOfPointer(
3056 SrcElementPtrAddr,
3057 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003058
3059 // Step 1.2: Get the address for dest element:
3060 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003061 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003062 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003063 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003064 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003065 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003066 ScratchPadElemAbsolutePtrVal =
3067 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003068 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3069 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003070 IncrScratchpadDest = true;
3071 break;
3072 }
3073 case ScratchpadToThread: {
3074 // Step 1.1: Get the address for the src element in the scratchpad.
3075 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003076 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003077 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003078 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003079 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003080 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003081 ScratchPadElemAbsolutePtrVal =
3082 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3083 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3084 C.getTypeAlignInChars(Private->getType()));
3085 IncrScratchpadSrc = true;
3086
3087 // Step 1.2: Create a temporary to store the element in the destination
3088 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003089 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003090 DestElementAddr =
3091 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3092 UpdateDestListPtr = true;
3093 break;
3094 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003095 }
3096
3097 // Regardless of src and dest of copy, we emit the load of src
3098 // element as this is required in all directions
3099 SrcElementAddr = Bld.CreateElementBitCast(
3100 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003101 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3102 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103
3104 // Now that all active lanes have read the element in the
3105 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003106 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003107 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3108 RemoteLaneOffset, Private->getExprLoc());
3109 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003110 switch (CGF.getEvaluationKind(Private->getType())) {
3111 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003112 llvm::Value *Elem =
3113 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3114 Private->getType(), Private->getExprLoc());
3115 // Store the source element value to the dest element address.
3116 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3117 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003118 break;
3119 }
3120 case TEK_Complex: {
3121 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3122 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3123 Private->getExprLoc());
3124 CGF.EmitStoreOfComplex(
3125 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3126 /*isInit=*/false);
3127 break;
3128 }
3129 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003130 CGF.EmitAggregateCopy(
3131 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3132 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3133 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003134 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003135 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003136 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003137
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138 // Step 3.1: Modify reference in dest Reduce list as needed.
3139 // Modifying the reference in Reduce list to point to the newly
3140 // created element. The element is live in the current function
3141 // scope and that of functions it invokes (i.e., reduce_function).
3142 // RemoteReduceData[i] = (void*)&RemoteElem
3143 if (UpdateDestListPtr) {
3144 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3145 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3146 DestElementPtrAddr, /*Volatile=*/false,
3147 C.VoidPtrTy);
3148 }
3149
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003150 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3151 // address of the next element in scratchpad memory, unless we're currently
3152 // processing the last one. Memory alignment is also taken care of here.
3153 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3154 llvm::Value *ScratchpadBasePtr =
3155 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003156 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3157 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003158 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003159 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003160
3161 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003162 ScratchpadBasePtr = Bld.CreateNUWSub(
3163 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3164 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003165 ScratchpadBasePtr,
3166 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003167 ScratchpadBasePtr = Bld.CreateNUWAdd(
3168 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3169 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003170 ScratchpadBasePtr,
3171 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3172
3173 if (IncrScratchpadDest)
3174 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3175 else /* IncrScratchpadSrc = true */
3176 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3177 }
3178
Alexey Bataev9ff80832018-04-16 20:16:21 +00003179 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180 }
3181}
3182
3183/// This function emits a helper that gathers Reduce lists from the first
3184/// lane of every active warp to lanes in the first warp.
3185///
3186/// void inter_warp_copy_func(void* reduce_data, num_warps)
3187/// shared smem[warp_size];
3188/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003189/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003190/// If (I am the first lane in each warp)
3191/// Copy my local D to smem[warp_id]
3192/// sync
3193/// if (I am the first warp)
3194/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003195static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3196 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003197 QualType ReductionArrayTy,
3198 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003199 ASTContext &C = CGM.getContext();
3200 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003201
3202 // ReduceList: thread local Reduce list.
3203 // At the stage of the computation when this function is called, partially
3204 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003205 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3206 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207 // NumWarps: number of warps active in the parallel region. This could
3208 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003209 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003210 C.getIntTypeForBitwidth(32, /* Signed */ true),
3211 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003212 FunctionArgList Args;
3213 Args.push_back(&ReduceListArg);
3214 Args.push_back(&NumWarpsArg);
3215
Alexey Bataev9ff80832018-04-16 20:16:21 +00003216 const CGFunctionInfo &CGFI =
3217 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003218 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3219 llvm::GlobalValue::InternalLinkage,
3220 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003221 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003222 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003224 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003225
Alexey Bataev9ff80832018-04-16 20:16:21 +00003226 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003227
3228 // This array is used as a medium to transfer, one reduce element at a time,
3229 // the data from the first lane of every warp to lanes in the first warp
3230 // in order to perform the final step of a reduction in a parallel region
3231 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3232 // for reduced latency, as well as to have a distinct copy for concurrently
3233 // executing target regions. The array is declared with common linkage so
3234 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003235 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236 "__openmp_nvptx_data_transfer_temporary_storage";
3237 llvm::GlobalVariable *TransferMedium =
3238 M.getGlobalVariable(TransferMediumName);
3239 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003240 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3242 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003243 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003244 llvm::Constant::getNullValue(Ty), TransferMediumName,
3245 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3246 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003247 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003248 }
3249
3250 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003251 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003252 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003253 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003254 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003255 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003256
3257 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3258 Address LocalReduceList(
3259 Bld.CreatePointerBitCastOrAddrSpaceCast(
3260 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003261 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003262 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3263 CGF.getPointerAlign());
3264
3265 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003266 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267 //
3268 // Warp master copies reduce element to transfer medium in __shared__
3269 // memory.
3270 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003271 unsigned RealTySize =
3272 C.getTypeSizeInChars(Private->getType())
3273 .alignTo(C.getTypeAlignInChars(Private->getType()))
3274 .getQuantity();
3275 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3276 unsigned NumIters = RealTySize / TySize;
3277 if (NumIters == 0)
3278 continue;
3279 QualType CType = C.getIntTypeForBitwidth(
3280 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3281 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3282 CharUnits Align = CharUnits::fromQuantity(TySize);
3283 llvm::Value *Cnt = nullptr;
3284 Address CntAddr = Address::invalid();
3285 llvm::BasicBlock *PrecondBB = nullptr;
3286 llvm::BasicBlock *ExitBB = nullptr;
3287 if (NumIters > 1) {
3288 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3289 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3290 /*Volatile=*/false, C.IntTy);
3291 PrecondBB = CGF.createBasicBlock("precond");
3292 ExitBB = CGF.createBasicBlock("exit");
3293 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3294 // There is no need to emit line number for unconditional branch.
3295 (void)ApplyDebugLocation::CreateEmpty(CGF);
3296 CGF.EmitBlock(PrecondBB);
3297 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3298 llvm::Value *Cmp =
3299 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3300 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3301 CGF.EmitBlock(BodyBB);
3302 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003303 // kmpc_barrier.
3304 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3305 /*EmitChecks=*/false,
3306 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003307 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3308 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3309 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003311 // if (lane_id == 0)
3312 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3313 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3314 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003315
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003316 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003317 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003318 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3319 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3320 // elemptr = ((CopyType*)(elemptrptr)) + I
3321 Address ElemPtr = Address(ElemPtrPtr, Align);
3322 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3323 if (NumIters > 1) {
3324 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3325 ElemPtr.getAlignment());
3326 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003328 // Get pointer to location in transfer medium.
3329 // MediumPtr = &medium[warp_id]
3330 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3331 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3332 Address MediumPtr(MediumPtrVal, Align);
3333 // Casting to actual data type.
3334 // MediumPtr = (CopyType*)MediumPtrAddr;
3335 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003336
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003337 // elem = *elemptr
3338 //*MediumPtr = elem
3339 llvm::Value *Elem =
3340 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003341 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003342 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003343
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003344 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003345
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003346 CGF.EmitBlock(ElseBB);
3347 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003348
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003349 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003350
Alexey Bataevae51b962018-12-14 21:00:58 +00003351 // kmpc_barrier.
3352 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3353 /*EmitChecks=*/false,
3354 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003355
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003356 //
3357 // Warp 0 copies reduce element from transfer medium.
3358 //
3359 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3360 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3361 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003362
Alexey Bataevae51b962018-12-14 21:00:58 +00003363 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3364 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3365 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3366
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003367 // Up to 32 threads in warp 0 are active.
3368 llvm::Value *IsActiveThread =
3369 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3370 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003371
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003372 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003373
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003374 // SrcMediumPtr = &medium[tid]
3375 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3376 TransferMedium,
3377 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3378 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3379 // SrcMediumVal = *SrcMediumPtr;
3380 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003381
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003382 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003383 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003384 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3385 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3386 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3387 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3388 if (NumIters > 1) {
3389 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3390 TargetElemPtr.getAlignment());
3391 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003392
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003393 // *TargetElemPtr = SrcMediumVal;
3394 llvm::Value *SrcMediumValue =
3395 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003396 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003397 CType);
3398 Bld.CreateBr(W0MergeBB);
3399
3400 CGF.EmitBlock(W0ElseBB);
3401 Bld.CreateBr(W0MergeBB);
3402
3403 CGF.EmitBlock(W0MergeBB);
3404
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003405 if (NumIters > 1) {
3406 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3407 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3408 CGF.EmitBranch(PrecondBB);
3409 (void)ApplyDebugLocation::CreateEmpty(CGF);
3410 CGF.EmitBlock(ExitBB);
3411 }
3412 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003413 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003414 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003415 }
3416
3417 CGF.FinishFunction();
3418 return Fn;
3419}
3420
3421/// Emit a helper that reduces data across two OpenMP threads (lanes)
3422/// in the same warp. It uses shuffle instructions to copy over data from
3423/// a remote lane's stack. The reduction algorithm performed is specified
3424/// by the fourth parameter.
3425///
3426/// Algorithm Versions.
3427/// Full Warp Reduce (argument value 0):
3428/// This algorithm assumes that all 32 lanes are active and gathers
3429/// data from these 32 lanes, producing a single resultant value.
3430/// Contiguous Partial Warp Reduce (argument value 1):
3431/// This algorithm assumes that only a *contiguous* subset of lanes
3432/// are active. This happens for the last warp in a parallel region
3433/// when the user specified num_threads is not an integer multiple of
3434/// 32. This contiguous subset always starts with the zeroth lane.
3435/// Partial Warp Reduce (argument value 2):
3436/// This algorithm gathers data from any number of lanes at any position.
3437/// All reduced values are stored in the lowest possible lane. The set
3438/// of problems every algorithm addresses is a super set of those
3439/// addressable by algorithms with a lower version number. Overhead
3440/// increases as algorithm version increases.
3441///
3442/// Terminology
3443/// Reduce element:
3444/// Reduce element refers to the individual data field with primitive
3445/// data types to be combined and reduced across threads.
3446/// Reduce list:
3447/// Reduce list refers to a collection of local, thread-private
3448/// reduce elements.
3449/// Remote Reduce list:
3450/// Remote Reduce list refers to a collection of remote (relative to
3451/// the current thread) reduce elements.
3452///
3453/// We distinguish between three states of threads that are important to
3454/// the implementation of this function.
3455/// Alive threads:
3456/// Threads in a warp executing the SIMT instruction, as distinguished from
3457/// threads that are inactive due to divergent control flow.
3458/// Active threads:
3459/// The minimal set of threads that has to be alive upon entry to this
3460/// function. The computation is correct iff active threads are alive.
3461/// Some threads are alive but they are not active because they do not
3462/// contribute to the computation in any useful manner. Turning them off
3463/// may introduce control flow overheads without any tangible benefits.
3464/// Effective threads:
3465/// In order to comply with the argument requirements of the shuffle
3466/// function, we must keep all lanes holding data alive. But at most
3467/// half of them perform value aggregation; we refer to this half of
3468/// threads as effective. The other half is simply handing off their
3469/// data.
3470///
3471/// Procedure
3472/// Value shuffle:
3473/// In this step active threads transfer data from higher lane positions
3474/// in the warp to lower lane positions, creating Remote Reduce list.
3475/// Value aggregation:
3476/// In this step, effective threads combine their thread local Reduce list
3477/// with Remote Reduce list and store the result in the thread local
3478/// Reduce list.
3479/// Value copy:
3480/// In this step, we deal with the assumption made by algorithm 2
3481/// (i.e. contiguity assumption). When we have an odd number of lanes
3482/// active, say 2k+1, only k threads will be effective and therefore k
3483/// new values will be produced. However, the Reduce list owned by the
3484/// (2k+1)th thread is ignored in the value aggregation. Therefore
3485/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3486/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003487static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003488 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003489 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003490 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003491
3492 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003493 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3494 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003495 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003496 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3497 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003498 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003499 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3500 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003501 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003502 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3503 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003504 FunctionArgList Args;
3505 Args.push_back(&ReduceListArg);
3506 Args.push_back(&LaneIDArg);
3507 Args.push_back(&RemoteLaneOffsetArg);
3508 Args.push_back(&AlgoVerArg);
3509
Alexey Bataev9ff80832018-04-16 20:16:21 +00003510 const CGFunctionInfo &CGFI =
3511 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003512 auto *Fn = llvm::Function::Create(
3513 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3514 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003515 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003516 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003517 if (CGM.getLangOpts().Optimize) {
3518 Fn->removeFnAttr(llvm::Attribute::NoInline);
3519 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3520 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3521 }
3522
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003523 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003524 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003525
Alexey Bataev9ff80832018-04-16 20:16:21 +00003526 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003527
3528 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3529 Address LocalReduceList(
3530 Bld.CreatePointerBitCastOrAddrSpaceCast(
3531 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3532 C.VoidPtrTy, SourceLocation()),
3533 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3534 CGF.getPointerAlign());
3535
3536 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3537 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3538 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3539
3540 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3541 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3542 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3543
3544 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3545 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3546 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3547
3548 // Create a local thread-private variable to host the Reduce list
3549 // from a remote lane.
3550 Address RemoteReduceList =
3551 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3552
3553 // This loop iterates through the list of reduce elements and copies,
3554 // element by element, from a remote lane in the warp to RemoteReduceList,
3555 // hosted on the thread's stack.
3556 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3557 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003558 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3559 /*ScratchpadIndex=*/nullptr,
3560 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003561
3562 // The actions to be performed on the Remote Reduce list is dependent
3563 // on the algorithm version.
3564 //
3565 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3566 // LaneId % 2 == 0 && Offset > 0):
3567 // do the reduction value aggregation
3568 //
3569 // The thread local variable Reduce list is mutated in place to host the
3570 // reduced data, which is the aggregated value produced from local and
3571 // remote lanes.
3572 //
3573 // Note that AlgoVer is expected to be a constant integer known at compile
3574 // time.
3575 // When AlgoVer==0, the first conjunction evaluates to true, making
3576 // the entire predicate true during compile time.
3577 // When AlgoVer==1, the second conjunction has only the second part to be
3578 // evaluated during runtime. Other conjunctions evaluates to false
3579 // during compile time.
3580 // When AlgoVer==2, the third conjunction has only the second part to be
3581 // evaluated during runtime. Other conjunctions evaluates to false
3582 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003583 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003584
Alexey Bataev9ff80832018-04-16 20:16:21 +00003585 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3586 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003587 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3588
Alexey Bataev9ff80832018-04-16 20:16:21 +00003589 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3590 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3591 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003592 CondAlgo2 = Bld.CreateAnd(
3593 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3594
Alexey Bataev9ff80832018-04-16 20:16:21 +00003595 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003596 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3597
3598 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3599 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3600 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3601 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3602
3603 CGF.EmitBlock(ThenBB);
3604 // reduce_function(LocalReduceList, RemoteReduceList)
3605 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3606 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3607 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3608 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003609 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3610 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003611 Bld.CreateBr(MergeBB);
3612
3613 CGF.EmitBlock(ElseBB);
3614 Bld.CreateBr(MergeBB);
3615
3616 CGF.EmitBlock(MergeBB);
3617
3618 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3619 // Reduce list.
3620 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003621 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003622 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3623
3624 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3625 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3626 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3627 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3628
3629 CGF.EmitBlock(CpyThenBB);
3630 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3631 RemoteReduceList, LocalReduceList);
3632 Bld.CreateBr(CpyMergeBB);
3633
3634 CGF.EmitBlock(CpyElseBB);
3635 Bld.CreateBr(CpyMergeBB);
3636
3637 CGF.EmitBlock(CpyMergeBB);
3638
3639 CGF.FinishFunction();
3640 return Fn;
3641}
3642
Alexey Bataev8061acd2019-02-20 16:36:22 +00003643/// This function emits a helper that copies all the reduction variables from
3644/// the team into the provided global buffer for the reduction variables.
3645///
3646/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3647/// For all data entries D in reduce_data:
3648/// Copy local D to buffer.D[Idx]
3649static llvm::Value *emitListToGlobalCopyFunction(
3650 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3651 QualType ReductionArrayTy, SourceLocation Loc,
3652 const RecordDecl *TeamReductionRec,
3653 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3654 &VarFieldMap) {
3655 ASTContext &C = CGM.getContext();
3656
3657 // Buffer: global reduction buffer.
3658 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3659 C.VoidPtrTy, ImplicitParamDecl::Other);
3660 // Idx: index of the buffer.
3661 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3662 ImplicitParamDecl::Other);
3663 // ReduceList: thread local Reduce list.
3664 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3665 C.VoidPtrTy, ImplicitParamDecl::Other);
3666 FunctionArgList Args;
3667 Args.push_back(&BufferArg);
3668 Args.push_back(&IdxArg);
3669 Args.push_back(&ReduceListArg);
3670
3671 const CGFunctionInfo &CGFI =
3672 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3673 auto *Fn = llvm::Function::Create(
3674 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3675 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3676 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3677 Fn->setDoesNotRecurse();
3678 CodeGenFunction CGF(CGM);
3679 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3680
3681 CGBuilderTy &Bld = CGF.Builder;
3682
3683 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3684 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3685 Address LocalReduceList(
3686 Bld.CreatePointerBitCastOrAddrSpaceCast(
3687 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3688 C.VoidPtrTy, Loc),
3689 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3690 CGF.getPointerAlign());
3691 QualType StaticTy = C.getRecordType(TeamReductionRec);
3692 llvm::Type *LLVMReductionsBufferTy =
3693 CGM.getTypes().ConvertTypeForMem(StaticTy);
3694 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3695 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3696 LLVMReductionsBufferTy->getPointerTo());
3697 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3698 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3699 /*Volatile=*/false, C.IntTy,
3700 Loc)};
3701 unsigned Idx = 0;
3702 for (const Expr *Private : Privates) {
3703 // Reduce element = LocalReduceList[i]
3704 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3705 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3706 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3707 // elemptr = ((CopyType*)(elemptrptr)) + I
3708 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3709 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3710 Address ElemPtr =
3711 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3712 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3713 // Global = Buffer.VD[Idx];
3714 const FieldDecl *FD = VarFieldMap.lookup(VD);
3715 LValue GlobLVal = CGF.EmitLValueForField(
3716 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003717 llvm::Value *BufferPtr =
3718 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003719 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3720 switch (CGF.getEvaluationKind(Private->getType())) {
3721 case TEK_Scalar: {
3722 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3723 Private->getType(), Loc);
3724 CGF.EmitStoreOfScalar(V, GlobLVal);
3725 break;
3726 }
3727 case TEK_Complex: {
3728 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3729 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3730 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3731 break;
3732 }
3733 case TEK_Aggregate:
3734 CGF.EmitAggregateCopy(GlobLVal,
3735 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3736 Private->getType(), AggValueSlot::DoesNotOverlap);
3737 break;
3738 }
3739 ++Idx;
3740 }
3741
3742 CGF.FinishFunction();
3743 return Fn;
3744}
3745
3746/// This function emits a helper that reduces all the reduction variables from
3747/// the team into the provided global buffer for the reduction variables.
3748///
3749/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3750/// void *GlobPtrs[];
3751/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3752/// ...
3753/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3754/// reduce_function(GlobPtrs, reduce_data);
3755static llvm::Value *emitListToGlobalReduceFunction(
3756 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3757 QualType ReductionArrayTy, SourceLocation Loc,
3758 const RecordDecl *TeamReductionRec,
3759 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3760 &VarFieldMap,
3761 llvm::Function *ReduceFn) {
3762 ASTContext &C = CGM.getContext();
3763
3764 // Buffer: global reduction buffer.
3765 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3766 C.VoidPtrTy, ImplicitParamDecl::Other);
3767 // Idx: index of the buffer.
3768 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3769 ImplicitParamDecl::Other);
3770 // ReduceList: thread local Reduce list.
3771 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3772 C.VoidPtrTy, ImplicitParamDecl::Other);
3773 FunctionArgList Args;
3774 Args.push_back(&BufferArg);
3775 Args.push_back(&IdxArg);
3776 Args.push_back(&ReduceListArg);
3777
3778 const CGFunctionInfo &CGFI =
3779 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3780 auto *Fn = llvm::Function::Create(
3781 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3782 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3783 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3784 Fn->setDoesNotRecurse();
3785 CodeGenFunction CGF(CGM);
3786 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3787
3788 CGBuilderTy &Bld = CGF.Builder;
3789
3790 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3791 QualType StaticTy = C.getRecordType(TeamReductionRec);
3792 llvm::Type *LLVMReductionsBufferTy =
3793 CGM.getTypes().ConvertTypeForMem(StaticTy);
3794 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3795 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3796 LLVMReductionsBufferTy->getPointerTo());
3797
3798 // 1. Build a list of reduction variables.
3799 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3800 Address ReductionList =
3801 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3802 auto IPriv = Privates.begin();
3803 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3804 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3805 /*Volatile=*/false, C.IntTy,
3806 Loc)};
3807 unsigned Idx = 0;
3808 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3809 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3810 // Global = Buffer.VD[Idx];
3811 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3812 const FieldDecl *FD = VarFieldMap.lookup(VD);
3813 LValue GlobLVal = CGF.EmitLValueForField(
3814 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003815 llvm::Value *BufferPtr =
3816 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003817 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3818 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3819 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3820 // Store array size.
3821 ++Idx;
3822 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3823 llvm::Value *Size = CGF.Builder.CreateIntCast(
3824 CGF.getVLASize(
3825 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3826 .NumElts,
3827 CGF.SizeTy, /*isSigned=*/false);
3828 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3829 Elem);
3830 }
3831 }
3832
3833 // Call reduce_function(GlobalReduceList, ReduceList)
3834 llvm::Value *GlobalReduceList =
3835 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3836 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3837 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3838 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3839 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3840 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3841 CGF.FinishFunction();
3842 return Fn;
3843}
3844
3845/// This function emits a helper that copies all the reduction variables from
3846/// the team into the provided global buffer for the reduction variables.
3847///
3848/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3849/// For all data entries D in reduce_data:
3850/// Copy buffer.D[Idx] to local D;
3851static llvm::Value *emitGlobalToListCopyFunction(
3852 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3853 QualType ReductionArrayTy, SourceLocation Loc,
3854 const RecordDecl *TeamReductionRec,
3855 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3856 &VarFieldMap) {
3857 ASTContext &C = CGM.getContext();
3858
3859 // Buffer: global reduction buffer.
3860 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3861 C.VoidPtrTy, ImplicitParamDecl::Other);
3862 // Idx: index of the buffer.
3863 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3864 ImplicitParamDecl::Other);
3865 // ReduceList: thread local Reduce list.
3866 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3867 C.VoidPtrTy, ImplicitParamDecl::Other);
3868 FunctionArgList Args;
3869 Args.push_back(&BufferArg);
3870 Args.push_back(&IdxArg);
3871 Args.push_back(&ReduceListArg);
3872
3873 const CGFunctionInfo &CGFI =
3874 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3875 auto *Fn = llvm::Function::Create(
3876 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3877 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3878 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3879 Fn->setDoesNotRecurse();
3880 CodeGenFunction CGF(CGM);
3881 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3882
3883 CGBuilderTy &Bld = CGF.Builder;
3884
3885 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3886 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3887 Address LocalReduceList(
3888 Bld.CreatePointerBitCastOrAddrSpaceCast(
3889 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3890 C.VoidPtrTy, Loc),
3891 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3892 CGF.getPointerAlign());
3893 QualType StaticTy = C.getRecordType(TeamReductionRec);
3894 llvm::Type *LLVMReductionsBufferTy =
3895 CGM.getTypes().ConvertTypeForMem(StaticTy);
3896 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3897 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3898 LLVMReductionsBufferTy->getPointerTo());
3899
3900 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3901 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3902 /*Volatile=*/false, C.IntTy,
3903 Loc)};
3904 unsigned Idx = 0;
3905 for (const Expr *Private : Privates) {
3906 // Reduce element = LocalReduceList[i]
3907 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3908 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3909 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3910 // elemptr = ((CopyType*)(elemptrptr)) + I
3911 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3912 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3913 Address ElemPtr =
3914 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3915 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3916 // Global = Buffer.VD[Idx];
3917 const FieldDecl *FD = VarFieldMap.lookup(VD);
3918 LValue GlobLVal = CGF.EmitLValueForField(
3919 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003920 llvm::Value *BufferPtr =
3921 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003922 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3923 switch (CGF.getEvaluationKind(Private->getType())) {
3924 case TEK_Scalar: {
3925 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3926 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3927 break;
3928 }
3929 case TEK_Complex: {
3930 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3931 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3932 /*isInit=*/false);
3933 break;
3934 }
3935 case TEK_Aggregate:
3936 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3937 GlobLVal, Private->getType(),
3938 AggValueSlot::DoesNotOverlap);
3939 break;
3940 }
3941 ++Idx;
3942 }
3943
3944 CGF.FinishFunction();
3945 return Fn;
3946}
3947
3948/// This function emits a helper that reduces all the reduction variables from
3949/// the team into the provided global buffer for the reduction variables.
3950///
3951/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3952/// void *GlobPtrs[];
3953/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3954/// ...
3955/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3956/// reduce_function(reduce_data, GlobPtrs);
3957static llvm::Value *emitGlobalToListReduceFunction(
3958 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3959 QualType ReductionArrayTy, SourceLocation Loc,
3960 const RecordDecl *TeamReductionRec,
3961 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3962 &VarFieldMap,
3963 llvm::Function *ReduceFn) {
3964 ASTContext &C = CGM.getContext();
3965
3966 // Buffer: global reduction buffer.
3967 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3968 C.VoidPtrTy, ImplicitParamDecl::Other);
3969 // Idx: index of the buffer.
3970 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3971 ImplicitParamDecl::Other);
3972 // ReduceList: thread local Reduce list.
3973 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3974 C.VoidPtrTy, ImplicitParamDecl::Other);
3975 FunctionArgList Args;
3976 Args.push_back(&BufferArg);
3977 Args.push_back(&IdxArg);
3978 Args.push_back(&ReduceListArg);
3979
3980 const CGFunctionInfo &CGFI =
3981 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3982 auto *Fn = llvm::Function::Create(
3983 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3984 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3985 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3986 Fn->setDoesNotRecurse();
3987 CodeGenFunction CGF(CGM);
3988 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3989
3990 CGBuilderTy &Bld = CGF.Builder;
3991
3992 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3993 QualType StaticTy = C.getRecordType(TeamReductionRec);
3994 llvm::Type *LLVMReductionsBufferTy =
3995 CGM.getTypes().ConvertTypeForMem(StaticTy);
3996 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3997 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3998 LLVMReductionsBufferTy->getPointerTo());
3999
4000 // 1. Build a list of reduction variables.
4001 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4002 Address ReductionList =
4003 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4004 auto IPriv = Privates.begin();
4005 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
4006 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
4007 /*Volatile=*/false, C.IntTy,
4008 Loc)};
4009 unsigned Idx = 0;
4010 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
4011 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4012 // Global = Buffer.VD[Idx];
4013 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
4014 const FieldDecl *FD = VarFieldMap.lookup(VD);
4015 LValue GlobLVal = CGF.EmitLValueForField(
4016 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004017 llvm::Value *BufferPtr =
4018 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004019 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
4020 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
4021 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4022 // Store array size.
4023 ++Idx;
4024 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4025 llvm::Value *Size = CGF.Builder.CreateIntCast(
4026 CGF.getVLASize(
4027 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4028 .NumElts,
4029 CGF.SizeTy, /*isSigned=*/false);
4030 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4031 Elem);
4032 }
4033 }
4034
4035 // Call reduce_function(ReduceList, GlobalReduceList)
4036 llvm::Value *GlobalReduceList =
4037 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
4038 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
4039 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
4040 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4041 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4042 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4043 CGF.FinishFunction();
4044 return Fn;
4045}
4046
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004047///
4048/// Design of OpenMP reductions on the GPU
4049///
4050/// Consider a typical OpenMP program with one or more reduction
4051/// clauses:
4052///
4053/// float foo;
4054/// double bar;
4055/// #pragma omp target teams distribute parallel for \
4056/// reduction(+:foo) reduction(*:bar)
4057/// for (int i = 0; i < N; i++) {
4058/// foo += A[i]; bar *= B[i];
4059/// }
4060///
4061/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4062/// all teams. In our OpenMP implementation on the NVPTX device an
4063/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4064/// within a team are mapped to CUDA threads within a threadblock.
4065/// Our goal is to efficiently aggregate values across all OpenMP
4066/// threads such that:
4067///
4068/// - the compiler and runtime are logically concise, and
4069/// - the reduction is performed efficiently in a hierarchical
4070/// manner as follows: within OpenMP threads in the same warp,
4071/// across warps in a threadblock, and finally across teams on
4072/// the NVPTX device.
4073///
4074/// Introduction to Decoupling
4075///
4076/// We would like to decouple the compiler and the runtime so that the
4077/// latter is ignorant of the reduction variables (number, data types)
4078/// and the reduction operators. This allows a simpler interface
4079/// and implementation while still attaining good performance.
4080///
4081/// Pseudocode for the aforementioned OpenMP program generated by the
4082/// compiler is as follows:
4083///
4084/// 1. Create private copies of reduction variables on each OpenMP
4085/// thread: 'foo_private', 'bar_private'
4086/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4087/// to it and writes the result in 'foo_private' and 'bar_private'
4088/// respectively.
4089/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4090/// and store the result on the team master:
4091///
Alexey Bataev8e009032019-01-04 17:25:09 +00004092/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004093/// reduceData, shuffleReduceFn, interWarpCpyFn)
4094///
4095/// where:
4096/// struct ReduceData {
4097/// double *foo;
4098/// double *bar;
4099/// } reduceData
4100/// reduceData.foo = &foo_private
4101/// reduceData.bar = &bar_private
4102///
4103/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4104/// auxiliary functions generated by the compiler that operate on
4105/// variables of type 'ReduceData'. They aid the runtime perform
4106/// algorithmic steps in a data agnostic manner.
4107///
4108/// 'shuffleReduceFn' is a pointer to a function that reduces data
4109/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4110/// same warp. It takes the following arguments as input:
4111///
4112/// a. variable of type 'ReduceData' on the calling lane,
4113/// b. its lane_id,
4114/// c. an offset relative to the current lane_id to generate a
4115/// remote_lane_id. The remote lane contains the second
4116/// variable of type 'ReduceData' that is to be reduced.
4117/// d. an algorithm version parameter determining which reduction
4118/// algorithm to use.
4119///
4120/// 'shuffleReduceFn' retrieves data from the remote lane using
4121/// efficient GPU shuffle intrinsics and reduces, using the
4122/// algorithm specified by the 4th parameter, the two operands
4123/// element-wise. The result is written to the first operand.
4124///
4125/// Different reduction algorithms are implemented in different
4126/// runtime functions, all calling 'shuffleReduceFn' to perform
4127/// the essential reduction step. Therefore, based on the 4th
4128/// parameter, this function behaves slightly differently to
4129/// cooperate with the runtime to ensure correctness under
4130/// different circumstances.
4131///
4132/// 'InterWarpCpyFn' is a pointer to a function that transfers
4133/// reduced variables across warps. It tunnels, through CUDA
4134/// shared memory, the thread-private data of type 'ReduceData'
4135/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004136/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4137/// The last team writes the global reduced value to memory.
4138///
4139/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4140/// reduceData, shuffleReduceFn, interWarpCpyFn,
4141/// scratchpadCopyFn, loadAndReduceFn)
4142///
4143/// 'scratchpadCopyFn' is a helper that stores reduced
4144/// data from the team master to a scratchpad array in
4145/// global memory.
4146///
4147/// 'loadAndReduceFn' is a helper that loads data from
4148/// the scratchpad array and reduces it with the input
4149/// operand.
4150///
4151/// These compiler generated functions hide address
4152/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004153/// 5. if ret == 1:
4154/// The team master of the last team stores the reduced
4155/// result to the globals in memory.
4156/// foo += reduceData.foo; bar *= reduceData.bar
4157///
4158///
4159/// Warp Reduction Algorithms
4160///
4161/// On the warp level, we have three algorithms implemented in the
4162/// OpenMP runtime depending on the number of active lanes:
4163///
4164/// Full Warp Reduction
4165///
4166/// The reduce algorithm within a warp where all lanes are active
4167/// is implemented in the runtime as follows:
4168///
4169/// full_warp_reduce(void *reduce_data,
4170/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4171/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4172/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4173/// }
4174///
4175/// The algorithm completes in log(2, WARPSIZE) steps.
4176///
4177/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4178/// not used therefore we save instructions by not retrieving lane_id
4179/// from the corresponding special registers. The 4th parameter, which
4180/// represents the version of the algorithm being used, is set to 0 to
4181/// signify full warp reduction.
4182///
4183/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4184///
4185/// #reduce_elem refers to an element in the local lane's data structure
4186/// #remote_elem is retrieved from a remote lane
4187/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4188/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4189///
4190/// Contiguous Partial Warp Reduction
4191///
4192/// This reduce algorithm is used within a warp where only the first
4193/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4194/// number of OpenMP threads in a parallel region is not a multiple of
4195/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4196///
4197/// void
4198/// contiguous_partial_reduce(void *reduce_data,
4199/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4200/// int size, int lane_id) {
4201/// int curr_size;
4202/// int offset;
4203/// curr_size = size;
4204/// mask = curr_size/2;
4205/// while (offset>0) {
4206/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4207/// curr_size = (curr_size+1)/2;
4208/// offset = curr_size/2;
4209/// }
4210/// }
4211///
4212/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4213///
4214/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4215/// if (lane_id < offset)
4216/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4217/// else
4218/// reduce_elem = remote_elem
4219///
4220/// This algorithm assumes that the data to be reduced are located in a
4221/// contiguous subset of lanes starting from the first. When there is
4222/// an odd number of active lanes, the data in the last lane is not
4223/// aggregated with any other lane's dat but is instead copied over.
4224///
4225/// Dispersed Partial Warp Reduction
4226///
4227/// This algorithm is used within a warp when any discontiguous subset of
4228/// lanes are active. It is used to implement the reduction operation
4229/// across lanes in an OpenMP simd region or in a nested parallel region.
4230///
4231/// void
4232/// dispersed_partial_reduce(void *reduce_data,
4233/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4234/// int size, remote_id;
4235/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4236/// do {
4237/// remote_id = next_active_lane_id_right_after_me();
4238/// # the above function returns 0 of no active lane
4239/// # is present right after the current lane.
4240/// size = number_of_active_lanes_in_this_warp();
4241/// logical_lane_id /= 2;
4242/// ShuffleReduceFn(reduce_data, logical_lane_id,
4243/// remote_id-1-threadIdx.x, 2);
4244/// } while (logical_lane_id % 2 == 0 && size > 1);
4245/// }
4246///
4247/// There is no assumption made about the initial state of the reduction.
4248/// Any number of lanes (>=1) could be active at any position. The reduction
4249/// result is returned in the first active lane.
4250///
4251/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4252///
4253/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4254/// if (lane_id % 2 == 0 && offset > 0)
4255/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4256/// else
4257/// reduce_elem = remote_elem
4258///
4259///
4260/// Intra-Team Reduction
4261///
4262/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004263/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004264/// threads in a team. It first reduces within a warp using the
4265/// aforementioned algorithms. We then proceed to gather all such
4266/// reduced values at the first warp.
4267///
4268/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4269/// data from each of the "warp master" (zeroth lane of each warp, where
4270/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4271/// a mathematical sense) the problem of reduction across warp masters in
4272/// a block to the problem of warp reduction.
4273///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004274///
4275/// Inter-Team Reduction
4276///
4277/// Once a team has reduced its data to a single value, it is stored in
4278/// a global scratchpad array. Since each team has a distinct slot, this
4279/// can be done without locking.
4280///
4281/// The last team to write to the scratchpad array proceeds to reduce the
4282/// scratchpad array. One or more workers in the last team use the helper
4283/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4284/// the k'th worker reduces every k'th element.
4285///
Alexey Bataev8e009032019-01-04 17:25:09 +00004286/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004287/// reduce across workers and compute a globally reduced value.
4288///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004289void CGOpenMPRuntimeNVPTX::emitReduction(
4290 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4291 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4292 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4293 if (!CGF.HaveInsertPoint())
4294 return;
4295
4296 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004297#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004298 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004299#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004300
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004301 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004302 assert(!TeamsReduction && !ParallelReduction &&
4303 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004304 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4305 ReductionOps, Options);
4306 return;
4307 }
4308
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004309 assert((TeamsReduction || ParallelReduction) &&
4310 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004311
Alexey Bataeva1166022018-11-27 21:24:54 +00004312 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004313 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004314 // or
4315 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004316 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004317 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004318
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004319 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004320 ASTContext &C = CGM.getContext();
4321 // 1. Build a list of reduction variables.
4322 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4323 auto Size = RHSExprs.size();
4324 for (const Expr *E : Privates) {
4325 if (E->getType()->isVariablyModifiedType())
4326 // Reserve place for array size.
4327 ++Size;
4328 }
4329 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4330 QualType ReductionArrayTy =
Richard Smith772e2662019-10-04 01:25:59 +00004331 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
Alexey Bataev8061acd2019-02-20 16:36:22 +00004332 /*IndexTypeQuals=*/0);
4333 Address ReductionList =
4334 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4335 auto IPriv = Privates.begin();
4336 unsigned Idx = 0;
4337 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4338 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4339 CGF.Builder.CreateStore(
4340 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004341 CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
Alexey Bataev8061acd2019-02-20 16:36:22 +00004342 Elem);
4343 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4344 // Store array size.
4345 ++Idx;
4346 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4347 llvm::Value *Size = CGF.Builder.CreateIntCast(
4348 CGF.getVLASize(
4349 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4350 .NumElts,
4351 CGF.SizeTy, /*isSigned=*/false);
4352 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4353 Elem);
4354 }
4355 }
4356
4357 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4358 ReductionList.getPointer(), CGF.VoidPtrTy);
4359 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004360 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4361 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004362 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4363 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4364 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4365 llvm::Value *InterWarpCopyFn =
4366 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4367
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004368 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004369 llvm::Value *Args[] = {RTLoc,
4370 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004371 CGF.Builder.getInt32(RHSExprs.size()),
4372 ReductionArrayTySize,
4373 RL,
4374 ShuffleAndReduceFn,
4375 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004376
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004377 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004378 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004379 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4380 Args);
4381 } else {
4382 assert(TeamsReduction && "expected teams reduction.");
4383 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4384 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4385 int Cnt = 0;
4386 for (const Expr *DRE : Privates) {
4387 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4388 ++Cnt;
4389 }
4390 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4391 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4392 C.getLangOpts().OpenMPCUDAReductionBufNum);
4393 TeamsReductions.push_back(TeamReductionRec);
4394 if (!KernelTeamsReductionPtr) {
4395 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4396 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4397 llvm::GlobalValue::InternalLinkage, nullptr,
4398 "_openmp_teams_reductions_buffer_$_$ptr");
4399 }
4400 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4401 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4402 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4403 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4404 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4405 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4406 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4407 ReductionFn);
4408 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4409 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4410 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4411 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4412 ReductionFn);
4413
4414 llvm::Value *Args[] = {
4415 RTLoc,
4416 ThreadId,
4417 GlobalBufferPtr,
4418 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4419 RL,
4420 ShuffleAndReduceFn,
4421 InterWarpCopyFn,
4422 GlobalToBufferCpyFn,
4423 GlobalToBufferRedFn,
4424 BufferToGlobalCpyFn,
4425 BufferToGlobalRedFn};
4426
4427 Res = CGF.EmitRuntimeCall(
4428 createNVPTXRuntimeFunction(
4429 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004430 Args);
4431 }
4432
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004433 // 5. Build if (res == 1)
4434 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4435 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4436 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4437 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4438 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004439
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004440 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004441 // thread in each team.
4442 // __kmpc_end_reduce{_nowait}(<gtid>);
4443 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004444 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004445
4446 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004447 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004448 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4449 auto IPriv = Privates.begin();
4450 auto ILHS = LHSExprs.begin();
4451 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004452 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004453 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4454 cast<DeclRefExpr>(*IRHS));
4455 ++IPriv;
4456 ++ILHS;
4457 ++IRHS;
4458 }
4459 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004460 llvm::Value *EndArgs[] = {ThreadId};
4461 RegionCodeGenTy RCG(CodeGen);
4462 NVPTXActionTy Action(
4463 nullptr, llvm::None,
4464 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4465 EndArgs);
4466 RCG.setAction(Action);
4467 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004468 // There is no need to emit line number for unconditional branch.
4469 (void)ApplyDebugLocation::CreateEmpty(CGF);
4470 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004471}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004472
4473const VarDecl *
4474CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4475 const VarDecl *NativeParam) const {
4476 if (!NativeParam->getType()->isReferenceType())
4477 return NativeParam;
4478 QualType ArgType = NativeParam->getType();
4479 QualifierCollector QC;
4480 const Type *NonQualTy = QC.strip(ArgType);
4481 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4482 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4483 if (Attr->getCaptureKind() == OMPC_map) {
4484 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4485 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004486 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4487 PointeeTy.isConstant(CGM.getContext())) {
4488 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4489 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004490 }
4491 }
4492 ArgType = CGM.getContext().getPointerType(PointeeTy);
4493 QC.addRestrict();
4494 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004495 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004496 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004497 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004498 return ImplicitParamDecl::Create(
4499 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4500 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004501 return ParmVarDecl::Create(
4502 CGM.getContext(),
4503 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004504 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004505 NativeParam->getIdentifier(), ArgType,
4506 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004507}
4508
4509Address
4510CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4511 const VarDecl *NativeParam,
4512 const VarDecl *TargetParam) const {
4513 assert(NativeParam != TargetParam &&
4514 NativeParam->getType()->isReferenceType() &&
4515 "Native arg must not be the same as target arg.");
4516 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4517 QualType NativeParamType = NativeParam->getType();
4518 QualifierCollector QC;
4519 const Type *NonQualTy = QC.strip(NativeParamType);
4520 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4521 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004522 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004523 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004524 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004525 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004526 // First cast to generic.
4527 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4528 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4529 /*AddrSpace=*/0));
4530 // Cast from generic to native address space.
4531 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4532 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4533 NativePointeeAddrSpace));
4534 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4535 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004536 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004537 return NativeParamAddr;
4538}
4539
4540void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004541 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004542 ArrayRef<llvm::Value *> Args) const {
4543 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004544 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004545 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004546 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004547 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4548 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4549 break;
4550 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004551 llvm::Type *TargetType = FnType->getParamType(I);
4552 llvm::Value *NativeArg = Args[I];
4553 if (!TargetType->isPointerTy()) {
4554 TargetArgs.emplace_back(NativeArg);
4555 continue;
4556 }
4557 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004558 NativeArg,
4559 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004560 TargetArgs.emplace_back(
4561 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4562 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004563 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004564}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004565
4566/// Emit function which wraps the outline parallel region
4567/// and controls the arguments which are passed to this function.
4568/// The wrapper ensures that the outlined function is called
4569/// with the correct arguments when data is shared.
4570llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4571 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4572 ASTContext &Ctx = CGM.getContext();
4573 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4574
4575 // Create a function that takes as argument the source thread.
4576 FunctionArgList WrapperArgs;
4577 QualType Int16QTy =
4578 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4579 QualType Int32QTy =
4580 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004581 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004582 /*Id=*/nullptr, Int16QTy,
4583 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004584 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004585 /*Id=*/nullptr, Int32QTy,
4586 ImplicitParamDecl::Other);
4587 WrapperArgs.emplace_back(&ParallelLevelArg);
4588 WrapperArgs.emplace_back(&WrapperArg);
4589
Alexey Bataev9ff80832018-04-16 20:16:21 +00004590 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004591 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4592
4593 auto *Fn = llvm::Function::Create(
4594 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004595 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004596 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004597 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004598 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004599
4600 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4601 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004602 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004603
4604 const auto *RD = CS.getCapturedRecordDecl();
4605 auto CurField = RD->field_begin();
4606
Alexey Bataevf89cf212019-10-16 16:59:01 +00004607 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4608 /*Name=*/".zero.addr");
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004609 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004610 // Get the array of arguments.
4611 SmallVector<llvm::Value *, 8> Args;
4612
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004613 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4614 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004615
4616 CGBuilderTy &Bld = CGF.Builder;
4617 auto CI = CS.capture_begin();
4618
4619 // Use global memory for data sharing.
4620 // Handle passing of global args to workers.
4621 Address GlobalArgs =
4622 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4623 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4624 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4625 CGF.EmitRuntimeCall(
4626 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4627 DataSharingArgs);
4628
4629 // Retrieve the shared variables from the list of references returned
4630 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004631 Address SharedArgListAddress = Address::invalid();
4632 if (CS.capture_size() > 0 ||
4633 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4634 SharedArgListAddress = CGF.EmitLoadOfPointer(
4635 GlobalArgs, CGF.getContext()
4636 .getPointerType(CGF.getContext().getPointerType(
4637 CGF.getContext().VoidPtrTy))
4638 .castAs<PointerType>());
4639 }
4640 unsigned Idx = 0;
4641 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004642 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004643 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4644 Src, CGF.SizeTy->getPointerTo());
4645 llvm::Value *LB = CGF.EmitLoadOfScalar(
4646 TypedAddress,
4647 /*Volatile=*/false,
4648 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4649 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4650 Args.emplace_back(LB);
4651 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004652 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004653 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4654 Src, CGF.SizeTy->getPointerTo());
4655 llvm::Value *UB = CGF.EmitLoadOfScalar(
4656 TypedAddress,
4657 /*Volatile=*/false,
4658 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4659 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4660 Args.emplace_back(UB);
4661 ++Idx;
4662 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004663 if (CS.capture_size() > 0) {
4664 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004665 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4666 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004667 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004668 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004669 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4670 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4671 /*Volatile=*/false,
4672 CGFContext.getPointerType(ElemTy),
4673 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004674 if (CI->capturesVariableByCopy() &&
4675 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004676 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4677 CI->getLocation());
4678 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004679 Args.emplace_back(Arg);
4680 }
4681 }
4682
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004683 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004684 CGF.FinishFunction();
4685 return Fn;
4686}
4687
4688void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4689 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004690 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4691 return;
4692
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004693 assert(D && "Expected function or captured|block decl.");
4694 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4695 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004696 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4697 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004698 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004699 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004700 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4701 Body = FD->getBody();
4702 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4703 Body = BD->getBody();
4704 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4705 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004706 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004707 if (NeedToDelayGlobalization &&
4708 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4709 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004710 }
4711 if (!Body)
4712 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004713 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004714 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004715 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004716 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004717 TeamAndReductions.first = nullptr;
4718 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004719 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4720 VarChecker.getEscapedVariableLengthDecls();
4721 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004722 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004723 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4724 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004725 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004726 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4727 I->getSecond().EscapedParameters.insert(
4728 VarChecker.getEscapedParameters().begin(),
4729 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004730 I->getSecond().EscapedVariableLengthDecls.append(
4731 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004732 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004733 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004734 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004735 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004736 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004737 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004738 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004739 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004740 VarChecker.Visit(Body);
4741 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004742 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004743 I->getSecond().SecondaryLocalVarData.emplace();
4744 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4745 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4746 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4747 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004748 Data.insert(
4749 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004750 }
4751 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004752 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004753 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004754 struct GlobalizationScope final : EHScopeStack::Cleanup {
4755 GlobalizationScope() = default;
4756
4757 void Emit(CodeGenFunction &CGF, Flags flags) override {
4758 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004759 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004760 }
4761 };
4762 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004763 }
4764}
4765
4766Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4767 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004768 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4769 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4770 switch (A->getAllocatorType()) {
4771 // Use the default allocator here as by default local vars are
4772 // threadlocal.
4773 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4774 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004775 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4776 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004777 // Follow the user decision - use default allocation.
4778 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004779 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004780 // TODO: implement aupport for user-defined allocators.
4781 return Address::invalid();
4782 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4783 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4784 auto *GV = new llvm::GlobalVariable(
4785 CGM.getModule(), VarTy, /*isConstant=*/false,
4786 llvm::GlobalValue::InternalLinkage,
4787 llvm::Constant::getNullValue(VarTy), VD->getName(),
4788 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4789 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4790 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004791 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004792 return Address(GV, Align);
4793 }
4794 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4795 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4796 auto *GV = new llvm::GlobalVariable(
4797 CGM.getModule(), VarTy, /*isConstant=*/false,
4798 llvm::GlobalValue::InternalLinkage,
4799 llvm::Constant::getNullValue(VarTy), VD->getName(),
4800 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4801 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4802 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004803 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004804 return Address(GV, Align);
4805 }
4806 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4807 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4808 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4809 auto *GV = new llvm::GlobalVariable(
4810 CGM.getModule(), VarTy, /*isConstant=*/false,
4811 llvm::GlobalValue::InternalLinkage,
4812 llvm::Constant::getNullValue(VarTy), VD->getName());
4813 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004814 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004815 return Address(GV, Align);
4816 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004817 }
4818 }
4819
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004820 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4821 return Address::invalid();
4822
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004823 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004824 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4825 if (I == FunctionGlobalizedDecls.end())
4826 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004827 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004828 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004829 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004830 if (VD->hasAttrs()) {
4831 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4832 E(VD->attr_end());
4833 IT != E; ++IT) {
4834 auto VDI = I->getSecond().LocalVarData.find(
4835 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4836 ->getCanonicalDecl());
4837 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004838 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004839 }
4840 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004841
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004842 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004843}
4844
4845void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004846 FunctionGlobalizedDecls.erase(CGF.CurFn);
4847 CGOpenMPRuntime::functionFinished(CGF);
4848}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004849
4850void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4851 CodeGenFunction &CGF, const OMPLoopDirective &S,
4852 OpenMPDistScheduleClauseKind &ScheduleKind,
4853 llvm::Value *&Chunk) const {
4854 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4855 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4856 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4857 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4858 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004859 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004860 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004861 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4862 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004863}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004864
4865void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4866 CodeGenFunction &CGF, const OMPLoopDirective &S,
4867 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004868 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004869 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004870 // Chunk size is 1 in this case.
4871 llvm::APInt ChunkSize(32, 1);
4872 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4873 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4874 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004875}
Alexey Bataev60705422018-10-30 15:50:12 +00004876
4877void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4878 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4879 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4880 " Expected target-based directive.");
4881 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4882 for (const CapturedStmt::Capture &C : CS->captures()) {
4883 // Capture variables captured by reference in lambdas for target-based
4884 // directives.
4885 if (!C.capturesVariable())
4886 continue;
4887 const VarDecl *VD = C.getCapturedVar();
4888 const auto *RD = VD->getType()
4889 .getCanonicalType()
4890 .getNonReferenceType()
4891 ->getAsCXXRecordDecl();
4892 if (!RD || !RD->isLambda())
4893 continue;
4894 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4895 LValue VDLVal;
4896 if (VD->getType().getCanonicalType()->isReferenceType())
4897 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4898 else
4899 VDLVal = CGF.MakeAddrLValue(
4900 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4901 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4902 FieldDecl *ThisCapture = nullptr;
4903 RD->getCaptureFields(Captures, ThisCapture);
4904 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4905 LValue ThisLVal =
4906 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4907 llvm::Value *CXXThis = CGF.LoadCXXThis();
4908 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4909 }
4910 for (const LambdaCapture &LC : RD->captures()) {
4911 if (LC.getCaptureKind() != LCK_ByRef)
4912 continue;
4913 const VarDecl *VD = LC.getCapturedVar();
4914 if (!CS->capturesVariable(VD))
4915 continue;
4916 auto It = Captures.find(VD);
4917 assert(It != Captures.end() && "Found lambda capture without field.");
4918 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4919 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4920 if (VD->getType().getCanonicalType()->isReferenceType())
4921 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4922 VD->getType().getCanonicalType())
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004923 .getAddress(CGF);
Alexey Bataev60705422018-10-30 15:50:12 +00004924 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4925 }
4926 }
4927}
4928
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004929unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4930 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4931}
4932
Alexey Bataevc5687252019-03-21 19:35:27 +00004933bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4934 LangAS &AS) {
4935 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4936 return false;
4937 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4938 switch(A->getAllocatorType()) {
4939 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4940 // Not supported, fallback to the default mem space.
4941 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4942 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4943 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4944 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4945 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4946 AS = LangAS::Default;
4947 return true;
4948 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4949 AS = LangAS::cuda_constant;
4950 return true;
4951 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4952 AS = LangAS::cuda_shared;
4953 return true;
4954 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4955 llvm_unreachable("Expected predefined allocator for the variables with the "
4956 "static storage.");
4957 }
4958 return false;
4959}
4960
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004961// Get current CudaArch and ignore any unknown values
4962static CudaArch getCudaArch(CodeGenModule &CGM) {
4963 if (!CGM.getTarget().hasFeature("ptx"))
4964 return CudaArch::UNKNOWN;
4965 llvm::StringMap<bool> Features;
4966 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4967 CGM.getTarget().getTargetOpts().CPU,
4968 CGM.getTarget().getTargetOpts().Features);
4969 for (const auto &Feature : Features) {
4970 if (Feature.getValue()) {
4971 CudaArch Arch = StringToCudaArch(Feature.getKey());
4972 if (Arch != CudaArch::UNKNOWN)
4973 return Arch;
4974 }
4975 }
4976 return CudaArch::UNKNOWN;
4977}
4978
4979/// Check to see if target architecture supports unified addressing which is
4980/// a restriction for OpenMP requires clause "unified_shared_memory".
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05004981void CGOpenMPRuntimeNVPTX::processRequiresDirective(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004982 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004983 for (const OMPClause *Clause : D->clauselists()) {
4984 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
Alexey Bataev7b710a42019-11-05 10:10:50 -05004985 CudaArch Arch = getCudaArch(CGM);
4986 switch (Arch) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004987 case CudaArch::SM_20:
4988 case CudaArch::SM_21:
4989 case CudaArch::SM_30:
4990 case CudaArch::SM_32:
4991 case CudaArch::SM_35:
4992 case CudaArch::SM_37:
4993 case CudaArch::SM_50:
4994 case CudaArch::SM_52:
4995 case CudaArch::SM_53:
4996 case CudaArch::SM_60:
4997 case CudaArch::SM_61:
Alexey Bataev7b710a42019-11-05 10:10:50 -05004998 case CudaArch::SM_62: {
4999 SmallString<256> Buffer;
5000 llvm::raw_svector_ostream Out(Buffer);
5001 Out << "Target architecture " << CudaArchToString(Arch)
5002 << " does not support unified addressing";
5003 CGM.Error(Clause->getBeginLoc(), Out.str());
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005004 return;
Alexey Bataev7b710a42019-11-05 10:10:50 -05005005 }
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005006 case CudaArch::SM_70:
5007 case CudaArch::SM_72:
5008 case CudaArch::SM_75:
5009 case CudaArch::GFX600:
5010 case CudaArch::GFX601:
5011 case CudaArch::GFX700:
5012 case CudaArch::GFX701:
5013 case CudaArch::GFX702:
5014 case CudaArch::GFX703:
5015 case CudaArch::GFX704:
5016 case CudaArch::GFX801:
5017 case CudaArch::GFX802:
5018 case CudaArch::GFX803:
5019 case CudaArch::GFX810:
5020 case CudaArch::GFX900:
5021 case CudaArch::GFX902:
5022 case CudaArch::GFX904:
5023 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005024 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005025 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005026 case CudaArch::GFX1010:
5027 case CudaArch::GFX1011:
5028 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005029 case CudaArch::UNKNOWN:
5030 break;
5031 case CudaArch::LAST:
5032 llvm_unreachable("Unexpected Cuda arch.");
5033 }
5034 }
5035 }
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05005036 CGOpenMPRuntime::processRequiresDirective(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005037}
5038
Alexey Bataeve4090182018-11-02 14:54:07 +00005039/// Get number of SMs and number of blocks per SM.
5040static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
5041 std::pair<unsigned, unsigned> Data;
5042 if (CGM.getLangOpts().OpenMPCUDANumSMs)
5043 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
5044 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5045 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5046 if (Data.first && Data.second)
5047 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005048 switch (getCudaArch(CGM)) {
5049 case CudaArch::SM_20:
5050 case CudaArch::SM_21:
5051 case CudaArch::SM_30:
5052 case CudaArch::SM_32:
5053 case CudaArch::SM_35:
5054 case CudaArch::SM_37:
5055 case CudaArch::SM_50:
5056 case CudaArch::SM_52:
5057 case CudaArch::SM_53:
5058 return {16, 16};
5059 case CudaArch::SM_60:
5060 case CudaArch::SM_61:
5061 case CudaArch::SM_62:
5062 return {56, 32};
5063 case CudaArch::SM_70:
5064 case CudaArch::SM_72:
5065 case CudaArch::SM_75:
5066 return {84, 32};
5067 case CudaArch::GFX600:
5068 case CudaArch::GFX601:
5069 case CudaArch::GFX700:
5070 case CudaArch::GFX701:
5071 case CudaArch::GFX702:
5072 case CudaArch::GFX703:
5073 case CudaArch::GFX704:
5074 case CudaArch::GFX801:
5075 case CudaArch::GFX802:
5076 case CudaArch::GFX803:
5077 case CudaArch::GFX810:
5078 case CudaArch::GFX900:
5079 case CudaArch::GFX902:
5080 case CudaArch::GFX904:
5081 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005082 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005083 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005084 case CudaArch::GFX1010:
5085 case CudaArch::GFX1011:
5086 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005087 case CudaArch::UNKNOWN:
5088 break;
5089 case CudaArch::LAST:
5090 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005091 }
5092 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5093}
5094
5095void CGOpenMPRuntimeNVPTX::clear() {
5096 if (!GlobalizedRecords.empty()) {
5097 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005098 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5099 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005100 RecordDecl *StaticRD = C.buildImplicitRecord(
5101 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5102 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005103 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5104 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5105 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005106 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5107 if (Records.Records.empty())
5108 continue;
5109 unsigned Size = 0;
5110 unsigned RecAlignment = 0;
5111 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005112 QualType RDTy = C.getRecordType(RD);
5113 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005114 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005115 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005116 Size =
5117 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5118 }
5119 Size = llvm::alignTo(Size, RecAlignment);
5120 llvm::APInt ArySize(/*numBits=*/64, Size);
5121 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005122 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005123 const bool UseSharedMemory = Size <= SharedMemorySize;
5124 auto *Field =
5125 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5126 SourceLocation(), SourceLocation(), nullptr, SubTy,
5127 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5128 /*BW=*/nullptr, /*Mutable=*/false,
5129 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005130 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005131 if (UseSharedMemory) {
5132 SharedStaticRD->addDecl(Field);
5133 SharedRecs.push_back(&Records);
5134 } else {
5135 StaticRD->addDecl(Field);
5136 GlobalRecs.push_back(&Records);
5137 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005138 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005139 Records.UseSharedMemory->setInitializer(
5140 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5141 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005142 // Allocate SharedMemorySize buffer for the shared memory.
5143 // FIXME: nvlink does not handle weak linkage correctly (object with the
5144 // different size are reported as erroneous).
5145 // Restore this code as sson as nvlink is fixed.
5146 if (!SharedStaticRD->field_empty()) {
5147 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5148 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005149 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005150 auto *Field = FieldDecl::Create(
5151 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5152 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5153 /*BW=*/nullptr, /*Mutable=*/false,
5154 /*InitStyle=*/ICIS_NoInit);
5155 Field->setAccess(AS_public);
5156 SharedStaticRD->addDecl(Field);
5157 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005158 SharedStaticRD->completeDefinition();
5159 if (!SharedStaticRD->field_empty()) {
5160 QualType StaticTy = C.getRecordType(SharedStaticRD);
5161 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5162 auto *GV = new llvm::GlobalVariable(
5163 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005164 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005165 llvm::Constant::getNullValue(LLVMStaticTy),
5166 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5167 llvm::GlobalValue::NotThreadLocal,
5168 C.getTargetAddressSpace(LangAS::cuda_shared));
5169 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5170 GV, CGM.VoidPtrTy);
5171 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5172 Rec->Buffer->replaceAllUsesWith(Replacement);
5173 Rec->Buffer->eraseFromParent();
5174 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005175 }
5176 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005177 if (!StaticRD->field_empty()) {
5178 QualType StaticTy = C.getRecordType(StaticRD);
5179 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5180 llvm::APInt Size1(32, SMsBlockPerSM.second);
5181 QualType Arr1Ty =
Richard Smith772e2662019-10-04 01:25:59 +00005182 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005183 /*IndexTypeQuals=*/0);
5184 llvm::APInt Size2(32, SMsBlockPerSM.first);
Richard Smith772e2662019-10-04 01:25:59 +00005185 QualType Arr2Ty =
5186 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5187 /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005188 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005189 // FIXME: nvlink does not handle weak linkage correctly (object with the
5190 // different size are reported as erroneous).
5191 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005192 auto *GV = new llvm::GlobalVariable(
5193 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005194 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005195 llvm::Constant::getNullValue(LLVMArr2Ty),
5196 "_openmp_static_glob_rd_$_");
5197 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5198 GV, CGM.VoidPtrTy);
5199 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5200 Rec->Buffer->replaceAllUsesWith(Replacement);
5201 Rec->Buffer->eraseFromParent();
5202 }
5203 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005204 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005205 if (!TeamsReductions.empty()) {
5206 ASTContext &C = CGM.getContext();
5207 RecordDecl *StaticRD = C.buildImplicitRecord(
5208 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5209 StaticRD->startDefinition();
5210 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5211 QualType RecTy = C.getRecordType(TeamReductionRec);
5212 auto *Field = FieldDecl::Create(
5213 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5214 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5215 /*BW=*/nullptr, /*Mutable=*/false,
5216 /*InitStyle=*/ICIS_NoInit);
5217 Field->setAccess(AS_public);
5218 StaticRD->addDecl(Field);
5219 }
5220 StaticRD->completeDefinition();
5221 QualType StaticTy = C.getRecordType(StaticRD);
5222 llvm::Type *LLVMReductionsBufferTy =
5223 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005224 // FIXME: nvlink does not handle weak linkage correctly (object with the
5225 // different size are reported as erroneous).
5226 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005227 auto *GV = new llvm::GlobalVariable(
5228 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005229 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005230 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5231 "_openmp_teams_reductions_buffer_$_");
5232 KernelTeamsReductionPtr->setInitializer(
5233 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5234 CGM.VoidPtrTy));
5235 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005236 CGOpenMPRuntime::clear();
5237}