blob: f66943a7018e9f1f08805fd2aeb6f47392872dbb [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Samuel Antao45bfe4c2016-02-08 15:59:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation specialized to NVPTX
10// targets.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000015#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000016#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000017#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000018#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000019#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000020#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000035 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
36 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Alexey Bataev8e009032019-01-04 17:25:09 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
Alexey Bataev8e009032019-01-04 17:25:09 +000063 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2,
Alexey Bataeva1166022018-11-27 21:24:54 +000064 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
65 /// global_tid, kmp_critical_name *lck)
66 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
67 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
68 /// kmp_int32 global_tid, kmp_critical_name *lck)
69 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000071 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000073 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000074 /// Call to void __kmpc_data_sharing_init_stack_spmd();
75 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000076 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000077 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000078 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000080 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000082 /// size_t n_args);
83 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000084 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000085 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000086 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000087 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000088 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
89 /// global_tid);
90 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000091 /// Call to int8_t __kmpc_is_spmd_exec_mode();
92 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +000093 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
94 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +000095 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +000096 /// Call to void __kmpc_restore_team_static_memory(int16_t
97 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +000098 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +000099 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000100 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000101 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
102 /// global_tid);
103 OMPRTL__kmpc_barrier_simple_spmd,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000104};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000105
106/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
107class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000108 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000109 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000110 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000111 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000112 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000113 llvm::BasicBlock *ContBlock = nullptr;
114
115public:
James Y Knight9871db02019-02-05 16:42:33 +0000116 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
117 ArrayRef<llvm::Value *> EnterArgs,
118 llvm::FunctionCallee ExitCallee,
119 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000120 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
121 ExitArgs(ExitArgs), Conditional(Conditional) {}
122 void Enter(CodeGenFunction &CGF) override {
123 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
124 if (Conditional) {
125 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
126 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
127 ContBlock = CGF.createBasicBlock("omp_if.end");
128 // Generate the branch (If-stmt)
129 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
130 CGF.EmitBlock(ThenBlock);
131 }
132 }
133 void Done(CodeGenFunction &CGF) {
134 // Emit the rest of blocks/branches
135 CGF.EmitBranch(ContBlock);
136 CGF.EmitBlock(ContBlock, true);
137 }
138 void Exit(CodeGenFunction &CGF) override {
139 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
140 }
141};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000142
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000143/// A class to track the execution mode when codegening directives within
144/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
145/// to the target region and used by containing directives such as 'parallel'
146/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000147class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000149 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
150 CGOpenMPRuntimeNVPTX::EM_Unknown;
151 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
152 bool SavedRuntimeMode = false;
153 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000154
155public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000156 /// Constructor for Non-SPMD mode.
157 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
158 : ExecMode(ExecMode) {
159 SavedExecMode = ExecMode;
160 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000161 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000162 /// Constructor for SPMD mode.
163 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
164 bool &RuntimeMode, bool FullRuntimeMode)
165 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
166 SavedExecMode = ExecMode;
167 SavedRuntimeMode = RuntimeMode;
168 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
169 RuntimeMode = FullRuntimeMode;
170 }
171 ~ExecutionRuntimeModesRAII() {
172 ExecMode = SavedExecMode;
173 if (RuntimeMode)
174 *RuntimeMode = SavedRuntimeMode;
175 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000176};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000177
178/// GPU Configuration: This information can be derived from cuda registers,
179/// however, providing compile time constants helps generate more efficient
180/// code. For all practical purposes this is fine because the configuration
181/// is the same for all known NVPTX architectures.
182enum MachineConfiguration : unsigned {
183 WarpSize = 32,
184 /// Number of bits required to represent a lane identifier, which is
185 /// computed as log_2(WarpSize).
186 LaneIDBits = 5,
187 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000188
189 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000190 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000191
192 /// Maximal size of the shared memory buffer.
193 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000194};
195
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000196static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
197 RefExpr = RefExpr->IgnoreParens();
198 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
199 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
200 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
201 Base = TempASE->getBase()->IgnoreParenImpCasts();
202 RefExpr = Base;
203 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
204 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
205 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
206 Base = TempOASE->getBase()->IgnoreParenImpCasts();
207 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
208 Base = TempASE->getBase()->IgnoreParenImpCasts();
209 RefExpr = Base;
210 }
211 RefExpr = RefExpr->IgnoreParenImpCasts();
212 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
213 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
214 const auto *ME = cast<MemberExpr>(RefExpr);
215 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
216}
217
Alexey Bataev2adecff2018-09-21 14:22:53 +0000218typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
219static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
220 return P1.first > P2.first;
221}
222
223static RecordDecl *buildRecordForGlobalizedVars(
224 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000225 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000226 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
227 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000228 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000229 return nullptr;
230 SmallVector<VarsDataTy, 4> GlobalizedVars;
231 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000232 GlobalizedVars.emplace_back(
233 CharUnits::fromQuantity(std::max(
234 C.getDeclAlign(D).getQuantity(),
235 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
236 D);
237 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000238 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
239 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
240 stable_sort_comparator);
241 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000242 // /* globalized vars */[WarSize] align (max(decl_align,
243 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000244 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000245 // };
246 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
247 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000248 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
249 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 for (const auto &Pair : GlobalizedVars) {
251 const ValueDecl *VD = Pair.second;
252 QualType Type = VD->getType();
253 if (Type->isLValueReferenceType())
254 Type = C.getPointerType(Type.getNonReferenceType());
255 else
256 Type = Type.getNonReferenceType();
257 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000258 FieldDecl *Field;
259 if (SingleEscaped.count(VD)) {
260 Field = FieldDecl::Create(
261 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
262 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
263 /*BW=*/nullptr, /*Mutable=*/false,
264 /*InitStyle=*/ICIS_NoInit);
265 Field->setAccess(AS_public);
266 if (VD->hasAttrs()) {
267 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
268 E(VD->getAttrs().end());
269 I != E; ++I)
270 Field->addAttr(*I);
271 }
272 } else {
273 llvm::APInt ArraySize(32, WarpSize);
274 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
275 Field = FieldDecl::Create(
276 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
277 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
278 /*BW=*/nullptr, /*Mutable=*/false,
279 /*InitStyle=*/ICIS_NoInit);
280 Field->setAccess(AS_public);
281 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
282 static_cast<CharUnits::QuantityType>(
283 GlobalMemoryAlignment)));
284 Field->addAttr(AlignedAttr::CreateImplicit(
285 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
286 IntegerLiteral::Create(C, Align,
287 C.getIntTypeForBitwidth(32, /*Signed=*/0),
288 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000289 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000290 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000291 MappedDeclsFields.try_emplace(VD, Field);
292 }
293 GlobalizedRD->completeDefinition();
294 return GlobalizedRD;
295}
296
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000297/// Get the list of variables that can escape their declaration context.
298class CheckVarsEscapingDeclContext final
299 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
300 CodeGenFunction &CGF;
301 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000302 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000303 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000304 RecordDecl *GlobalizedRD = nullptr;
305 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000306 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000307 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000308
309 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000310 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000311 if (!isa<VarDecl>(VD) ||
312 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000313 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000314 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000315 // Variables captured by value must be globalized.
316 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000317 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000318 // Check if need to capture the variable that was already captured by
319 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000320 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000321 if (!FD->hasAttrs())
322 return;
323 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
324 if (!Attr)
325 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000326 if (((Attr->getCaptureKind() != OMPC_map) &&
327 !isOpenMPPrivate(
328 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
329 ((Attr->getCaptureKind() == OMPC_map) &&
330 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000331 return;
332 }
333 if (!FD->getType()->isReferenceType()) {
334 assert(!VD->getType()->isVariablyModifiedType() &&
335 "Parameter captured by value with variably modified type");
336 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000337 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000338 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000339 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000340 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000341 }
342 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000343 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000344 VD->getType()->isReferenceType())
345 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000346 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000347 if (VD->getType()->isVariablyModifiedType())
348 EscapedVariableLengthDecls.insert(VD);
349 else
350 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000351 }
352
353 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000354 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000355 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000356 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
357 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
358 const bool SavedAllEscaped = AllEscaped;
359 AllEscaped = VD->getType()->isLValueReferenceType();
360 Visit(VarD->getInit());
361 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000362 }
363 }
364 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000365 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
366 ArrayRef<OMPClause *> Clauses,
367 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 if (!S)
369 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000370 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000371 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
372 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000373 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
374 if (IsCombinedParallelRegion) {
375 // Check if the variable is privatized in the combined construct and
376 // those private copies must be shared in the inner parallel
377 // directive.
378 IsForCombinedParallelRegion = false;
379 for (const OMPClause *C : Clauses) {
380 if (!isOpenMPPrivate(C->getClauseKind()) ||
381 C->getClauseKind() == OMPC_reduction ||
382 C->getClauseKind() == OMPC_linear ||
383 C->getClauseKind() == OMPC_private)
384 continue;
385 ArrayRef<const Expr *> Vars;
386 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
387 Vars = PC->getVarRefs();
388 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
389 Vars = PC->getVarRefs();
390 else
391 llvm_unreachable("Unexpected clause.");
392 for (const auto *E : Vars) {
393 const Decl *D =
394 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
395 if (D == VD->getCanonicalDecl()) {
396 IsForCombinedParallelRegion = true;
397 break;
398 }
399 }
400 if (IsForCombinedParallelRegion)
401 break;
402 }
403 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000404 markAsEscaped(VD);
405 if (isa<OMPCapturedExprDecl>(VD))
406 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000407 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000408 }
409 }
410 }
411
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000412 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000413 assert(!GlobalizedRD &&
414 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000415 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000416 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000417 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
418 else
419 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000420 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000421 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000422 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000423 }
424
425public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000426 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
427 ArrayRef<const ValueDecl *> TeamsReductions)
428 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
429 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000430 virtual ~CheckVarsEscapingDeclContext() = default;
431 void VisitDeclStmt(const DeclStmt *S) {
432 if (!S)
433 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000434 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000435 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
436 VisitValueDecl(VD);
437 }
438 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
439 if (!D)
440 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000441 if (!D->hasAssociatedStmt())
442 return;
443 if (const auto *S =
444 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
445 // Do not analyze directives that do not actually require capturing,
446 // like `omp for` or `omp simd` directives.
447 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
448 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
449 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
450 VisitStmt(S->getCapturedStmt());
451 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000452 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000453 VisitOpenMPCapturedStmt(
454 S, D->clauses(),
455 CaptureRegions.back() == OMPD_parallel &&
456 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000457 }
458 }
459 void VisitCapturedStmt(const CapturedStmt *S) {
460 if (!S)
461 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000462 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
464 const ValueDecl *VD = C.getCapturedVar();
465 markAsEscaped(VD);
466 if (isa<OMPCapturedExprDecl>(VD))
467 VisitValueDecl(VD);
468 }
469 }
470 }
471 void VisitLambdaExpr(const LambdaExpr *E) {
472 if (!E)
473 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000474 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000475 if (C.capturesVariable()) {
476 if (C.getCaptureKind() == LCK_ByRef) {
477 const ValueDecl *VD = C.getCapturedVar();
478 markAsEscaped(VD);
479 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
480 VisitValueDecl(VD);
481 }
482 }
483 }
484 }
485 void VisitBlockExpr(const BlockExpr *E) {
486 if (!E)
487 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000488 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000489 if (C.isByRef()) {
490 const VarDecl *VD = C.getVariable();
491 markAsEscaped(VD);
492 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
493 VisitValueDecl(VD);
494 }
495 }
496 }
497 void VisitCallExpr(const CallExpr *E) {
498 if (!E)
499 return;
500 for (const Expr *Arg : E->arguments()) {
501 if (!Arg)
502 continue;
503 if (Arg->isLValue()) {
504 const bool SavedAllEscaped = AllEscaped;
505 AllEscaped = true;
506 Visit(Arg);
507 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000508 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000509 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000510 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000511 }
512 Visit(E->getCallee());
513 }
514 void VisitDeclRefExpr(const DeclRefExpr *E) {
515 if (!E)
516 return;
517 const ValueDecl *VD = E->getDecl();
518 if (AllEscaped)
519 markAsEscaped(VD);
520 if (isa<OMPCapturedExprDecl>(VD))
521 VisitValueDecl(VD);
522 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
523 if (VarD->isInitCapture())
524 VisitValueDecl(VD);
525 }
526 void VisitUnaryOperator(const UnaryOperator *E) {
527 if (!E)
528 return;
529 if (E->getOpcode() == UO_AddrOf) {
530 const bool SavedAllEscaped = AllEscaped;
531 AllEscaped = true;
532 Visit(E->getSubExpr());
533 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000534 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000535 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000536 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000537 }
538 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
539 if (!E)
540 return;
541 if (E->getCastKind() == CK_ArrayToPointerDecay) {
542 const bool SavedAllEscaped = AllEscaped;
543 AllEscaped = true;
544 Visit(E->getSubExpr());
545 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000546 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000547 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000548 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000549 }
550 void VisitExpr(const Expr *E) {
551 if (!E)
552 return;
553 bool SavedAllEscaped = AllEscaped;
554 if (!E->isLValue())
555 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000556 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000557 if (Child)
558 Visit(Child);
559 AllEscaped = SavedAllEscaped;
560 }
561 void VisitStmt(const Stmt *S) {
562 if (!S)
563 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000564 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000565 if (Child)
566 Visit(Child);
567 }
568
Alexey Bataevc99042b2018-03-15 18:10:54 +0000569 /// Returns the record that handles all the escaped local variables and used
570 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000571 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000572 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000573 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000574 return GlobalizedRD;
575 }
576
Alexey Bataevc99042b2018-03-15 18:10:54 +0000577 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000578 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
579 assert(GlobalizedRD &&
580 "Record for globalized variables must be generated already.");
581 auto I = MappedDeclsFields.find(VD);
582 if (I == MappedDeclsFields.end())
583 return nullptr;
584 return I->getSecond();
585 }
586
Alexey Bataevc99042b2018-03-15 18:10:54 +0000587 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000588 ArrayRef<const ValueDecl *> getEscapedDecls() const {
589 return EscapedDecls.getArrayRef();
590 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000591
592 /// Checks if the escaped local variable is actually a parameter passed by
593 /// value.
594 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
595 return EscapedParameters;
596 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000597
598 /// Returns the list of the escaped variables with the variably modified
599 /// types.
600 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
601 return EscapedVariableLengthDecls.getArrayRef();
602 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000603};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000604} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000605
606/// Get the GPU warp size.
607static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000608 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000609 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000610 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000611 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000612}
613
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000614/// Get the id of the current thread on the GPU.
615static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000616 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000617 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000618 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000620}
621
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000622/// Get the id of the warp in the block.
623/// We assume that the warp size is 32, which is always the case
624/// on the NVPTX device, to generate more efficient code.
625static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
626 CGBuilderTy &Bld = CGF.Builder;
627 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
628}
629
630/// Get the id of the current lane in the Warp.
631/// We assume that the warp size is 32, which is always the case
632/// on the NVPTX device, to generate more efficient code.
633static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
634 CGBuilderTy &Bld = CGF.Builder;
635 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
636 "nvptx_lane_id");
637}
638
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000639/// Get the maximum number of threads in a block of the GPU.
640static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000641 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000642 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000643 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000644 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000645}
646
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000647/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000648/// For the 'generic' execution mode, the runtime encodes thread_limit in
649/// the launch parameters, always starting thread_limit+warpSize threads per
650/// CTA. The threads in the last warp are reserved for master execution.
651/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
652static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000653 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000654 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000655 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000656 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000657 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
658 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000659}
660
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000661/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000662/// The master thread id is the first thread (lane) of the last warp in the
663/// GPU block. Warp size is assumed to be some power of 2.
664/// Thread id is 0 indexed.
665/// E.g: If NumThreads is 33, master id is 32.
666/// If NumThreads is 64, master id is 32.
667/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000668static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000669 CGBuilderTy &Bld = CGF.Builder;
670 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
671
672 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000673 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000674
Alexey Bataeve290ec02018-04-06 16:03:36 +0000675 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000676 Bld.CreateNot(Mask), "master_tid");
677}
678
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000679CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000680 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000681 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
682 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000684}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000685
686void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
687 CodeGenModule &CGM) {
688 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689
690 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000691 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000692 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000693 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000694 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695}
696
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000697CGOpenMPRuntimeNVPTX::ExecutionMode
698CGOpenMPRuntimeNVPTX::getExecutionMode() const {
699 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000700}
701
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000702static CGOpenMPRuntimeNVPTX::DataSharingMode
703getDataSharingMode(CodeGenModule &CGM) {
704 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
705 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000706}
707
Alexey Bataev7bb33532019-01-07 21:30:43 +0000708/// Checks if the expression is constant or does not have non-trivial function
709/// calls.
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000710static bool isTrivial(ASTContext &Ctx, const Expr * E) {
711 // We can skip constant expressions.
712 // We can skip expressions with trivial calls or simple expressions.
713 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
714 !E->hasNonTrivialCall(Ctx)) &&
715 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
716}
717
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000718/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000719/// iff there is only one that is not evaluatable at the compile time.
720static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
721 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
722 const Stmt *Child = nullptr;
723 for (const Stmt *S : C->body()) {
724 if (const auto *E = dyn_cast<Expr>(S)) {
725 if (isTrivial(Ctx, E))
726 continue;
727 }
728 // Some of the statements can be ignored.
729 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
730 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
731 continue;
732 // Analyze declarations.
733 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
734 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
735 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
736 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
737 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
738 isa<UsingDirectiveDecl>(D) ||
739 isa<OMPDeclareReductionDecl>(D) ||
740 isa<OMPThreadPrivateDecl>(D))
741 return true;
742 const auto *VD = dyn_cast<VarDecl>(D);
743 if (!VD)
744 return false;
745 return VD->isConstexpr() ||
746 ((VD->getType().isTrivialType(Ctx) ||
747 VD->getType()->isReferenceType()) &&
748 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
749 }))
750 continue;
751 }
752 // Found multiple children - cannot get the one child only.
753 if (Child)
754 return Body;
755 Child = S;
756 }
757 if (Child)
758 return Child;
759 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000760 return Body;
761}
762
763/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000764/// false condition. Also, check if the number of threads is strictly specified
765/// and run those directives in non-SPMD mode.
766static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
767 const OMPExecutableDirective &D) {
768 if (D.hasClausesOfKind<OMPNumThreadsClause>())
769 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000770 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
771 OpenMPDirectiveKind NameModifier = C->getNameModifier();
772 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
773 continue;
774 const Expr *Cond = C->getCondition();
775 bool Result;
776 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
777 return true;
778 }
779 return false;
780}
781
782/// Check for inner (nested) SPMD construct, if any
783static bool hasNestedSPMDDirective(ASTContext &Ctx,
784 const OMPExecutableDirective &D) {
785 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000786 const auto *Body =
787 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000788 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000789
790 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
791 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000792 switch (D.getDirectiveKind()) {
793 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000794 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000795 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000796 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000797 if (DKind == OMPD_teams) {
798 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
799 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000800 if (!Body)
801 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000802 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000803 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
804 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000805 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000806 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000807 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000808 }
809 }
810 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000811 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000812 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000813 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000814 case OMPD_target_simd:
815 case OMPD_target_parallel:
816 case OMPD_target_parallel_for:
817 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000818 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 case OMPD_target_teams_distribute_simd:
820 case OMPD_target_teams_distribute_parallel_for:
821 case OMPD_target_teams_distribute_parallel_for_simd:
822 case OMPD_parallel:
823 case OMPD_for:
824 case OMPD_parallel_for:
825 case OMPD_parallel_sections:
826 case OMPD_for_simd:
827 case OMPD_parallel_for_simd:
828 case OMPD_cancel:
829 case OMPD_cancellation_point:
830 case OMPD_ordered:
831 case OMPD_threadprivate:
832 case OMPD_task:
833 case OMPD_simd:
834 case OMPD_sections:
835 case OMPD_section:
836 case OMPD_single:
837 case OMPD_master:
838 case OMPD_critical:
839 case OMPD_taskyield:
840 case OMPD_barrier:
841 case OMPD_taskwait:
842 case OMPD_taskgroup:
843 case OMPD_atomic:
844 case OMPD_flush:
845 case OMPD_teams:
846 case OMPD_target_data:
847 case OMPD_target_exit_data:
848 case OMPD_target_enter_data:
849 case OMPD_distribute:
850 case OMPD_distribute_simd:
851 case OMPD_distribute_parallel_for:
852 case OMPD_distribute_parallel_for_simd:
853 case OMPD_teams_distribute:
854 case OMPD_teams_distribute_simd:
855 case OMPD_teams_distribute_parallel_for:
856 case OMPD_teams_distribute_parallel_for_simd:
857 case OMPD_target_update:
858 case OMPD_declare_simd:
859 case OMPD_declare_target:
860 case OMPD_end_declare_target:
861 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000862 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000863 case OMPD_taskloop:
864 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000865 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000866 case OMPD_unknown:
867 llvm_unreachable("Unexpected directive.");
868 }
869 }
870
871 return false;
872}
873
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000874static bool supportsSPMDExecutionMode(ASTContext &Ctx,
875 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000876 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
877 switch (DirectiveKind) {
878 case OMPD_target:
879 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000880 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000881 case OMPD_target_parallel:
882 case OMPD_target_parallel_for:
883 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000884 case OMPD_target_teams_distribute_parallel_for:
885 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000886 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000887 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000888 case OMPD_target_teams_distribute:
889 case OMPD_target_teams_distribute_simd:
890 return false;
891 case OMPD_parallel:
892 case OMPD_for:
893 case OMPD_parallel_for:
894 case OMPD_parallel_sections:
895 case OMPD_for_simd:
896 case OMPD_parallel_for_simd:
897 case OMPD_cancel:
898 case OMPD_cancellation_point:
899 case OMPD_ordered:
900 case OMPD_threadprivate:
901 case OMPD_task:
902 case OMPD_simd:
903 case OMPD_sections:
904 case OMPD_section:
905 case OMPD_single:
906 case OMPD_master:
907 case OMPD_critical:
908 case OMPD_taskyield:
909 case OMPD_barrier:
910 case OMPD_taskwait:
911 case OMPD_taskgroup:
912 case OMPD_atomic:
913 case OMPD_flush:
914 case OMPD_teams:
915 case OMPD_target_data:
916 case OMPD_target_exit_data:
917 case OMPD_target_enter_data:
918 case OMPD_distribute:
919 case OMPD_distribute_simd:
920 case OMPD_distribute_parallel_for:
921 case OMPD_distribute_parallel_for_simd:
922 case OMPD_teams_distribute:
923 case OMPD_teams_distribute_simd:
924 case OMPD_teams_distribute_parallel_for:
925 case OMPD_teams_distribute_parallel_for_simd:
926 case OMPD_target_update:
927 case OMPD_declare_simd:
928 case OMPD_declare_target:
929 case OMPD_end_declare_target:
930 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000931 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000932 case OMPD_taskloop:
933 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000934 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000935 case OMPD_unknown:
936 break;
937 }
938 llvm_unreachable(
939 "Unknown programming model for OpenMP directive on NVPTX target.");
940}
941
942/// Check if the directive is loops based and has schedule clause at all or has
943/// static scheduling.
944static bool hasStaticScheduling(const OMPExecutableDirective &D) {
945 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
946 isOpenMPLoopDirective(D.getDirectiveKind()) &&
947 "Expected loop-based directive.");
948 return !D.hasClausesOfKind<OMPOrderedClause>() &&
949 (!D.hasClausesOfKind<OMPScheduleClause>() ||
950 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
951 [](const OMPScheduleClause *C) {
952 return C->getScheduleKind() == OMPC_SCHEDULE_static;
953 }));
954}
955
956/// Check for inner (nested) lightweight runtime construct, if any
957static bool hasNestedLightweightDirective(ASTContext &Ctx,
958 const OMPExecutableDirective &D) {
959 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
960 const auto *CS = D.getInnermostCapturedStmt();
961 const auto *Body =
962 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000963 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000964
965 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
966 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
967 switch (D.getDirectiveKind()) {
968 case OMPD_target:
969 if (isOpenMPParallelDirective(DKind) &&
970 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
971 hasStaticScheduling(*NestedDir))
972 return true;
973 if (DKind == OMPD_parallel) {
974 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
975 /*IgnoreCaptured=*/true);
976 if (!Body)
977 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000978 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000979 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
980 DKind = NND->getDirectiveKind();
981 if (isOpenMPWorksharingDirective(DKind) &&
982 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
983 return true;
984 }
985 } else if (DKind == OMPD_teams) {
986 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
987 /*IgnoreCaptured=*/true);
988 if (!Body)
989 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000990 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000991 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
992 DKind = NND->getDirectiveKind();
993 if (isOpenMPParallelDirective(DKind) &&
994 isOpenMPWorksharingDirective(DKind) &&
995 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
996 return true;
997 if (DKind == OMPD_parallel) {
998 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
999 /*IgnoreCaptured=*/true);
1000 if (!Body)
1001 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001002 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001003 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1004 DKind = NND->getDirectiveKind();
1005 if (isOpenMPWorksharingDirective(DKind) &&
1006 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1007 return true;
1008 }
1009 }
1010 }
1011 }
1012 return false;
1013 case OMPD_target_teams:
1014 if (isOpenMPParallelDirective(DKind) &&
1015 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1016 hasStaticScheduling(*NestedDir))
1017 return true;
1018 if (DKind == OMPD_parallel) {
1019 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1020 /*IgnoreCaptured=*/true);
1021 if (!Body)
1022 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001023 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001024 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1025 DKind = NND->getDirectiveKind();
1026 if (isOpenMPWorksharingDirective(DKind) &&
1027 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1028 return true;
1029 }
1030 }
1031 return false;
1032 case OMPD_target_parallel:
1033 return isOpenMPWorksharingDirective(DKind) &&
1034 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1035 case OMPD_target_teams_distribute:
1036 case OMPD_target_simd:
1037 case OMPD_target_parallel_for:
1038 case OMPD_target_parallel_for_simd:
1039 case OMPD_target_teams_distribute_simd:
1040 case OMPD_target_teams_distribute_parallel_for:
1041 case OMPD_target_teams_distribute_parallel_for_simd:
1042 case OMPD_parallel:
1043 case OMPD_for:
1044 case OMPD_parallel_for:
1045 case OMPD_parallel_sections:
1046 case OMPD_for_simd:
1047 case OMPD_parallel_for_simd:
1048 case OMPD_cancel:
1049 case OMPD_cancellation_point:
1050 case OMPD_ordered:
1051 case OMPD_threadprivate:
1052 case OMPD_task:
1053 case OMPD_simd:
1054 case OMPD_sections:
1055 case OMPD_section:
1056 case OMPD_single:
1057 case OMPD_master:
1058 case OMPD_critical:
1059 case OMPD_taskyield:
1060 case OMPD_barrier:
1061 case OMPD_taskwait:
1062 case OMPD_taskgroup:
1063 case OMPD_atomic:
1064 case OMPD_flush:
1065 case OMPD_teams:
1066 case OMPD_target_data:
1067 case OMPD_target_exit_data:
1068 case OMPD_target_enter_data:
1069 case OMPD_distribute:
1070 case OMPD_distribute_simd:
1071 case OMPD_distribute_parallel_for:
1072 case OMPD_distribute_parallel_for_simd:
1073 case OMPD_teams_distribute:
1074 case OMPD_teams_distribute_simd:
1075 case OMPD_teams_distribute_parallel_for:
1076 case OMPD_teams_distribute_parallel_for_simd:
1077 case OMPD_target_update:
1078 case OMPD_declare_simd:
1079 case OMPD_declare_target:
1080 case OMPD_end_declare_target:
1081 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001082 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001083 case OMPD_taskloop:
1084 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001085 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001086 case OMPD_unknown:
1087 llvm_unreachable("Unexpected directive.");
1088 }
1089 }
1090
1091 return false;
1092}
1093
1094/// Checks if the construct supports lightweight runtime. It must be SPMD
1095/// construct + inner loop-based construct with static scheduling.
1096static bool supportsLightweightRuntime(ASTContext &Ctx,
1097 const OMPExecutableDirective &D) {
1098 if (!supportsSPMDExecutionMode(Ctx, D))
1099 return false;
1100 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1101 switch (DirectiveKind) {
1102 case OMPD_target:
1103 case OMPD_target_teams:
1104 case OMPD_target_parallel:
1105 return hasNestedLightweightDirective(Ctx, D);
1106 case OMPD_target_parallel_for:
1107 case OMPD_target_parallel_for_simd:
1108 case OMPD_target_teams_distribute_parallel_for:
1109 case OMPD_target_teams_distribute_parallel_for_simd:
1110 // (Last|First)-privates must be shared in parallel region.
1111 return hasStaticScheduling(D);
1112 case OMPD_target_simd:
1113 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001114 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001115 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001116 case OMPD_parallel:
1117 case OMPD_for:
1118 case OMPD_parallel_for:
1119 case OMPD_parallel_sections:
1120 case OMPD_for_simd:
1121 case OMPD_parallel_for_simd:
1122 case OMPD_cancel:
1123 case OMPD_cancellation_point:
1124 case OMPD_ordered:
1125 case OMPD_threadprivate:
1126 case OMPD_task:
1127 case OMPD_simd:
1128 case OMPD_sections:
1129 case OMPD_section:
1130 case OMPD_single:
1131 case OMPD_master:
1132 case OMPD_critical:
1133 case OMPD_taskyield:
1134 case OMPD_barrier:
1135 case OMPD_taskwait:
1136 case OMPD_taskgroup:
1137 case OMPD_atomic:
1138 case OMPD_flush:
1139 case OMPD_teams:
1140 case OMPD_target_data:
1141 case OMPD_target_exit_data:
1142 case OMPD_target_enter_data:
1143 case OMPD_distribute:
1144 case OMPD_distribute_simd:
1145 case OMPD_distribute_parallel_for:
1146 case OMPD_distribute_parallel_for_simd:
1147 case OMPD_teams_distribute:
1148 case OMPD_teams_distribute_simd:
1149 case OMPD_teams_distribute_parallel_for:
1150 case OMPD_teams_distribute_parallel_for_simd:
1151 case OMPD_target_update:
1152 case OMPD_declare_simd:
1153 case OMPD_declare_target:
1154 case OMPD_end_declare_target:
1155 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001156 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001157 case OMPD_taskloop:
1158 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001159 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001160 case OMPD_unknown:
1161 break;
1162 }
1163 llvm_unreachable(
1164 "Unknown programming model for OpenMP directive on NVPTX target.");
1165}
1166
1167void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168 StringRef ParentName,
1169 llvm::Function *&OutlinedFn,
1170 llvm::Constant *&OutlinedFnID,
1171 bool IsOffloadEntry,
1172 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001173 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001175 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001176 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001177 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001178
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001179 // Emit target region as a standalone region.
1180 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001181 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1182 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001183
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001185 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001186 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001187 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001188 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001189 auto &RT =
1190 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001191 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1192 // Skip target region initialization.
1193 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 }
1195 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001196 auto &RT =
1197 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001198 RT.clearLocThreadIdInsertPt(CGF);
1199 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001200 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001201 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001202 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001203 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001204 // Reserve place for the globalized memory.
1205 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001206 if (!KernelStaticGlobalized) {
1207 KernelStaticGlobalized = new llvm::GlobalVariable(
1208 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1209 llvm::GlobalValue::InternalLinkage,
1210 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1211 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1212 llvm::GlobalValue::NotThreadLocal,
1213 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1214 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001215 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1216 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001217 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001218
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 // Now change the name of the worker function to correspond to this target
1220 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001221 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001222
1223 // Create the worker function
1224 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225}
1226
1227// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001228void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001229 EntryFunctionState &EST,
1230 WorkerFunctionState &WST) {
1231 CGBuilderTy &Bld = CGF.Builder;
1232
1233 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1234 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1235 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1236 EST.ExitBB = CGF.createBasicBlock(".exit");
1237
Alexey Bataev9ff80832018-04-16 20:16:21 +00001238 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001239 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1240 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1241
1242 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001243 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001244 CGF.EmitBranch(EST.ExitBB);
1245
1246 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001247 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001248 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1249 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1250
1251 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001252 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001253 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 // First action in sequential region:
1255 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001256 // TODO: Optimize runtime initialization and pass in correct value.
1257 llvm::Value *Args[] = {getThreadLimit(CGF),
1258 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001259 CGF.EmitRuntimeCall(
1260 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001261
1262 // For data sharing, we need to initialize the stack.
1263 CGF.EmitRuntimeCall(
1264 createNVPTXRuntimeFunction(
1265 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1266
Alexey Bataevc99042b2018-03-15 18:10:54 +00001267 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001268}
1269
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001270void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001271 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001272 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001273 if (!CGF.HaveInsertPoint())
1274 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001275
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001276 emitGenericVarsEpilog(CGF);
1277
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001278 if (!EST.ExitBB)
1279 EST.ExitBB = CGF.createBasicBlock(".exit");
1280
1281 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1282 CGF.EmitBranch(TerminateBB);
1283
1284 CGF.EmitBlock(TerminateBB);
1285 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001286 // TODO: Optimize runtime initialization and pass in correct value.
1287 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001288 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001289 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001290 // Barrier to terminate worker threads.
1291 syncCTAThreads(CGF);
1292 // Master thread jumps to exit point.
1293 CGF.EmitBranch(EST.ExitBB);
1294
1295 CGF.EmitBlock(EST.ExitBB);
1296 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001297}
1298
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001299void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001300 StringRef ParentName,
1301 llvm::Function *&OutlinedFn,
1302 llvm::Constant *&OutlinedFnID,
1303 bool IsOffloadEntry,
1304 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001305 ExecutionRuntimeModesRAII ModeRAII(
1306 CurrentExecutionMode, RequiresFullRuntime,
1307 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1308 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001309 EntryFunctionState EST;
1310
1311 // Emit target region as a standalone region.
1312 class NVPTXPrePostActionTy : public PrePostActionTy {
1313 CGOpenMPRuntimeNVPTX &RT;
1314 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1315 const OMPExecutableDirective &D;
1316
1317 public:
1318 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1319 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1320 const OMPExecutableDirective &D)
1321 : RT(RT), EST(EST), D(D) {}
1322 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001323 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001324 // Skip target region initialization.
1325 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326 }
1327 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001328 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001329 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001330 }
1331 } Action(*this, EST, D);
1332 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001333 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001334 // Reserve place for the globalized memory.
1335 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001336 if (!KernelStaticGlobalized) {
1337 KernelStaticGlobalized = new llvm::GlobalVariable(
1338 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1339 llvm::GlobalValue::InternalLinkage,
1340 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1341 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1342 llvm::GlobalValue::NotThreadLocal,
1343 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1344 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001345 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1346 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001347 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348}
1349
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001350void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351 CodeGenFunction &CGF, EntryFunctionState &EST,
1352 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001353 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001354
1355 // Setup BBs in entry function.
1356 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1357 EST.ExitBB = CGF.createBasicBlock(".exit");
1358
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001359 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1360 /*RequiresOMPRuntime=*/
1361 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1362 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001363 CGF.EmitRuntimeCall(
1364 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001365
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001366 if (RequiresFullRuntime) {
1367 // For data sharing, we need to initialize the stack.
1368 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1369 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1370 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001371
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001372 CGF.EmitBranch(ExecuteBB);
1373
1374 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001375
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001376 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001377}
1378
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001379void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001380 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001381 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001382 if (!CGF.HaveInsertPoint())
1383 return;
1384
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001385 if (!EST.ExitBB)
1386 EST.ExitBB = CGF.createBasicBlock(".exit");
1387
1388 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1389 CGF.EmitBranch(OMPDeInitBB);
1390
1391 CGF.EmitBlock(OMPDeInitBB);
1392 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001393 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1394 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001395 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001396 createNVPTXRuntimeFunction(
1397 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001398 CGF.EmitBranch(EST.ExitBB);
1399
1400 CGF.EmitBlock(EST.ExitBB);
1401 EST.ExitBB = nullptr;
1402}
1403
1404// Create a unique global variable to indicate the execution mode of this target
1405// region. The execution mode is either 'generic', or 'spmd' depending on the
1406// target directive. This variable is picked up by the offload library to setup
1407// the device appropriately before kernel launch. If the execution mode is
1408// 'generic', the runtime reserves one warp for the master, otherwise, all
1409// warps participate in parallel work.
1410static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001411 bool Mode) {
1412 auto *GVMode =
1413 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1414 llvm::GlobalValue::WeakAnyLinkage,
1415 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1416 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001417 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001418}
1419
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001420void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001421 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001422
1423 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001424 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001425 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001426 emitWorkerLoop(CGF, WST);
1427 CGF.FinishFunction();
1428}
1429
1430void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1431 WorkerFunctionState &WST) {
1432 //
1433 // The workers enter this loop and wait for parallel work from the master.
1434 // When the master encounters a parallel region it sets up the work + variable
1435 // arguments, and wakes up the workers. The workers first check to see if
1436 // they are required for the parallel region, i.e., within the # of requested
1437 // parallel threads. The activated workers load the variable arguments and
1438 // execute the parallel work.
1439 //
1440
1441 CGBuilderTy &Bld = CGF.Builder;
1442
1443 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1444 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1445 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1446 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1447 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1448 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1449
1450 CGF.EmitBranch(AwaitBB);
1451
1452 // Workers wait for work from master.
1453 CGF.EmitBlock(AwaitBB);
1454 // Wait for parallel work
1455 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001456
1457 Address WorkFn =
1458 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1459 Address ExecStatus =
1460 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1461 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1462 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1463
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001464 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001465 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001466 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001467 llvm::Value *Ret = CGF.EmitRuntimeCall(
1468 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1469 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001470
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001471 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001472 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1473 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001474 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1475
1476 // Activate requested workers.
1477 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001478 llvm::Value *IsActive =
1479 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1480 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001481
1482 // Signal start of parallel region.
1483 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001484 // Skip initialization.
1485 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001486
1487 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001488 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001489 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001490 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001491
1492 llvm::Value *WorkFnMatch =
1493 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1494
1495 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1496 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1497 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1498
1499 // Execute this outlined function.
1500 CGF.EmitBlock(ExecuteFNBB);
1501
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001502 // Insert call to work function via shared wrapper. The shared
1503 // wrapper takes two arguments:
1504 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001505 // - the thread ID;
1506 emitCall(CGF, WST.Loc, W,
1507 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001508
1509 // Go to end of parallel region.
1510 CGF.EmitBranch(TerminateBB);
1511
1512 CGF.EmitBlock(CheckNextBB);
1513 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001514 // Default case: call to outlined function through pointer if the target
1515 // region makes a declare target call that may contain an orphaned parallel
1516 // directive.
1517 auto *ParallelFnTy =
1518 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001519 /*isVarArg=*/false);
1520 llvm::Value *WorkFnCast =
1521 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001522 // Insert call to work function via shared wrapper. The shared
1523 // wrapper takes two arguments:
1524 // - the parallelism level;
1525 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001526 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001527 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1528 // Go to end of parallel region.
1529 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001530
1531 // Signal end of parallel region.
1532 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001533 CGF.EmitRuntimeCall(
1534 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1535 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001536 CGF.EmitBranch(BarrierBB);
1537
1538 // All active and inactive workers wait at a barrier after parallel region.
1539 CGF.EmitBlock(BarrierBB);
1540 // Barrier after parallel region.
1541 syncCTAThreads(CGF);
1542 CGF.EmitBranch(AwaitBB);
1543
1544 // Exit target region.
1545 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001546 // Skip initialization.
1547 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001548}
1549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001550/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001551/// implementation. Specialized for the NVPTX device.
1552/// \param Function OpenMP runtime function.
1553/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001554llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001555CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001556 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001557 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1558 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001559 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1560 // RequiresOMPRuntime);
1561 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001562 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001563 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1565 break;
1566 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001567 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001568 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1569 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001570 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001571 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001572 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1573 break;
1574 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001575 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1576 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001577 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001578 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001579 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001580 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1581 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1582 break;
1583 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001584 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1585 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1586 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001587 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001590 break;
1591 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001592 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1593 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001594 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001595 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001596 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1599 break;
1600 }
1601 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001602 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1603 /// int16_t IsOMPRuntimeInitialized);
1604 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001605 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001606 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001607 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1609 break;
1610 }
1611 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1612 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001613 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001614 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1615 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1616 break;
1617 }
1618 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1619 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1620 // global_tid);
1621 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001622 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001623 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1625 break;
1626 }
1627 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1628 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1629 // global_tid);
1630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001631 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1634 break;
1635 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001636 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1637 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1638 // int16_t lane_offset, int16_t warp_size);
1639 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001640 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001641 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1643 break;
1644 }
1645 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1646 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1647 // int16_t lane_offset, int16_t warp_size);
1648 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001649 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001650 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1652 break;
1653 }
Alexey Bataev8e009032019-01-04 17:25:09 +00001654 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2: {
1655 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1656 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1657 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1658 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1659 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001660 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1661 CGM.Int16Ty, CGM.Int16Ty};
1662 auto *ShuffleReduceFnTy =
1663 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1664 /*isVarArg=*/false);
1665 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1666 auto *InterWarpCopyFnTy =
1667 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1668 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001669 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1670 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001671 CGM.Int32Ty,
1672 CGM.SizeTy,
1673 CGM.VoidPtrTy,
1674 ShuffleReduceFnTy->getPointerTo(),
1675 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001676 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001677 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1678 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001679 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001680 break;
1681 }
1682 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1683 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1684 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001685 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1687 RTLFn = CGM.CreateRuntimeFunction(
1688 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1689 break;
1690 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001691 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1692 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1693 // global_tid, kmp_critical_name *lck)
1694 llvm::Type *TypeParams[] = {
1695 getIdentTyPointerTy(), CGM.Int32Ty,
1696 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1697 auto *FnTy =
1698 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1699 RTLFn = CGM.CreateRuntimeFunction(
1700 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1701 break;
1702 }
1703 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1704 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1705 // global_tid, kmp_critical_name *lck)
1706 llvm::Type *TypeParams[] = {
1707 getIdentTyPointerTy(), CGM.Int32Ty,
1708 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1709 auto *FnTy =
1710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1711 RTLFn = CGM.CreateRuntimeFunction(
1712 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1713 break;
1714 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001715 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1716 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001717 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001718 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1719 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1720 break;
1721 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001722 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1723 /// Build void __kmpc_data_sharing_init_stack_spmd();
1724 auto *FnTy =
1725 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001726 RTLFn =
1727 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001728 break;
1729 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001730 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1731 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001732 // int16_t UseSharedMemory);
1733 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001734 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001735 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1736 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001737 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001738 break;
1739 }
1740 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1741 // Build void __kmpc_data_sharing_pop_stack(void *a);
1742 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001743 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001744 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1745 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1746 /*Name=*/"__kmpc_data_sharing_pop_stack");
1747 break;
1748 }
1749 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1750 /// Build void __kmpc_begin_sharing_variables(void ***args,
1751 /// size_t n_args);
1752 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001753 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001754 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1755 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1756 break;
1757 }
1758 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1759 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001760 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001761 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1763 break;
1764 }
1765 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1766 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1767 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001768 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001769 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1771 break;
1772 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001773 case OMPRTL_NVPTX__kmpc_parallel_level: {
1774 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1775 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1776 auto *FnTy =
1777 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1778 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1779 break;
1780 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001781 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1782 // Build int8_t __kmpc_is_spmd_exec_mode();
1783 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1785 break;
1786 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001787 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001788 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1789 // const void *buf, size_t size, int16_t is_shared, const void **res);
1790 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1791 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001792 auto *FnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1795 break;
1796 }
1797 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001798 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1799 // int16_t is_shared);
1800 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001801 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001803 RTLFn =
1804 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1805 break;
1806 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001807 case OMPRTL__kmpc_barrier: {
1808 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1810 auto *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001813 cast<llvm::Function>(RTLFn.getCallee())
1814 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001815 break;
1816 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001817 case OMPRTL__kmpc_barrier_simple_spmd: {
1818 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1819 // global_tid);
1820 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1821 auto *FnTy =
1822 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1823 RTLFn =
1824 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001825 cast<llvm::Function>(RTLFn.getCallee())
1826 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001827 break;
1828 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001829 }
1830 return RTLFn;
1831}
1832
1833void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1834 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001835 uint64_t Size, int32_t,
1836 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001837 // TODO: Add support for global variables on the device after declare target
1838 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001839 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001840 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001841 llvm::Module &M = CGM.getModule();
1842 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843
1844 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001845 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846
1847 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001848 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001849 llvm::ConstantAsMetadata::get(
1850 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1851 // Append metadata to nvvm.annotations
1852 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1853}
1854
1855void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1856 const OMPExecutableDirective &D, StringRef ParentName,
1857 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001858 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001859 if (!IsOffloadEntry) // Nothing to do.
1860 return;
1861
1862 assert(!ParentName.empty() && "Invalid target region parent name!");
1863
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001864 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001865 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001866 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001867 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001868 else
1869 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1870 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001871
1872 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001873}
1874
Alexey Bataevceeaa482018-11-21 21:04:34 +00001875namespace {
1876LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1877/// Enum for accesseing the reserved_2 field of the ident_t struct.
1878enum ModeFlagsTy : unsigned {
1879 /// Bit set to 1 when in SPMD mode.
1880 KMP_IDENT_SPMD_MODE = 0x01,
1881 /// Bit set to 1 when a simplified runtime is used.
1882 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1883 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1884};
1885
1886/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1887static const ModeFlagsTy UndefinedMode =
1888 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1889} // anonymous namespace
1890
1891unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001892 switch (getExecutionMode()) {
1893 case EM_SPMD:
1894 if (requiresFullRuntime())
1895 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1896 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1897 case EM_NonSPMD:
1898 assert(requiresFullRuntime() && "Expected full runtime.");
1899 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1900 case EM_Unknown:
1901 return UndefinedMode;
1902 }
1903 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001904}
1905
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001906CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001907 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001908 if (!CGM.getLangOpts().OpenMPIsDevice)
1909 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001910}
Carlo Bertollic6872252016-04-04 15:55:02 +00001911
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001912void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1913 OpenMPProcBindClauseKind ProcBind,
1914 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001915 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001916 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001917 return;
1918
1919 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1920}
1921
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001922void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1923 llvm::Value *NumThreads,
1924 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001925 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001926 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001927 return;
1928
1929 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1930}
1931
Carlo Bertollic6872252016-04-04 15:55:02 +00001932void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1933 const Expr *NumTeams,
1934 const Expr *ThreadLimit,
1935 SourceLocation Loc) {}
1936
James Y Knight9871db02019-02-05 16:42:33 +00001937llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001938 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1939 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001940 // Emit target region as a standalone region.
1941 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001942 bool &IsInParallelRegion;
1943 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001944
1945 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001946 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1947 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001948 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001949 PrevIsInParallelRegion = IsInParallelRegion;
1950 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001951 }
1952 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001953 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001954 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001955 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001956 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001957 bool PrevIsInTTDRegion = IsInTTDRegion;
1958 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001959 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1960 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001961 auto *OutlinedFun =
1962 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1963 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001964 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001965 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001966 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1967 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001968 llvm::Function *WrapperFun =
1969 createParallelDataSharingWrapper(OutlinedFun, D);
1970 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1971 }
1972
1973 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001974}
1975
Alexey Bataev2adecff2018-09-21 14:22:53 +00001976/// Get list of lastprivate variables from the teams distribute ... or
1977/// teams {distribute ...} directives.
1978static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001979getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001980 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1981 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1982 "expected teams directive.");
1983 const OMPExecutableDirective *Dir = &D;
1984 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1985 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001986 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001987 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1988 /*IgnoreCaptured=*/true))) {
1989 Dir = dyn_cast<OMPExecutableDirective>(S);
1990 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1991 Dir = nullptr;
1992 }
1993 }
1994 if (!Dir)
1995 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001996 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001997 for (const Expr *E : C->getVarRefs())
1998 Vars.push_back(getPrivateItem(E));
1999 }
2000}
2001
2002/// Get list of reduction variables from the teams ... directives.
2003static void
2004getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2005 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2006 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2007 "expected teams directive.");
2008 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2009 for (const Expr *E : C->privates())
2010 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002011 }
2012}
2013
James Y Knight9871db02019-02-05 16:42:33 +00002014llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002015 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2016 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002017 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002018
Alexey Bataev2adecff2018-09-21 14:22:53 +00002019 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002020 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002021 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 // Globalize team reductions variable unconditionally in all modes.
2023 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002024 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002025 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2026 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002027 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002028 CGM.getContext(), llvm::None, LastPrivatesReductions,
2029 MappedDeclsFields);
2030 }
2031 } else if (!LastPrivatesReductions.empty()) {
2032 assert(!TeamAndReductions.first &&
2033 "Previous team declaration is not expected.");
2034 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2035 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002036 }
2037
Alexey Bataevc99042b2018-03-15 18:10:54 +00002038 // Emit target region as a standalone region.
2039 class NVPTXPrePostActionTy : public PrePostActionTy {
2040 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002041 const RecordDecl *GlobalizedRD;
2042 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2043 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002044
2045 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002046 NVPTXPrePostActionTy(
2047 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2048 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2049 &MappedDeclsFields)
2050 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2051 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002052 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002053 auto &Rt =
2054 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2055 if (GlobalizedRD) {
2056 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2057 I->getSecond().GlobalRecord = GlobalizedRD;
2058 I->getSecond().MappedParams =
2059 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2060 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2061 for (const auto &Pair : MappedDeclsFields) {
2062 assert(Pair.getFirst()->isCanonicalDecl() &&
2063 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002064 Data.insert(std::make_pair(Pair.getFirst(),
2065 MappedVarData(Pair.getSecond(),
2066 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002067 }
2068 }
2069 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002070 }
2071 void Exit(CodeGenFunction &CGF) override {
2072 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2073 .emitGenericVarsEpilog(CGF);
2074 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002075 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2076 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002077 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002078 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002079 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002080 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002081 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002082
2083 return OutlinedFun;
2084}
2085
Alexey Bataevc99042b2018-03-15 18:10:54 +00002086void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002087 SourceLocation Loc,
2088 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002089 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2090 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002091 return;
2092
Alexey Bataevc99042b2018-03-15 18:10:54 +00002093 CGBuilderTy &Bld = CGF.Builder;
2094
2095 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2096 if (I == FunctionGlobalizedDecls.end())
2097 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002098 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002099 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002100 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002101
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002102 // Recover pointer to this function's global record. The runtime will
2103 // handle the specifics of the allocation of the memory.
2104 // Use actual memory size of the record including the padding
2105 // for alignment purposes.
2106 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002108 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002109 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002110 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002111
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002112 llvm::PointerType *GlobalRecPtrTy =
2113 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002115 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002116 if (!IsInTTDRegion &&
2117 (WithSPMDCheck ||
2118 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002119 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2120 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2121 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002122 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2123 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2124 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2125 llvm::Value *PL = CGF.EmitRuntimeCall(
2126 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2127 {RTLoc, ThreadID});
2128 IsTTD = Bld.CreateIsNull(PL);
2129 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002130 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2131 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2132 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2133 // There is no need to emit line number for unconditional branch.
2134 (void)ApplyDebugLocation::CreateEmpty(CGF);
2135 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002136 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2137 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002138 CGF.EmitBranch(ExitBB);
2139 // There is no need to emit line number for unconditional branch.
2140 (void)ApplyDebugLocation::CreateEmpty(CGF);
2141 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002142 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2143 if (const RecordDecl *SecGlobalizedVarsRecord =
2144 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2145 SecGlobalRecTy =
2146 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2147
2148 // Recover pointer to this function's global record. The runtime will
2149 // handle the specifics of the allocation of the memory.
2150 // Use actual memory size of the record including the padding
2151 // for alignment purposes.
2152 unsigned Alignment =
2153 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2154 unsigned GlobalRecordSize =
2155 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2156 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2157 Size = Bld.CreateSelect(
2158 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2159 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002160 // TODO: allow the usage of shared memory to be controlled by
2161 // the user, for now, default to global.
2162 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002163 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002164 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2165 createNVPTXRuntimeFunction(
2166 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2167 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002168 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002169 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002170 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002171 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002172 /*NumReservedValues=*/2, "_select_stack");
2173 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2174 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2175 GlobalRecCastAddr = Phi;
2176 I->getSecond().GlobalRecordAddr = Phi;
2177 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002178 } else if (IsInTTDRegion) {
2179 assert(GlobalizedRecords.back().Records.size() < 2 &&
2180 "Expected less than 2 globalized records: one for target and one "
2181 "for teams.");
2182 unsigned Offset = 0;
2183 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2184 QualType RDTy = CGM.getContext().getRecordType(RD);
2185 unsigned Alignment =
2186 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2187 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2188 Offset =
2189 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2190 }
2191 unsigned Alignment =
2192 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2193 Offset = llvm::alignTo(Offset, Alignment);
2194 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2195 ++GlobalizedRecords.back().RegionCounter;
2196 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002197 assert(KernelStaticGlobalized &&
2198 "Kernel static pointer must be initialized already.");
2199 auto *UseSharedMemory = new llvm::GlobalVariable(
2200 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2201 llvm::GlobalValue::InternalLinkage, nullptr,
2202 "_openmp_static_kernel$is_shared");
2203 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2204 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2205 /*DestWidth=*/16, /*Signed=*/0);
2206 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2207 Address(UseSharedMemory,
2208 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2209 /*Volatile=*/false, Int16Ty, Loc);
2210 auto *StaticGlobalized = new llvm::GlobalVariable(
2211 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002212 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002213 auto *RecSize = new llvm::GlobalVariable(
2214 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2215 llvm::GlobalValue::InternalLinkage, nullptr,
2216 "_openmp_static_kernel$size");
2217 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2218 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002219 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 CGM.getContext().getSizeType(), Loc);
2221 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2222 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002223 llvm::Value *GlobalRecordSizeArg[] = {
2224 llvm::ConstantInt::get(
2225 CGM.Int16Ty,
2226 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2227 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002228 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2229 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2230 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002231 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002232 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002233 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2234 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002235 }
2236 assert(KernelStaticGlobalized && "Global address must be set already.");
2237 Address FrameAddr = CGF.EmitLoadOfPointer(
2238 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2239 CGM.getContext()
2240 .getPointerType(CGM.getContext().VoidPtrTy)
2241 .castAs<PointerType>());
2242 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002243 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002244 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2245 I->getSecond().IsInSPMDModeFlag = nullptr;
2246 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2247 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002248 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002249 // TODO: allow the usage of shared memory to be controlled by
2250 // the user, for now, default to global.
2251 llvm::Value *GlobalRecordSizeArg[] = {
2252 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2253 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002254 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2255 createNVPTXRuntimeFunction(
2256 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2257 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002258 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002259 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002260 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2261 I->getSecond().IsInSPMDModeFlag = nullptr;
2262 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002263 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002264 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002265
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002266 // Emit the "global alloca" which is a GEP from the global declaration
2267 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002268 LValue SecBase;
2269 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2270 if (IsTTD) {
2271 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2272 llvm::PointerType *SecGlobalRecPtrTy =
2273 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2274 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2275 Bld.CreatePointerBitCastOrAddrSpaceCast(
2276 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2277 SecGlobalRecTy);
2278 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002279 for (auto &Rec : I->getSecond().LocalVarData) {
2280 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2281 llvm::Value *ParValue;
2282 if (EscapedParam) {
2283 const auto *VD = cast<VarDecl>(Rec.first);
2284 LValue ParLVal =
2285 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2286 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2287 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002288 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2289 // Emit VarAddr basing on lane-id if required.
2290 QualType VarTy;
2291 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002292 VarTy = Rec.second.FD->getType();
2293 } else {
2294 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2295 VarAddr.getAddress().getPointer(),
2296 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002297 VarTy =
2298 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002299 VarAddr = CGF.MakeAddrLValue(
2300 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2301 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002302 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002303 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002304 if (!IsInTTDRegion &&
2305 (WithSPMDCheck ||
2306 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002307 assert(I->getSecond().IsInSPMDModeFlag &&
2308 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002309 if (IsTTD) {
2310 assert(SecIt->second.IsOnePerTeam &&
2311 "Secondary glob data must be one per team.");
2312 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2313 VarAddr.setAddress(
2314 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2315 VarAddr.getPointer()),
2316 VarAddr.getAlignment()));
2317 Rec.second.PrivateAddr = VarAddr.getAddress();
2318 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002319 Address GlobalPtr = Rec.second.PrivateAddr;
2320 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2321 Rec.second.PrivateAddr = Address(
2322 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2323 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2324 LocalAddr.getAlignment());
2325 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002326 if (EscapedParam) {
2327 const auto *VD = cast<VarDecl>(Rec.first);
2328 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2329 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2330 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002331 if (IsTTD)
2332 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002333 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002334 }
2335 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2336 // Recover pointer to this function's global record. The runtime will
2337 // handle the specifics of the allocation of the memory.
2338 // Use actual memory size of the record including the padding
2339 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002340 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002341 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2342 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2343 Size = Bld.CreateNUWAdd(
2344 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2345 llvm::Value *AlignVal =
2346 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2347 Size = Bld.CreateUDiv(Size, AlignVal);
2348 Size = Bld.CreateNUWMul(Size, AlignVal);
2349 // TODO: allow the usage of shared memory to be controlled by
2350 // the user, for now, default to global.
2351 llvm::Value *GlobalRecordSizeArg[] = {
2352 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2353 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002354 createNVPTXRuntimeFunction(
2355 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002356 GlobalRecordSizeArg);
2357 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2358 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2359 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2360 CGM.getContext().getDeclAlign(VD),
2361 AlignmentSource::Decl);
2362 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2363 Base.getAddress());
2364 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002365 }
2366 I->getSecond().MappedParams->apply(CGF);
2367}
2368
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002369void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2370 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002371 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2372 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002373 return;
2374
Alexey Bataevc99042b2018-03-15 18:10:54 +00002375 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002376 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002377 I->getSecond().MappedParams->restore(CGF);
2378 if (!CGF.HaveInsertPoint())
2379 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002380 for (llvm::Value *Addr :
2381 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2382 CGF.EmitRuntimeCall(
2383 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2384 Addr);
2385 }
2386 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002387 if (!IsInTTDRegion &&
2388 (WithSPMDCheck ||
2389 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002390 CGBuilderTy &Bld = CGF.Builder;
2391 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2392 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2393 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2394 // There is no need to emit line number for unconditional branch.
2395 (void)ApplyDebugLocation::CreateEmpty(CGF);
2396 CGF.EmitBlock(NonSPMDBB);
2397 CGF.EmitRuntimeCall(
2398 createNVPTXRuntimeFunction(
2399 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2400 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2401 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002402 } else if (IsInTTDRegion) {
2403 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2404 "region counter must be > 0.");
2405 --GlobalizedRecords.back().RegionCounter;
2406 // Emit the restore function only in the target region.
2407 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002408 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2409 /*DestWidth=*/16, /*Signed=*/0);
2410 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2411 Address(GlobalizedRecords.back().UseSharedMemory,
2412 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2413 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002414 llvm::Value *Args[] = {
2415 llvm::ConstantInt::get(
2416 CGM.Int16Ty,
2417 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2418 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002419 CGF.EmitRuntimeCall(
2420 createNVPTXRuntimeFunction(
2421 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002422 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002423 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002424 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002425 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2426 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2427 I->getSecond().GlobalRecordAddr);
2428 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002429 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002430 }
2431}
2432
Carlo Bertollic6872252016-04-04 15:55:02 +00002433void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2434 const OMPExecutableDirective &D,
2435 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002436 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002437 ArrayRef<llvm::Value *> CapturedVars) {
2438 if (!CGF.HaveInsertPoint())
2439 return;
2440
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002441 Address ZeroAddr = CGF.CreateMemTemp(
2442 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2443 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002444 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2445 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002446 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002447 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2448 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002449 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002450}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002451
2452void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002453 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002454 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2455 if (!CGF.HaveInsertPoint())
2456 return;
2457
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002458 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002459 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002460 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002461 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002462}
2463
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002464void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002465 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2466 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2467 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002468
2469 // Force inline this outlined function at its call site.
2470 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2471
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002472 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2473 /*DestWidth=*/32, /*Signed=*/1),
2474 ".zero.addr");
2475 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002476 // ThreadId for serialized parallels is 0.
2477 Address ThreadIDAddr = ZeroAddr;
2478 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002479 CodeGenFunction &CGF, PrePostActionTy &Action) {
2480 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002481
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002482 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2483 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2484 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2485 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2486 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2487 };
2488 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2489 PrePostActionTy &) {
2490
2491 RegionCodeGenTy RCG(CodeGen);
2492 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2493 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2494 llvm::Value *Args[] = {RTLoc, ThreadID};
2495
2496 NVPTXActionTy Action(
2497 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2498 Args,
2499 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2500 Args);
2501 RCG.setAction(Action);
2502 RCG(CGF);
2503 };
2504
2505 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2506 PrePostActionTy &Action) {
2507 CGBuilderTy &Bld = CGF.Builder;
2508 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2509 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002510 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2511
2512 // Prepare for parallel region. Indicate the outlined function.
2513 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002514 CGF.EmitRuntimeCall(
2515 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2516 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002517
2518 // Create a private scope that will globalize the arguments
2519 // passed from the outside of the target region.
2520 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2521
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002522 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002523 if (!CapturedVars.empty()) {
2524 // Prepare for parallel region. Indicate the outlined function.
2525 Address SharedArgs =
2526 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2527 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2528
2529 llvm::Value *DataSharingArgs[] = {
2530 SharedArgsPtr,
2531 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2532 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2533 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2534 DataSharingArgs);
2535
2536 // Store variable address in a list of references to pass to workers.
2537 unsigned Idx = 0;
2538 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002539 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2540 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2541 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002542 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002543 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002544 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002545 if (V->getType()->isIntegerTy())
2546 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2547 else
2548 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002549 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2550 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002551 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002552 }
2553 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002554
2555 // Activate workers. This barrier is used by the master to signal
2556 // work for the workers.
2557 syncCTAThreads(CGF);
2558
2559 // OpenMP [2.5, Parallel Construct, p.49]
2560 // There is an implied barrier at the end of a parallel region. After the
2561 // end of a parallel region, only the master thread of the team resumes
2562 // execution of the enclosing task region.
2563 //
2564 // The master waits at this barrier until all workers are done.
2565 syncCTAThreads(CGF);
2566
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002567 if (!CapturedVars.empty())
2568 CGF.EmitRuntimeCall(
2569 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2570
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002571 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002572 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002573 };
2574
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002575 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2576 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002577 if (IsInParallelRegion) {
2578 SeqGen(CGF, Action);
2579 } else if (IsInTargetMasterThreadRegion) {
2580 L0ParallelGen(CGF, Action);
2581 } else {
2582 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002583 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002584 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002585 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002586 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002587 // }
2588 CGBuilderTy &Bld = CGF.Builder;
2589 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002590 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2591 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002592 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002593 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2594 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002595 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002596 // There is no need to emit line number for unconditional branch.
2597 (void)ApplyDebugLocation::CreateEmpty(CGF);
2598 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002599 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2600 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2601 llvm::Value *PL = CGF.EmitRuntimeCall(
2602 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2603 {RTLoc, ThreadID});
2604 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002606 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002607 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002608 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002609 // There is no need to emit line number for unconditional branch.
2610 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002611 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 L0ParallelGen(CGF, Action);
2613 CGF.EmitBranch(ExitBB);
2614 // There is no need to emit line number for unconditional branch.
2615 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 // Emit the continuation block for code after the if.
2617 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2618 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002619 };
2620
Alexey Bataev9ff80832018-04-16 20:16:21 +00002621 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002622 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002623 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002624 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002625 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002626 ThenRCG(CGF);
2627 }
2628}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002629
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002630void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002631 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002632 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2633 // Just call the outlined function to execute the parallel region.
2634 // OutlinedFn(&GTid, &zero, CapturedStruct);
2635 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002636 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002637
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002638 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2639 /*DestWidth=*/32, /*Signed=*/1),
2640 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002641 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002642 // ThreadId for serialized parallels is 0.
2643 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002644 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002645 &ThreadIDAddr](CodeGenFunction &CGF,
2646 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002647 Action.Enter(CGF);
2648
2649 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2650 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2651 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2652 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2653 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2654 };
2655 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2656 PrePostActionTy &) {
2657
2658 RegionCodeGenTy RCG(CodeGen);
2659 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2660 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2661 llvm::Value *Args[] = {RTLoc, ThreadID};
2662
2663 NVPTXActionTy Action(
2664 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2665 Args,
2666 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2667 Args);
2668 RCG.setAction(Action);
2669 RCG(CGF);
2670 };
2671
2672 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002673 // In the worker need to use the real thread id.
2674 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002675 RegionCodeGenTy RCG(CodeGen);
2676 RCG(CGF);
2677 } else {
2678 // If we are not in the target region, it is definitely L2 parallelism or
2679 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2680 // need to check for orphaned directives.
2681 RegionCodeGenTy RCG(SeqGen);
2682 RCG(CGF);
2683 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002684}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002685
Alexey Bataeva3924b52019-01-03 16:25:35 +00002686void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2687 // Always emit simple barriers!
2688 if (!CGF.HaveInsertPoint())
2689 return;
2690 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2691 // This function does not use parameters, so we can emit just default values.
2692 llvm::Value *Args[] = {
2693 llvm::ConstantPointerNull::get(
2694 cast<llvm::PointerType>(getIdentTyPointerTy())),
2695 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2696 CGF.EmitRuntimeCall(
2697 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2698}
2699
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002700void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2701 SourceLocation Loc,
2702 OpenMPDirectiveKind Kind, bool,
2703 bool) {
2704 // Always emit simple barriers!
2705 if (!CGF.HaveInsertPoint())
2706 return;
2707 // Build call __kmpc_cancel_barrier(loc, thread_id);
2708 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2709 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2710 getThreadID(CGF, Loc)};
2711 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2712}
2713
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002714void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2715 CodeGenFunction &CGF, StringRef CriticalName,
2716 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2717 const Expr *Hint) {
2718 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2719 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2720 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2721 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2722 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2723
2724 // Fetch team-local id of the thread.
2725 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2726
2727 // Get the width of the team.
2728 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2729
2730 // Initialize the counter variable for the loop.
2731 QualType Int32Ty =
2732 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2733 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2734 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2735 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2736 /*isInit=*/true);
2737
2738 // Block checks if loop counter exceeds upper bound.
2739 CGF.EmitBlock(LoopBB);
2740 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2741 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2742 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2743
2744 // Block tests which single thread should execute region, and which threads
2745 // should go straight to synchronisation point.
2746 CGF.EmitBlock(TestBB);
2747 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2748 llvm::Value *CmpThreadToCounter =
2749 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2750 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2751
2752 // Block emits the body of the critical region.
2753 CGF.EmitBlock(BodyBB);
2754
2755 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002756 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2757 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002758
2759 // After the body surrounded by the critical region, the single executing
2760 // thread will jump to the synchronisation point.
2761 // Block waits for all threads in current team to finish then increments the
2762 // counter variable and returns to the loop.
2763 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002764 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2765 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002766
2767 llvm::Value *IncCounterVal =
2768 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2769 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2770 CGF.EmitBranch(LoopBB);
2771
2772 // Block that is reached when all threads in the team complete the region.
2773 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2774}
2775
Alexey Bataevb2575932018-01-04 20:18:55 +00002776/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002777static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2778 QualType ValTy, QualType CastTy,
2779 SourceLocation Loc) {
2780 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2781 "Cast type must sized.");
2782 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2783 "Val type must sized.");
2784 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2785 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002786 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002787 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2788 CGF.getContext().getTypeSizeInChars(CastTy))
2789 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2790 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2791 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2792 CastTy->hasSignedIntegerRepresentation());
2793 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002794 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2795 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002796 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2797 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002798}
2799
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800/// This function creates calls to one of two shuffle functions to copy
2801/// variables between lanes in a warp.
2802static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002803 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002804 QualType ElemType,
2805 llvm::Value *Offset,
2806 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002807 CodeGenModule &CGM = CGF.CGM;
2808 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002809 CGOpenMPRuntimeNVPTX &RT =
2810 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2811
Alexey Bataeva453f362018-03-19 17:53:56 +00002812 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2813 assert(Size.getQuantity() <= 8 &&
2814 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002815
Alexey Bataeva453f362018-03-19 17:53:56 +00002816 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002817 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2818 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2819
2820 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002821 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2822 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2823 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002824 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002825 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002826
Alexey Bataev9ff80832018-04-16 20:16:21 +00002827 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2828 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829
Alexey Bataeva453f362018-03-19 17:53:56 +00002830 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002831}
2832
Alexey Bataev12c62902018-06-22 19:10:38 +00002833static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2834 Address DestAddr, QualType ElemType,
2835 llvm::Value *Offset, SourceLocation Loc) {
2836 CGBuilderTy &Bld = CGF.Builder;
2837
2838 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2839 // Create the loop over the big sized data.
2840 // ptr = (void*)Elem;
2841 // ptrEnd = (void*) Elem + 1;
2842 // Step = 8;
2843 // while (ptr + Step < ptrEnd)
2844 // shuffle((int64_t)*ptr);
2845 // Step = 4;
2846 // while (ptr + Step < ptrEnd)
2847 // shuffle((int32_t)*ptr);
2848 // ...
2849 Address ElemPtr = DestAddr;
2850 Address Ptr = SrcAddr;
2851 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002852 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002853 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2854 if (Size < CharUnits::fromQuantity(IntSize))
2855 continue;
2856 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2857 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2858 /*Signed=*/1);
2859 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2860 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2861 ElemPtr =
2862 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2863 if (Size.getQuantity() / IntSize > 1) {
2864 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2865 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2866 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2867 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2868 CGF.EmitBlock(PreCondBB);
2869 llvm::PHINode *PhiSrc =
2870 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2871 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2872 llvm::PHINode *PhiDest =
2873 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2874 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2875 Ptr = Address(PhiSrc, Ptr.getAlignment());
2876 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2877 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2878 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2879 Ptr.getPointer(), CGF.VoidPtrTy));
2880 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2881 ThenBB, ExitBB);
2882 CGF.EmitBlock(ThenBB);
2883 llvm::Value *Res = createRuntimeShuffleFunction(
2884 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2885 IntType, Offset, Loc);
2886 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002887 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2888 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002889 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2890 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002891 CGF.EmitBranch(PreCondBB);
2892 CGF.EmitBlock(ExitBB);
2893 } else {
2894 llvm::Value *Res = createRuntimeShuffleFunction(
2895 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2896 IntType, Offset, Loc);
2897 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002898 Ptr = Bld.CreateConstGEP(Ptr, 1);
2899 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002900 }
2901 Size = Size % IntSize;
2902 }
2903}
2904
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002905namespace {
2906enum CopyAction : unsigned {
2907 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2908 // the warp using shuffle instructions.
2909 RemoteLaneToThread,
2910 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2911 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002912 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2913 ThreadToScratchpad,
2914 // ScratchpadToThread: Copy from a scratchpad array in global memory
2915 // containing team-reduced data to a thread's stack.
2916 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917};
2918} // namespace
2919
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002920struct CopyOptionsTy {
2921 llvm::Value *RemoteLaneOffset;
2922 llvm::Value *ScratchpadIndex;
2923 llvm::Value *ScratchpadWidth;
2924};
2925
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002926/// Emit instructions to copy a Reduce list, which contains partially
2927/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002928static void emitReductionListCopy(
2929 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2930 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2931 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002932
Alexey Bataev9ff80832018-04-16 20:16:21 +00002933 CodeGenModule &CGM = CGF.CGM;
2934 ASTContext &C = CGM.getContext();
2935 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002936
Alexey Bataev9ff80832018-04-16 20:16:21 +00002937 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2938 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2939 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002940
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002941 // Iterates, element-by-element, through the source Reduce list and
2942 // make a copy.
2943 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002944 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002945 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002946 Address SrcElementAddr = Address::invalid();
2947 Address DestElementAddr = Address::invalid();
2948 Address DestElementPtrAddr = Address::invalid();
2949 // Should we shuffle in an element from a remote lane?
2950 bool ShuffleInElement = false;
2951 // Set to true to update the pointer in the dest Reduce list to a
2952 // newly created element.
2953 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002954 // Increment the src or dest pointer to the scratchpad, for each
2955 // new element.
2956 bool IncrScratchpadSrc = false;
2957 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958
2959 switch (Action) {
2960 case RemoteLaneToThread: {
2961 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002962 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002963 SrcElementAddr = CGF.EmitLoadOfPointer(
2964 SrcElementPtrAddr,
2965 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966
2967 // Step 1.2: Create a temporary to store the element in the destination
2968 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002969 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002970 DestElementAddr =
2971 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2972 ShuffleInElement = true;
2973 UpdateDestListPtr = true;
2974 break;
2975 }
2976 case ThreadCopy: {
2977 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002978 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002979 SrcElementAddr = CGF.EmitLoadOfPointer(
2980 SrcElementPtrAddr,
2981 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002982
2983 // Step 1.2: Get the address for dest element. The destination
2984 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002985 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002986 DestElementAddr = CGF.EmitLoadOfPointer(
2987 DestElementPtrAddr,
2988 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002989 break;
2990 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002991 case ThreadToScratchpad: {
2992 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002993 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002994 SrcElementAddr = CGF.EmitLoadOfPointer(
2995 SrcElementPtrAddr,
2996 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002997
2998 // Step 1.2: Get the address for dest element:
2999 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003000 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003001 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003002 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003003 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003004 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003005 ScratchPadElemAbsolutePtrVal =
3006 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003007 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3008 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003009 IncrScratchpadDest = true;
3010 break;
3011 }
3012 case ScratchpadToThread: {
3013 // Step 1.1: Get the address for the src element in the scratchpad.
3014 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003015 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003016 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003017 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003018 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003019 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003020 ScratchPadElemAbsolutePtrVal =
3021 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3022 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3023 C.getTypeAlignInChars(Private->getType()));
3024 IncrScratchpadSrc = true;
3025
3026 // Step 1.2: Create a temporary to store the element in the destination
3027 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003028 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003029 DestElementAddr =
3030 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3031 UpdateDestListPtr = true;
3032 break;
3033 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003034 }
3035
3036 // Regardless of src and dest of copy, we emit the load of src
3037 // element as this is required in all directions
3038 SrcElementAddr = Bld.CreateElementBitCast(
3039 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003040 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3041 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003042
3043 // Now that all active lanes have read the element in the
3044 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003045 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003046 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3047 RemoteLaneOffset, Private->getExprLoc());
3048 } else {
3049 if (Private->getType()->isScalarType()) {
3050 llvm::Value *Elem =
3051 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3052 Private->getType(), Private->getExprLoc());
3053 // Store the source element value to the dest element address.
3054 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3055 Private->getType());
3056 } else {
3057 CGF.EmitAggregateCopy(
3058 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3059 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3060 Private->getType(), AggValueSlot::DoesNotOverlap);
3061 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003062 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003063
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003064 // Step 3.1: Modify reference in dest Reduce list as needed.
3065 // Modifying the reference in Reduce list to point to the newly
3066 // created element. The element is live in the current function
3067 // scope and that of functions it invokes (i.e., reduce_function).
3068 // RemoteReduceData[i] = (void*)&RemoteElem
3069 if (UpdateDestListPtr) {
3070 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3071 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3072 DestElementPtrAddr, /*Volatile=*/false,
3073 C.VoidPtrTy);
3074 }
3075
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003076 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3077 // address of the next element in scratchpad memory, unless we're currently
3078 // processing the last one. Memory alignment is also taken care of here.
3079 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3080 llvm::Value *ScratchpadBasePtr =
3081 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003082 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3083 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003084 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003085 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003086
3087 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003088 ScratchpadBasePtr = Bld.CreateNUWSub(
3089 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3090 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003091 ScratchpadBasePtr,
3092 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003093 ScratchpadBasePtr = Bld.CreateNUWAdd(
3094 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3095 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003096 ScratchpadBasePtr,
3097 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3098
3099 if (IncrScratchpadDest)
3100 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3101 else /* IncrScratchpadSrc = true */
3102 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3103 }
3104
Alexey Bataev9ff80832018-04-16 20:16:21 +00003105 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003106 }
3107}
3108
3109/// This function emits a helper that gathers Reduce lists from the first
3110/// lane of every active warp to lanes in the first warp.
3111///
3112/// void inter_warp_copy_func(void* reduce_data, num_warps)
3113/// shared smem[warp_size];
3114/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003115/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003116/// If (I am the first lane in each warp)
3117/// Copy my local D to smem[warp_id]
3118/// sync
3119/// if (I am the first warp)
3120/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003121static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3122 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003123 QualType ReductionArrayTy,
3124 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003125 ASTContext &C = CGM.getContext();
3126 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003127
3128 // ReduceList: thread local Reduce list.
3129 // At the stage of the computation when this function is called, partially
3130 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003131 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3132 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003133 // NumWarps: number of warps active in the parallel region. This could
3134 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003135 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003136 C.getIntTypeForBitwidth(32, /* Signed */ true),
3137 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138 FunctionArgList Args;
3139 Args.push_back(&ReduceListArg);
3140 Args.push_back(&NumWarpsArg);
3141
Alexey Bataev9ff80832018-04-16 20:16:21 +00003142 const CGFunctionInfo &CGFI =
3143 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003144 auto *Fn = llvm::Function::Create(
3145 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3146 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003147 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003148 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003150 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003151
Alexey Bataev9ff80832018-04-16 20:16:21 +00003152 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153
3154 // This array is used as a medium to transfer, one reduce element at a time,
3155 // the data from the first lane of every warp to lanes in the first warp
3156 // in order to perform the final step of a reduction in a parallel region
3157 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3158 // for reduced latency, as well as to have a distinct copy for concurrently
3159 // executing target regions. The array is declared with common linkage so
3160 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003161 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003162 "__openmp_nvptx_data_transfer_temporary_storage";
3163 llvm::GlobalVariable *TransferMedium =
3164 M.getGlobalVariable(TransferMediumName);
3165 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003166 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3168 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003169 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170 llvm::Constant::getNullValue(Ty), TransferMediumName,
3171 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3172 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003173 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003174 }
3175
3176 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003177 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003179 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003181 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003182
3183 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3184 Address LocalReduceList(
3185 Bld.CreatePointerBitCastOrAddrSpaceCast(
3186 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003187 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003188 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3189 CGF.getPointerAlign());
3190
3191 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003192 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003193 //
3194 // Warp master copies reduce element to transfer medium in __shared__
3195 // memory.
3196 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003197 unsigned RealTySize =
3198 C.getTypeSizeInChars(Private->getType())
3199 .alignTo(C.getTypeAlignInChars(Private->getType()))
3200 .getQuantity();
3201 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3202 unsigned NumIters = RealTySize / TySize;
3203 if (NumIters == 0)
3204 continue;
3205 QualType CType = C.getIntTypeForBitwidth(
3206 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3207 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3208 CharUnits Align = CharUnits::fromQuantity(TySize);
3209 llvm::Value *Cnt = nullptr;
3210 Address CntAddr = Address::invalid();
3211 llvm::BasicBlock *PrecondBB = nullptr;
3212 llvm::BasicBlock *ExitBB = nullptr;
3213 if (NumIters > 1) {
3214 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3215 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3216 /*Volatile=*/false, C.IntTy);
3217 PrecondBB = CGF.createBasicBlock("precond");
3218 ExitBB = CGF.createBasicBlock("exit");
3219 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3220 // There is no need to emit line number for unconditional branch.
3221 (void)ApplyDebugLocation::CreateEmpty(CGF);
3222 CGF.EmitBlock(PrecondBB);
3223 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3224 llvm::Value *Cmp =
3225 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3226 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3227 CGF.EmitBlock(BodyBB);
3228 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003229 // kmpc_barrier.
3230 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3231 /*EmitChecks=*/false,
3232 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003233 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3234 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3235 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003237 // if (lane_id == 0)
3238 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3239 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3240 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003243 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003244 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3245 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3246 // elemptr = ((CopyType*)(elemptrptr)) + I
3247 Address ElemPtr = Address(ElemPtrPtr, Align);
3248 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3249 if (NumIters > 1) {
3250 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3251 ElemPtr.getAlignment());
3252 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003253
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003254 // Get pointer to location in transfer medium.
3255 // MediumPtr = &medium[warp_id]
3256 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3257 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3258 Address MediumPtr(MediumPtrVal, Align);
3259 // Casting to actual data type.
3260 // MediumPtr = (CopyType*)MediumPtrAddr;
3261 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003262
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003263 // elem = *elemptr
3264 //*MediumPtr = elem
3265 llvm::Value *Elem =
3266 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003267 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003268 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003269
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003270 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003271
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003272 CGF.EmitBlock(ElseBB);
3273 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003275 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276
Alexey Bataevae51b962018-12-14 21:00:58 +00003277 // kmpc_barrier.
3278 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3279 /*EmitChecks=*/false,
3280 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 //
3283 // Warp 0 copies reduce element from transfer medium.
3284 //
3285 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3286 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3287 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003288
Alexey Bataevae51b962018-12-14 21:00:58 +00003289 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3290 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3291 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3292
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003293 // Up to 32 threads in warp 0 are active.
3294 llvm::Value *IsActiveThread =
3295 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3296 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003297
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003298 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003299
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003300 // SrcMediumPtr = &medium[tid]
3301 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3302 TransferMedium,
3303 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3304 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3305 // SrcMediumVal = *SrcMediumPtr;
3306 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003309 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003310 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3311 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3312 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3313 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3314 if (NumIters > 1) {
3315 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3316 TargetElemPtr.getAlignment());
3317 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003318
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003319 // *TargetElemPtr = SrcMediumVal;
3320 llvm::Value *SrcMediumValue =
3321 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003322 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003323 CType);
3324 Bld.CreateBr(W0MergeBB);
3325
3326 CGF.EmitBlock(W0ElseBB);
3327 Bld.CreateBr(W0MergeBB);
3328
3329 CGF.EmitBlock(W0MergeBB);
3330
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003331 if (NumIters > 1) {
3332 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3333 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3334 CGF.EmitBranch(PrecondBB);
3335 (void)ApplyDebugLocation::CreateEmpty(CGF);
3336 CGF.EmitBlock(ExitBB);
3337 }
3338 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003339 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003340 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003341 }
3342
3343 CGF.FinishFunction();
3344 return Fn;
3345}
3346
3347/// Emit a helper that reduces data across two OpenMP threads (lanes)
3348/// in the same warp. It uses shuffle instructions to copy over data from
3349/// a remote lane's stack. The reduction algorithm performed is specified
3350/// by the fourth parameter.
3351///
3352/// Algorithm Versions.
3353/// Full Warp Reduce (argument value 0):
3354/// This algorithm assumes that all 32 lanes are active and gathers
3355/// data from these 32 lanes, producing a single resultant value.
3356/// Contiguous Partial Warp Reduce (argument value 1):
3357/// This algorithm assumes that only a *contiguous* subset of lanes
3358/// are active. This happens for the last warp in a parallel region
3359/// when the user specified num_threads is not an integer multiple of
3360/// 32. This contiguous subset always starts with the zeroth lane.
3361/// Partial Warp Reduce (argument value 2):
3362/// This algorithm gathers data from any number of lanes at any position.
3363/// All reduced values are stored in the lowest possible lane. The set
3364/// of problems every algorithm addresses is a super set of those
3365/// addressable by algorithms with a lower version number. Overhead
3366/// increases as algorithm version increases.
3367///
3368/// Terminology
3369/// Reduce element:
3370/// Reduce element refers to the individual data field with primitive
3371/// data types to be combined and reduced across threads.
3372/// Reduce list:
3373/// Reduce list refers to a collection of local, thread-private
3374/// reduce elements.
3375/// Remote Reduce list:
3376/// Remote Reduce list refers to a collection of remote (relative to
3377/// the current thread) reduce elements.
3378///
3379/// We distinguish between three states of threads that are important to
3380/// the implementation of this function.
3381/// Alive threads:
3382/// Threads in a warp executing the SIMT instruction, as distinguished from
3383/// threads that are inactive due to divergent control flow.
3384/// Active threads:
3385/// The minimal set of threads that has to be alive upon entry to this
3386/// function. The computation is correct iff active threads are alive.
3387/// Some threads are alive but they are not active because they do not
3388/// contribute to the computation in any useful manner. Turning them off
3389/// may introduce control flow overheads without any tangible benefits.
3390/// Effective threads:
3391/// In order to comply with the argument requirements of the shuffle
3392/// function, we must keep all lanes holding data alive. But at most
3393/// half of them perform value aggregation; we refer to this half of
3394/// threads as effective. The other half is simply handing off their
3395/// data.
3396///
3397/// Procedure
3398/// Value shuffle:
3399/// In this step active threads transfer data from higher lane positions
3400/// in the warp to lower lane positions, creating Remote Reduce list.
3401/// Value aggregation:
3402/// In this step, effective threads combine their thread local Reduce list
3403/// with Remote Reduce list and store the result in the thread local
3404/// Reduce list.
3405/// Value copy:
3406/// In this step, we deal with the assumption made by algorithm 2
3407/// (i.e. contiguity assumption). When we have an odd number of lanes
3408/// active, say 2k+1, only k threads will be effective and therefore k
3409/// new values will be produced. However, the Reduce list owned by the
3410/// (2k+1)th thread is ignored in the value aggregation. Therefore
3411/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3412/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003413static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003414 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003415 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003416 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003417
3418 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003419 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3420 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003421 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003422 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3423 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003424 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003425 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3426 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003427 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003428 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3429 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430 FunctionArgList Args;
3431 Args.push_back(&ReduceListArg);
3432 Args.push_back(&LaneIDArg);
3433 Args.push_back(&RemoteLaneOffsetArg);
3434 Args.push_back(&AlgoVerArg);
3435
Alexey Bataev9ff80832018-04-16 20:16:21 +00003436 const CGFunctionInfo &CGFI =
3437 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003438 auto *Fn = llvm::Function::Create(
3439 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3440 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003441 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003442 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003444 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445
Alexey Bataev9ff80832018-04-16 20:16:21 +00003446 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003447
3448 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3449 Address LocalReduceList(
3450 Bld.CreatePointerBitCastOrAddrSpaceCast(
3451 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3452 C.VoidPtrTy, SourceLocation()),
3453 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3454 CGF.getPointerAlign());
3455
3456 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3457 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3458 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3459
3460 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3461 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3462 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3463
3464 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3465 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3466 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3467
3468 // Create a local thread-private variable to host the Reduce list
3469 // from a remote lane.
3470 Address RemoteReduceList =
3471 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3472
3473 // This loop iterates through the list of reduce elements and copies,
3474 // element by element, from a remote lane in the warp to RemoteReduceList,
3475 // hosted on the thread's stack.
3476 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3477 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003478 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3479 /*ScratchpadIndex=*/nullptr,
3480 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003481
3482 // The actions to be performed on the Remote Reduce list is dependent
3483 // on the algorithm version.
3484 //
3485 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3486 // LaneId % 2 == 0 && Offset > 0):
3487 // do the reduction value aggregation
3488 //
3489 // The thread local variable Reduce list is mutated in place to host the
3490 // reduced data, which is the aggregated value produced from local and
3491 // remote lanes.
3492 //
3493 // Note that AlgoVer is expected to be a constant integer known at compile
3494 // time.
3495 // When AlgoVer==0, the first conjunction evaluates to true, making
3496 // the entire predicate true during compile time.
3497 // When AlgoVer==1, the second conjunction has only the second part to be
3498 // evaluated during runtime. Other conjunctions evaluates to false
3499 // during compile time.
3500 // When AlgoVer==2, the third conjunction has only the second part to be
3501 // evaluated during runtime. Other conjunctions evaluates to false
3502 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003504
Alexey Bataev9ff80832018-04-16 20:16:21 +00003505 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3506 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003507 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3508
Alexey Bataev9ff80832018-04-16 20:16:21 +00003509 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3510 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3511 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003512 CondAlgo2 = Bld.CreateAnd(
3513 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3514
Alexey Bataev9ff80832018-04-16 20:16:21 +00003515 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003516 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3517
3518 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3519 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3520 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3521 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3522
3523 CGF.EmitBlock(ThenBB);
3524 // reduce_function(LocalReduceList, RemoteReduceList)
3525 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3526 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3527 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3528 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003529 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3530 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003531 Bld.CreateBr(MergeBB);
3532
3533 CGF.EmitBlock(ElseBB);
3534 Bld.CreateBr(MergeBB);
3535
3536 CGF.EmitBlock(MergeBB);
3537
3538 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3539 // Reduce list.
3540 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003541 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003542 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3543
3544 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3545 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3546 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3547 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3548
3549 CGF.EmitBlock(CpyThenBB);
3550 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3551 RemoteReduceList, LocalReduceList);
3552 Bld.CreateBr(CpyMergeBB);
3553
3554 CGF.EmitBlock(CpyElseBB);
3555 Bld.CreateBr(CpyMergeBB);
3556
3557 CGF.EmitBlock(CpyMergeBB);
3558
3559 CGF.FinishFunction();
3560 return Fn;
3561}
3562
3563///
3564/// Design of OpenMP reductions on the GPU
3565///
3566/// Consider a typical OpenMP program with one or more reduction
3567/// clauses:
3568///
3569/// float foo;
3570/// double bar;
3571/// #pragma omp target teams distribute parallel for \
3572/// reduction(+:foo) reduction(*:bar)
3573/// for (int i = 0; i < N; i++) {
3574/// foo += A[i]; bar *= B[i];
3575/// }
3576///
3577/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3578/// all teams. In our OpenMP implementation on the NVPTX device an
3579/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3580/// within a team are mapped to CUDA threads within a threadblock.
3581/// Our goal is to efficiently aggregate values across all OpenMP
3582/// threads such that:
3583///
3584/// - the compiler and runtime are logically concise, and
3585/// - the reduction is performed efficiently in a hierarchical
3586/// manner as follows: within OpenMP threads in the same warp,
3587/// across warps in a threadblock, and finally across teams on
3588/// the NVPTX device.
3589///
3590/// Introduction to Decoupling
3591///
3592/// We would like to decouple the compiler and the runtime so that the
3593/// latter is ignorant of the reduction variables (number, data types)
3594/// and the reduction operators. This allows a simpler interface
3595/// and implementation while still attaining good performance.
3596///
3597/// Pseudocode for the aforementioned OpenMP program generated by the
3598/// compiler is as follows:
3599///
3600/// 1. Create private copies of reduction variables on each OpenMP
3601/// thread: 'foo_private', 'bar_private'
3602/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3603/// to it and writes the result in 'foo_private' and 'bar_private'
3604/// respectively.
3605/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3606/// and store the result on the team master:
3607///
Alexey Bataev8e009032019-01-04 17:25:09 +00003608/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003609/// reduceData, shuffleReduceFn, interWarpCpyFn)
3610///
3611/// where:
3612/// struct ReduceData {
3613/// double *foo;
3614/// double *bar;
3615/// } reduceData
3616/// reduceData.foo = &foo_private
3617/// reduceData.bar = &bar_private
3618///
3619/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3620/// auxiliary functions generated by the compiler that operate on
3621/// variables of type 'ReduceData'. They aid the runtime perform
3622/// algorithmic steps in a data agnostic manner.
3623///
3624/// 'shuffleReduceFn' is a pointer to a function that reduces data
3625/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3626/// same warp. It takes the following arguments as input:
3627///
3628/// a. variable of type 'ReduceData' on the calling lane,
3629/// b. its lane_id,
3630/// c. an offset relative to the current lane_id to generate a
3631/// remote_lane_id. The remote lane contains the second
3632/// variable of type 'ReduceData' that is to be reduced.
3633/// d. an algorithm version parameter determining which reduction
3634/// algorithm to use.
3635///
3636/// 'shuffleReduceFn' retrieves data from the remote lane using
3637/// efficient GPU shuffle intrinsics and reduces, using the
3638/// algorithm specified by the 4th parameter, the two operands
3639/// element-wise. The result is written to the first operand.
3640///
3641/// Different reduction algorithms are implemented in different
3642/// runtime functions, all calling 'shuffleReduceFn' to perform
3643/// the essential reduction step. Therefore, based on the 4th
3644/// parameter, this function behaves slightly differently to
3645/// cooperate with the runtime to ensure correctness under
3646/// different circumstances.
3647///
3648/// 'InterWarpCpyFn' is a pointer to a function that transfers
3649/// reduced variables across warps. It tunnels, through CUDA
3650/// shared memory, the thread-private data of type 'ReduceData'
3651/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003652/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3653/// The last team writes the global reduced value to memory.
3654///
3655/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3656/// reduceData, shuffleReduceFn, interWarpCpyFn,
3657/// scratchpadCopyFn, loadAndReduceFn)
3658///
3659/// 'scratchpadCopyFn' is a helper that stores reduced
3660/// data from the team master to a scratchpad array in
3661/// global memory.
3662///
3663/// 'loadAndReduceFn' is a helper that loads data from
3664/// the scratchpad array and reduces it with the input
3665/// operand.
3666///
3667/// These compiler generated functions hide address
3668/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003669/// 5. if ret == 1:
3670/// The team master of the last team stores the reduced
3671/// result to the globals in memory.
3672/// foo += reduceData.foo; bar *= reduceData.bar
3673///
3674///
3675/// Warp Reduction Algorithms
3676///
3677/// On the warp level, we have three algorithms implemented in the
3678/// OpenMP runtime depending on the number of active lanes:
3679///
3680/// Full Warp Reduction
3681///
3682/// The reduce algorithm within a warp where all lanes are active
3683/// is implemented in the runtime as follows:
3684///
3685/// full_warp_reduce(void *reduce_data,
3686/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3687/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3688/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3689/// }
3690///
3691/// The algorithm completes in log(2, WARPSIZE) steps.
3692///
3693/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3694/// not used therefore we save instructions by not retrieving lane_id
3695/// from the corresponding special registers. The 4th parameter, which
3696/// represents the version of the algorithm being used, is set to 0 to
3697/// signify full warp reduction.
3698///
3699/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3700///
3701/// #reduce_elem refers to an element in the local lane's data structure
3702/// #remote_elem is retrieved from a remote lane
3703/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3704/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3705///
3706/// Contiguous Partial Warp Reduction
3707///
3708/// This reduce algorithm is used within a warp where only the first
3709/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3710/// number of OpenMP threads in a parallel region is not a multiple of
3711/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3712///
3713/// void
3714/// contiguous_partial_reduce(void *reduce_data,
3715/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3716/// int size, int lane_id) {
3717/// int curr_size;
3718/// int offset;
3719/// curr_size = size;
3720/// mask = curr_size/2;
3721/// while (offset>0) {
3722/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3723/// curr_size = (curr_size+1)/2;
3724/// offset = curr_size/2;
3725/// }
3726/// }
3727///
3728/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3729///
3730/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3731/// if (lane_id < offset)
3732/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3733/// else
3734/// reduce_elem = remote_elem
3735///
3736/// This algorithm assumes that the data to be reduced are located in a
3737/// contiguous subset of lanes starting from the first. When there is
3738/// an odd number of active lanes, the data in the last lane is not
3739/// aggregated with any other lane's dat but is instead copied over.
3740///
3741/// Dispersed Partial Warp Reduction
3742///
3743/// This algorithm is used within a warp when any discontiguous subset of
3744/// lanes are active. It is used to implement the reduction operation
3745/// across lanes in an OpenMP simd region or in a nested parallel region.
3746///
3747/// void
3748/// dispersed_partial_reduce(void *reduce_data,
3749/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3750/// int size, remote_id;
3751/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3752/// do {
3753/// remote_id = next_active_lane_id_right_after_me();
3754/// # the above function returns 0 of no active lane
3755/// # is present right after the current lane.
3756/// size = number_of_active_lanes_in_this_warp();
3757/// logical_lane_id /= 2;
3758/// ShuffleReduceFn(reduce_data, logical_lane_id,
3759/// remote_id-1-threadIdx.x, 2);
3760/// } while (logical_lane_id % 2 == 0 && size > 1);
3761/// }
3762///
3763/// There is no assumption made about the initial state of the reduction.
3764/// Any number of lanes (>=1) could be active at any position. The reduction
3765/// result is returned in the first active lane.
3766///
3767/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3768///
3769/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3770/// if (lane_id % 2 == 0 && offset > 0)
3771/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3772/// else
3773/// reduce_elem = remote_elem
3774///
3775///
3776/// Intra-Team Reduction
3777///
3778/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00003779/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003780/// threads in a team. It first reduces within a warp using the
3781/// aforementioned algorithms. We then proceed to gather all such
3782/// reduced values at the first warp.
3783///
3784/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3785/// data from each of the "warp master" (zeroth lane of each warp, where
3786/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3787/// a mathematical sense) the problem of reduction across warp masters in
3788/// a block to the problem of warp reduction.
3789///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003790///
3791/// Inter-Team Reduction
3792///
3793/// Once a team has reduced its data to a single value, it is stored in
3794/// a global scratchpad array. Since each team has a distinct slot, this
3795/// can be done without locking.
3796///
3797/// The last team to write to the scratchpad array proceeds to reduce the
3798/// scratchpad array. One or more workers in the last team use the helper
3799/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3800/// the k'th worker reduces every k'th element.
3801///
Alexey Bataev8e009032019-01-04 17:25:09 +00003802/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003803/// reduce across workers and compute a globally reduced value.
3804///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003805void CGOpenMPRuntimeNVPTX::emitReduction(
3806 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3807 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3808 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3809 if (!CGF.HaveInsertPoint())
3810 return;
3811
3812 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003813#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003814 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003815#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003816
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003817 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003818 assert(!TeamsReduction && !ParallelReduction &&
3819 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003820 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3821 ReductionOps, Options);
3822 return;
3823 }
3824
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003825 assert((TeamsReduction || ParallelReduction) &&
3826 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003827
Alexey Bataeva1166022018-11-27 21:24:54 +00003828 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003829 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003830 // or
3831 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00003832 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003833 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003834
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003835 llvm::Value *Res;
3836 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003837 ASTContext &C = CGM.getContext();
3838 // 1. Build a list of reduction variables.
3839 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3840 auto Size = RHSExprs.size();
3841 for (const Expr *E : Privates) {
3842 if (E->getType()->isVariablyModifiedType())
3843 // Reserve place for array size.
3844 ++Size;
3845 }
3846 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3847 QualType ReductionArrayTy =
3848 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3849 /*IndexTypeQuals=*/0);
3850 Address ReductionList =
3851 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3852 auto IPriv = Privates.begin();
3853 unsigned Idx = 0;
3854 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
James Y Knight751fe282019-02-09 22:22:28 +00003855 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
Alexey Bataeva1166022018-11-27 21:24:54 +00003856 CGF.Builder.CreateStore(
3857 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3858 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3859 Elem);
3860 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3861 // Store array size.
3862 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00003863 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
Alexey Bataeva1166022018-11-27 21:24:54 +00003864 llvm::Value *Size = CGF.Builder.CreateIntCast(
3865 CGF.getVLASize(
3866 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3867 .NumElts,
3868 CGF.SizeTy, /*isSigned=*/false);
3869 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3870 Elem);
3871 }
3872 }
3873
3874 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3875 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3876 ReductionList.getPointer(), CGF.VoidPtrTy);
James Y Knight9871db02019-02-05 16:42:33 +00003877 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataeva1166022018-11-27 21:24:54 +00003878 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3879 Privates, LHSExprs, RHSExprs, ReductionOps);
James Y Knight9871db02019-02-05 16:42:33 +00003880 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataeva1166022018-11-27 21:24:54 +00003881 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3882 llvm::Value *InterWarpCopyFn =
3883 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3884
Alexey Bataev8e009032019-01-04 17:25:09 +00003885 llvm::Value *Args[] = {RTLoc,
3886 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003887 CGF.Builder.getInt32(RHSExprs.size()),
3888 ReductionArrayTySize,
3889 RL,
3890 ShuffleAndReduceFn,
3891 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003892
Alexey Bataev8e009032019-01-04 17:25:09 +00003893 Res = CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
3894 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2),
3895 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003896 } else {
3897 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003898 std::string Name = getName({"reduction"});
3899 llvm::Value *Lock = getCriticalRegionLock(Name);
3900 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003901 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003902 createNVPTXRuntimeFunction(
3903 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003904 Args);
3905 }
3906
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003907 // 5. Build if (res == 1)
3908 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3909 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3910 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3911 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3912 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003913
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003914 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003915 // thread in each team.
3916 // __kmpc_end_reduce{_nowait}(<gtid>);
3917 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003918 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003919
3920 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003921 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003922 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3923 auto IPriv = Privates.begin();
3924 auto ILHS = LHSExprs.begin();
3925 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003926 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003927 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3928 cast<DeclRefExpr>(*IRHS));
3929 ++IPriv;
3930 ++ILHS;
3931 ++IRHS;
3932 }
3933 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003934 if (ParallelReduction) {
3935 llvm::Value *EndArgs[] = {ThreadId};
3936 RegionCodeGenTy RCG(CodeGen);
3937 NVPTXActionTy Action(
3938 nullptr, llvm::None,
3939 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3940 EndArgs);
3941 RCG.setAction(Action);
3942 RCG(CGF);
3943 } else {
3944 assert(TeamsReduction && "expected teams reduction.");
3945 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3946 std::string Name = getName({"reduction"});
3947 llvm::Value *Lock = getCriticalRegionLock(Name);
3948 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3949 RegionCodeGenTy RCG(CodeGen);
3950 NVPTXActionTy Action(
3951 nullptr, llvm::None,
3952 createNVPTXRuntimeFunction(
3953 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3954 EndArgs);
3955 RCG.setAction(Action);
3956 RCG(CGF);
3957 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003958 // There is no need to emit line number for unconditional branch.
3959 (void)ApplyDebugLocation::CreateEmpty(CGF);
3960 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003961}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003962
3963const VarDecl *
3964CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3965 const VarDecl *NativeParam) const {
3966 if (!NativeParam->getType()->isReferenceType())
3967 return NativeParam;
3968 QualType ArgType = NativeParam->getType();
3969 QualifierCollector QC;
3970 const Type *NonQualTy = QC.strip(ArgType);
3971 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3972 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3973 if (Attr->getCaptureKind() == OMPC_map) {
3974 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3975 LangAS::opencl_global);
3976 }
3977 }
3978 ArgType = CGM.getContext().getPointerType(PointeeTy);
3979 QC.addRestrict();
3980 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003981 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003982 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003983 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003984 return ImplicitParamDecl::Create(
3985 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3986 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003987 return ParmVarDecl::Create(
3988 CGM.getContext(),
3989 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003990 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003991 NativeParam->getIdentifier(), ArgType,
3992 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003993}
3994
3995Address
3996CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3997 const VarDecl *NativeParam,
3998 const VarDecl *TargetParam) const {
3999 assert(NativeParam != TargetParam &&
4000 NativeParam->getType()->isReferenceType() &&
4001 "Native arg must not be the same as target arg.");
4002 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4003 QualType NativeParamType = NativeParam->getType();
4004 QualifierCollector QC;
4005 const Type *NonQualTy = QC.strip(NativeParamType);
4006 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4007 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004008 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004009 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004010 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004011 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004012 // First cast to generic.
4013 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4014 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4015 /*AddrSpace=*/0));
4016 // Cast from generic to native address space.
4017 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4018 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4019 NativePointeeAddrSpace));
4020 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4021 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004022 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004023 return NativeParamAddr;
4024}
4025
4026void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004027 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004028 ArrayRef<llvm::Value *> Args) const {
4029 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004030 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004031 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004032 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004033 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4034 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4035 break;
4036 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004037 llvm::Type *TargetType = FnType->getParamType(I);
4038 llvm::Value *NativeArg = Args[I];
4039 if (!TargetType->isPointerTy()) {
4040 TargetArgs.emplace_back(NativeArg);
4041 continue;
4042 }
4043 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004044 NativeArg,
4045 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004046 TargetArgs.emplace_back(
4047 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4048 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004049 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004050}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004051
4052/// Emit function which wraps the outline parallel region
4053/// and controls the arguments which are passed to this function.
4054/// The wrapper ensures that the outlined function is called
4055/// with the correct arguments when data is shared.
4056llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4057 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4058 ASTContext &Ctx = CGM.getContext();
4059 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4060
4061 // Create a function that takes as argument the source thread.
4062 FunctionArgList WrapperArgs;
4063 QualType Int16QTy =
4064 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4065 QualType Int32QTy =
4066 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004067 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004068 /*Id=*/nullptr, Int16QTy,
4069 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004070 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004071 /*Id=*/nullptr, Int32QTy,
4072 ImplicitParamDecl::Other);
4073 WrapperArgs.emplace_back(&ParallelLevelArg);
4074 WrapperArgs.emplace_back(&WrapperArg);
4075
Alexey Bataev9ff80832018-04-16 20:16:21 +00004076 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004077 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4078
4079 auto *Fn = llvm::Function::Create(
4080 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004081 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004082 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004083 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004084 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085
4086 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4087 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004088 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004089
4090 const auto *RD = CS.getCapturedRecordDecl();
4091 auto CurField = RD->field_begin();
4092
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004093 Address ZeroAddr = CGF.CreateMemTemp(
4094 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4095 /*Name*/ ".zero.addr");
4096 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004097 // Get the array of arguments.
4098 SmallVector<llvm::Value *, 8> Args;
4099
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004100 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4101 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004102
4103 CGBuilderTy &Bld = CGF.Builder;
4104 auto CI = CS.capture_begin();
4105
4106 // Use global memory for data sharing.
4107 // Handle passing of global args to workers.
4108 Address GlobalArgs =
4109 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4110 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4111 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4112 CGF.EmitRuntimeCall(
4113 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4114 DataSharingArgs);
4115
4116 // Retrieve the shared variables from the list of references returned
4117 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004118 Address SharedArgListAddress = Address::invalid();
4119 if (CS.capture_size() > 0 ||
4120 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4121 SharedArgListAddress = CGF.EmitLoadOfPointer(
4122 GlobalArgs, CGF.getContext()
4123 .getPointerType(CGF.getContext().getPointerType(
4124 CGF.getContext().VoidPtrTy))
4125 .castAs<PointerType>());
4126 }
4127 unsigned Idx = 0;
4128 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004129 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004130 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4131 Src, CGF.SizeTy->getPointerTo());
4132 llvm::Value *LB = CGF.EmitLoadOfScalar(
4133 TypedAddress,
4134 /*Volatile=*/false,
4135 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4136 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4137 Args.emplace_back(LB);
4138 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004139 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004140 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4141 Src, CGF.SizeTy->getPointerTo());
4142 llvm::Value *UB = CGF.EmitLoadOfScalar(
4143 TypedAddress,
4144 /*Volatile=*/false,
4145 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4146 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4147 Args.emplace_back(UB);
4148 ++Idx;
4149 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004150 if (CS.capture_size() > 0) {
4151 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004152 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4153 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004154 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004155 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004156 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4157 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4158 /*Volatile=*/false,
4159 CGFContext.getPointerType(ElemTy),
4160 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004161 if (CI->capturesVariableByCopy() &&
4162 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004163 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4164 CI->getLocation());
4165 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004166 Args.emplace_back(Arg);
4167 }
4168 }
4169
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004170 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004171 CGF.FinishFunction();
4172 return Fn;
4173}
4174
4175void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4176 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004177 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4178 return;
4179
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004180 assert(D && "Expected function or captured|block decl.");
4181 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4182 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004183 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4184 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004185 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004186 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004187 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4188 Body = FD->getBody();
4189 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4190 Body = BD->getBody();
4191 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4192 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004193 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004194 if (NeedToDelayGlobalization &&
4195 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4196 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004197 }
4198 if (!Body)
4199 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004200 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004201 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004202 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004203 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004204 TeamAndReductions.first = nullptr;
4205 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004206 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4207 VarChecker.getEscapedVariableLengthDecls();
4208 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004209 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004210 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4211 I->getSecond().MappedParams =
4212 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4213 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4214 I->getSecond().EscapedParameters.insert(
4215 VarChecker.getEscapedParameters().begin(),
4216 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004217 I->getSecond().EscapedVariableLengthDecls.append(
4218 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004219 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004220 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004221 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004222 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004223 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004224 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004225 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004226 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004227 VarChecker.Visit(Body);
4228 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004229 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004230 I->getSecond().SecondaryLocalVarData.emplace();
4231 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4232 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4233 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4234 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004235 Data.insert(
4236 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004237 }
4238 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004239 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004240 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004241 struct GlobalizationScope final : EHScopeStack::Cleanup {
4242 GlobalizationScope() = default;
4243
4244 void Emit(CodeGenFunction &CGF, Flags flags) override {
4245 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004246 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004247 }
4248 };
4249 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004250 }
4251}
4252
4253Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4254 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004255 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4256 return Address::invalid();
4257
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004258 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004259 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4260 if (I == FunctionGlobalizedDecls.end())
4261 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004262 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004263 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004264 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004265 if (VD->hasAttrs()) {
4266 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4267 E(VD->attr_end());
4268 IT != E; ++IT) {
4269 auto VDI = I->getSecond().LocalVarData.find(
4270 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4271 ->getCanonicalDecl());
4272 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004273 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004274 }
4275 }
4276 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004277}
4278
4279void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004280 FunctionGlobalizedDecls.erase(CGF.CurFn);
4281 CGOpenMPRuntime::functionFinished(CGF);
4282}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004283
4284void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4285 CodeGenFunction &CGF, const OMPLoopDirective &S,
4286 OpenMPDistScheduleClauseKind &ScheduleKind,
4287 llvm::Value *&Chunk) const {
4288 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4289 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4290 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4291 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4292 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004293 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004294 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004295 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4296 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004297}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004298
4299void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4300 CodeGenFunction &CGF, const OMPLoopDirective &S,
4301 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004302 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004303 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004304 // Chunk size is 1 in this case.
4305 llvm::APInt ChunkSize(32, 1);
4306 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4307 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4308 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004309}
Alexey Bataev60705422018-10-30 15:50:12 +00004310
4311void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4312 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4313 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4314 " Expected target-based directive.");
4315 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4316 for (const CapturedStmt::Capture &C : CS->captures()) {
4317 // Capture variables captured by reference in lambdas for target-based
4318 // directives.
4319 if (!C.capturesVariable())
4320 continue;
4321 const VarDecl *VD = C.getCapturedVar();
4322 const auto *RD = VD->getType()
4323 .getCanonicalType()
4324 .getNonReferenceType()
4325 ->getAsCXXRecordDecl();
4326 if (!RD || !RD->isLambda())
4327 continue;
4328 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4329 LValue VDLVal;
4330 if (VD->getType().getCanonicalType()->isReferenceType())
4331 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4332 else
4333 VDLVal = CGF.MakeAddrLValue(
4334 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4335 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4336 FieldDecl *ThisCapture = nullptr;
4337 RD->getCaptureFields(Captures, ThisCapture);
4338 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4339 LValue ThisLVal =
4340 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4341 llvm::Value *CXXThis = CGF.LoadCXXThis();
4342 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4343 }
4344 for (const LambdaCapture &LC : RD->captures()) {
4345 if (LC.getCaptureKind() != LCK_ByRef)
4346 continue;
4347 const VarDecl *VD = LC.getCapturedVar();
4348 if (!CS->capturesVariable(VD))
4349 continue;
4350 auto It = Captures.find(VD);
4351 assert(It != Captures.end() && "Found lambda capture without field.");
4352 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4353 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4354 if (VD->getType().getCanonicalType()->isReferenceType())
4355 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4356 VD->getType().getCanonicalType())
4357 .getAddress();
4358 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4359 }
4360 }
4361}
4362
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004363// Get current CudaArch and ignore any unknown values
4364static CudaArch getCudaArch(CodeGenModule &CGM) {
4365 if (!CGM.getTarget().hasFeature("ptx"))
4366 return CudaArch::UNKNOWN;
4367 llvm::StringMap<bool> Features;
4368 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4369 CGM.getTarget().getTargetOpts().CPU,
4370 CGM.getTarget().getTargetOpts().Features);
4371 for (const auto &Feature : Features) {
4372 if (Feature.getValue()) {
4373 CudaArch Arch = StringToCudaArch(Feature.getKey());
4374 if (Arch != CudaArch::UNKNOWN)
4375 return Arch;
4376 }
4377 }
4378 return CudaArch::UNKNOWN;
4379}
4380
4381/// Check to see if target architecture supports unified addressing which is
4382/// a restriction for OpenMP requires clause "unified_shared_memory".
4383void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4384 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4385 for (const OMPClause *Clause : D->clauselists()) {
4386 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4387 switch (getCudaArch(CGM)) {
4388 case CudaArch::SM_20:
4389 case CudaArch::SM_21:
4390 case CudaArch::SM_30:
4391 case CudaArch::SM_32:
4392 case CudaArch::SM_35:
4393 case CudaArch::SM_37:
4394 case CudaArch::SM_50:
4395 case CudaArch::SM_52:
4396 case CudaArch::SM_53:
4397 case CudaArch::SM_60:
4398 case CudaArch::SM_61:
4399 case CudaArch::SM_62:
4400 CGM.Error(Clause->getBeginLoc(),
4401 "Target architecture does not support unified addressing");
4402 return;
4403 case CudaArch::SM_70:
4404 case CudaArch::SM_72:
4405 case CudaArch::SM_75:
4406 case CudaArch::GFX600:
4407 case CudaArch::GFX601:
4408 case CudaArch::GFX700:
4409 case CudaArch::GFX701:
4410 case CudaArch::GFX702:
4411 case CudaArch::GFX703:
4412 case CudaArch::GFX704:
4413 case CudaArch::GFX801:
4414 case CudaArch::GFX802:
4415 case CudaArch::GFX803:
4416 case CudaArch::GFX810:
4417 case CudaArch::GFX900:
4418 case CudaArch::GFX902:
4419 case CudaArch::GFX904:
4420 case CudaArch::GFX906:
4421 case CudaArch::GFX909:
4422 case CudaArch::UNKNOWN:
4423 break;
4424 case CudaArch::LAST:
4425 llvm_unreachable("Unexpected Cuda arch.");
4426 }
4427 }
4428 }
4429}
4430
Alexey Bataeve4090182018-11-02 14:54:07 +00004431/// Get number of SMs and number of blocks per SM.
4432static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4433 std::pair<unsigned, unsigned> Data;
4434 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4435 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4436 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4437 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4438 if (Data.first && Data.second)
4439 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004440 switch (getCudaArch(CGM)) {
4441 case CudaArch::SM_20:
4442 case CudaArch::SM_21:
4443 case CudaArch::SM_30:
4444 case CudaArch::SM_32:
4445 case CudaArch::SM_35:
4446 case CudaArch::SM_37:
4447 case CudaArch::SM_50:
4448 case CudaArch::SM_52:
4449 case CudaArch::SM_53:
4450 return {16, 16};
4451 case CudaArch::SM_60:
4452 case CudaArch::SM_61:
4453 case CudaArch::SM_62:
4454 return {56, 32};
4455 case CudaArch::SM_70:
4456 case CudaArch::SM_72:
4457 case CudaArch::SM_75:
4458 return {84, 32};
4459 case CudaArch::GFX600:
4460 case CudaArch::GFX601:
4461 case CudaArch::GFX700:
4462 case CudaArch::GFX701:
4463 case CudaArch::GFX702:
4464 case CudaArch::GFX703:
4465 case CudaArch::GFX704:
4466 case CudaArch::GFX801:
4467 case CudaArch::GFX802:
4468 case CudaArch::GFX803:
4469 case CudaArch::GFX810:
4470 case CudaArch::GFX900:
4471 case CudaArch::GFX902:
4472 case CudaArch::GFX904:
4473 case CudaArch::GFX906:
4474 case CudaArch::GFX909:
4475 case CudaArch::UNKNOWN:
4476 break;
4477 case CudaArch::LAST:
4478 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004479 }
4480 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4481}
4482
4483void CGOpenMPRuntimeNVPTX::clear() {
Alexey Bataeve4e9ba22019-01-28 20:03:02 +00004484 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
4485 if (CGM.getCodeGenOpts().getDebugInfo() >=
4486 codegenoptions::LimitedDebugInfo) {
4487 ASTContext &C = CGM.getContext();
4488 auto *VD = VarDecl::Create(
4489 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
4490 &C.Idents.get("_$_"), C.IntTy, /*TInfo=*/nullptr, SC_Static);
4491 auto *Var = cast<llvm::GlobalVariable>(
4492 CGM.CreateRuntimeVariable(CGM.IntTy, "_$_"));
4493 Var->setInitializer(llvm::ConstantInt::getNullValue(CGM.IntTy));
4494 Var->setLinkage(llvm::GlobalVariable::CommonLinkage);
4495 CGM.addCompilerUsedGlobal(Var);
4496 DI->EmitGlobalVariable(Var, VD);
4497 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004498 if (!GlobalizedRecords.empty()) {
4499 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004500 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4501 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004502 RecordDecl *StaticRD = C.buildImplicitRecord(
4503 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4504 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004505 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4506 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4507 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004508 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4509 if (Records.Records.empty())
4510 continue;
4511 unsigned Size = 0;
4512 unsigned RecAlignment = 0;
4513 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004514 QualType RDTy = C.getRecordType(RD);
4515 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004516 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004517 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004518 Size =
4519 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4520 }
4521 Size = llvm::alignTo(Size, RecAlignment);
4522 llvm::APInt ArySize(/*numBits=*/64, Size);
4523 QualType SubTy = C.getConstantArrayType(
4524 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004525 const bool UseSharedMemory = Size <= SharedMemorySize;
4526 auto *Field =
4527 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4528 SourceLocation(), SourceLocation(), nullptr, SubTy,
4529 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4530 /*BW=*/nullptr, /*Mutable=*/false,
4531 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004532 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004533 if (UseSharedMemory) {
4534 SharedStaticRD->addDecl(Field);
4535 SharedRecs.push_back(&Records);
4536 } else {
4537 StaticRD->addDecl(Field);
4538 GlobalRecs.push_back(&Records);
4539 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004540 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004541 Records.UseSharedMemory->setInitializer(
4542 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4543 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004544 // Allocate SharedMemorySize buffer for the shared memory.
4545 // FIXME: nvlink does not handle weak linkage correctly (object with the
4546 // different size are reported as erroneous).
4547 // Restore this code as sson as nvlink is fixed.
4548 if (!SharedStaticRD->field_empty()) {
4549 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4550 QualType SubTy = C.getConstantArrayType(
4551 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4552 auto *Field = FieldDecl::Create(
4553 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4554 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4555 /*BW=*/nullptr, /*Mutable=*/false,
4556 /*InitStyle=*/ICIS_NoInit);
4557 Field->setAccess(AS_public);
4558 SharedStaticRD->addDecl(Field);
4559 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004560 SharedStaticRD->completeDefinition();
4561 if (!SharedStaticRD->field_empty()) {
4562 QualType StaticTy = C.getRecordType(SharedStaticRD);
4563 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4564 auto *GV = new llvm::GlobalVariable(
4565 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004566 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004567 llvm::Constant::getNullValue(LLVMStaticTy),
4568 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4569 llvm::GlobalValue::NotThreadLocal,
4570 C.getTargetAddressSpace(LangAS::cuda_shared));
4571 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4572 GV, CGM.VoidPtrTy);
4573 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4574 Rec->Buffer->replaceAllUsesWith(Replacement);
4575 Rec->Buffer->eraseFromParent();
4576 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004577 }
4578 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004579 if (!StaticRD->field_empty()) {
4580 QualType StaticTy = C.getRecordType(StaticRD);
4581 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4582 llvm::APInt Size1(32, SMsBlockPerSM.second);
4583 QualType Arr1Ty =
4584 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4585 /*IndexTypeQuals=*/0);
4586 llvm::APInt Size2(32, SMsBlockPerSM.first);
4587 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4588 /*IndexTypeQuals=*/0);
4589 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4590 auto *GV = new llvm::GlobalVariable(
4591 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004592 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004593 llvm::Constant::getNullValue(LLVMArr2Ty),
4594 "_openmp_static_glob_rd_$_");
4595 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4596 GV, CGM.VoidPtrTy);
4597 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4598 Rec->Buffer->replaceAllUsesWith(Replacement);
4599 Rec->Buffer->eraseFromParent();
4600 }
4601 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004602 }
4603 CGOpenMPRuntime::clear();
4604}