blob: 9748dce22cec3164c0f22c03e7bec9c5583325fd [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 =
2243 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2244 .getPointer();
2245 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2246 I->getSecond().IsInSPMDModeFlag = nullptr;
2247 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2248 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002249 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002250 // TODO: allow the usage of shared memory to be controlled by
2251 // the user, for now, default to global.
2252 llvm::Value *GlobalRecordSizeArg[] = {
2253 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2254 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002255 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2256 createNVPTXRuntimeFunction(
2257 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2258 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002259 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002260 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002261 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2262 I->getSecond().IsInSPMDModeFlag = nullptr;
2263 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002264 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002265 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002266
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002267 // Emit the "global alloca" which is a GEP from the global declaration
2268 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002269 LValue SecBase;
2270 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2271 if (IsTTD) {
2272 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2273 llvm::PointerType *SecGlobalRecPtrTy =
2274 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2275 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2276 Bld.CreatePointerBitCastOrAddrSpaceCast(
2277 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2278 SecGlobalRecTy);
2279 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002280 for (auto &Rec : I->getSecond().LocalVarData) {
2281 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2282 llvm::Value *ParValue;
2283 if (EscapedParam) {
2284 const auto *VD = cast<VarDecl>(Rec.first);
2285 LValue ParLVal =
2286 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2287 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2288 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002289 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2290 // Emit VarAddr basing on lane-id if required.
2291 QualType VarTy;
2292 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002293 VarTy = Rec.second.FD->getType();
2294 } else {
2295 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2296 VarAddr.getAddress().getPointer(),
2297 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002298 VarTy =
2299 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002300 VarAddr = CGF.MakeAddrLValue(
2301 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2302 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002303 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002304 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002305 if (!IsInTTDRegion &&
2306 (WithSPMDCheck ||
2307 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002308 assert(I->getSecond().IsInSPMDModeFlag &&
2309 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002310 if (IsTTD) {
2311 assert(SecIt->second.IsOnePerTeam &&
2312 "Secondary glob data must be one per team.");
2313 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2314 VarAddr.setAddress(
2315 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2316 VarAddr.getPointer()),
2317 VarAddr.getAlignment()));
2318 Rec.second.PrivateAddr = VarAddr.getAddress();
2319 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002320 Address GlobalPtr = Rec.second.PrivateAddr;
2321 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2322 Rec.second.PrivateAddr = Address(
2323 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2324 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2325 LocalAddr.getAlignment());
2326 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002327 if (EscapedParam) {
2328 const auto *VD = cast<VarDecl>(Rec.first);
2329 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2330 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2331 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002332 if (IsTTD)
2333 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002334 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002335 }
2336 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2337 // Recover pointer to this function's global record. The runtime will
2338 // handle the specifics of the allocation of the memory.
2339 // Use actual memory size of the record including the padding
2340 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002341 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002342 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2343 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2344 Size = Bld.CreateNUWAdd(
2345 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2346 llvm::Value *AlignVal =
2347 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2348 Size = Bld.CreateUDiv(Size, AlignVal);
2349 Size = Bld.CreateNUWMul(Size, AlignVal);
2350 // TODO: allow the usage of shared memory to be controlled by
2351 // the user, for now, default to global.
2352 llvm::Value *GlobalRecordSizeArg[] = {
2353 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2354 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002355 createNVPTXRuntimeFunction(
2356 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002357 GlobalRecordSizeArg);
2358 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2359 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2360 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2361 CGM.getContext().getDeclAlign(VD),
2362 AlignmentSource::Decl);
2363 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2364 Base.getAddress());
2365 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002366 }
2367 I->getSecond().MappedParams->apply(CGF);
2368}
2369
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002370void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2371 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002372 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2373 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002374 return;
2375
Alexey Bataevc99042b2018-03-15 18:10:54 +00002376 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002377 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002378 I->getSecond().MappedParams->restore(CGF);
2379 if (!CGF.HaveInsertPoint())
2380 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002381 for (llvm::Value *Addr :
2382 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2383 CGF.EmitRuntimeCall(
2384 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2385 Addr);
2386 }
2387 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002388 if (!IsInTTDRegion &&
2389 (WithSPMDCheck ||
2390 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002391 CGBuilderTy &Bld = CGF.Builder;
2392 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2393 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2394 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2395 // There is no need to emit line number for unconditional branch.
2396 (void)ApplyDebugLocation::CreateEmpty(CGF);
2397 CGF.EmitBlock(NonSPMDBB);
2398 CGF.EmitRuntimeCall(
2399 createNVPTXRuntimeFunction(
2400 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2401 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2402 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002403 } else if (IsInTTDRegion) {
2404 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2405 "region counter must be > 0.");
2406 --GlobalizedRecords.back().RegionCounter;
2407 // Emit the restore function only in the target region.
2408 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002409 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2410 /*DestWidth=*/16, /*Signed=*/0);
2411 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2412 Address(GlobalizedRecords.back().UseSharedMemory,
2413 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2414 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002415 llvm::Value *Args[] = {
2416 llvm::ConstantInt::get(
2417 CGM.Int16Ty,
2418 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2419 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002420 CGF.EmitRuntimeCall(
2421 createNVPTXRuntimeFunction(
2422 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002423 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002424 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002425 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002426 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2427 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2428 I->getSecond().GlobalRecordAddr);
2429 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002430 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002431 }
2432}
2433
Carlo Bertollic6872252016-04-04 15:55:02 +00002434void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2435 const OMPExecutableDirective &D,
2436 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002437 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002438 ArrayRef<llvm::Value *> CapturedVars) {
2439 if (!CGF.HaveInsertPoint())
2440 return;
2441
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002442 Address ZeroAddr = CGF.CreateMemTemp(
2443 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2444 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002445 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2446 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002447 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002448 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2449 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002450 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002451}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002452
2453void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002454 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002455 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2456 if (!CGF.HaveInsertPoint())
2457 return;
2458
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002459 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002460 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002461 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002462 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002463}
2464
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002465void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002466 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2467 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2468 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002469
2470 // Force inline this outlined function at its call site.
2471 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2472
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002473 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2474 /*DestWidth=*/32, /*Signed=*/1),
2475 ".zero.addr");
2476 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002477 // ThreadId for serialized parallels is 0.
2478 Address ThreadIDAddr = ZeroAddr;
2479 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002480 CodeGenFunction &CGF, PrePostActionTy &Action) {
2481 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002482
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002483 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2484 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2485 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2486 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2487 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2488 };
2489 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2490 PrePostActionTy &) {
2491
2492 RegionCodeGenTy RCG(CodeGen);
2493 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2494 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2495 llvm::Value *Args[] = {RTLoc, ThreadID};
2496
2497 NVPTXActionTy Action(
2498 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2499 Args,
2500 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2501 Args);
2502 RCG.setAction(Action);
2503 RCG(CGF);
2504 };
2505
2506 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2507 PrePostActionTy &Action) {
2508 CGBuilderTy &Bld = CGF.Builder;
2509 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2510 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002511 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2512
2513 // Prepare for parallel region. Indicate the outlined function.
2514 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002515 CGF.EmitRuntimeCall(
2516 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2517 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002518
2519 // Create a private scope that will globalize the arguments
2520 // passed from the outside of the target region.
2521 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2522
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002523 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002524 if (!CapturedVars.empty()) {
2525 // Prepare for parallel region. Indicate the outlined function.
2526 Address SharedArgs =
2527 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2528 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2529
2530 llvm::Value *DataSharingArgs[] = {
2531 SharedArgsPtr,
2532 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2533 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2534 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2535 DataSharingArgs);
2536
2537 // Store variable address in a list of references to pass to workers.
2538 unsigned Idx = 0;
2539 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002540 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2541 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2542 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002543 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002544 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2545 CGF.getPointerSize());
2546 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002547 if (V->getType()->isIntegerTy())
2548 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2549 else
2550 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002551 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2552 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002553 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002554 }
2555 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002556
2557 // Activate workers. This barrier is used by the master to signal
2558 // work for the workers.
2559 syncCTAThreads(CGF);
2560
2561 // OpenMP [2.5, Parallel Construct, p.49]
2562 // There is an implied barrier at the end of a parallel region. After the
2563 // end of a parallel region, only the master thread of the team resumes
2564 // execution of the enclosing task region.
2565 //
2566 // The master waits at this barrier until all workers are done.
2567 syncCTAThreads(CGF);
2568
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002569 if (!CapturedVars.empty())
2570 CGF.EmitRuntimeCall(
2571 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2572
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002573 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002574 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002575 };
2576
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002577 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2578 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002579 if (IsInParallelRegion) {
2580 SeqGen(CGF, Action);
2581 } else if (IsInTargetMasterThreadRegion) {
2582 L0ParallelGen(CGF, Action);
2583 } else {
2584 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002585 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002586 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002587 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002588 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002589 // }
2590 CGBuilderTy &Bld = CGF.Builder;
2591 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002592 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2593 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002594 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002595 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2596 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002597 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002598 // There is no need to emit line number for unconditional branch.
2599 (void)ApplyDebugLocation::CreateEmpty(CGF);
2600 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002601 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2602 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2603 llvm::Value *PL = CGF.EmitRuntimeCall(
2604 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2605 {RTLoc, ThreadID});
2606 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002607 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002608 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002609 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002610 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 // There is no need to emit line number for unconditional branch.
2612 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002613 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002614 L0ParallelGen(CGF, Action);
2615 CGF.EmitBranch(ExitBB);
2616 // There is no need to emit line number for unconditional branch.
2617 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002618 // Emit the continuation block for code after the if.
2619 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2620 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002621 };
2622
Alexey Bataev9ff80832018-04-16 20:16:21 +00002623 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002624 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002625 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002626 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002627 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002628 ThenRCG(CGF);
2629 }
2630}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002631
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002632void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002633 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002634 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2635 // Just call the outlined function to execute the parallel region.
2636 // OutlinedFn(&GTid, &zero, CapturedStruct);
2637 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002638 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002639
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002640 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2641 /*DestWidth=*/32, /*Signed=*/1),
2642 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002643 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002644 // ThreadId for serialized parallels is 0.
2645 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002646 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002647 &ThreadIDAddr](CodeGenFunction &CGF,
2648 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002649 Action.Enter(CGF);
2650
2651 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2652 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2653 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2654 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2655 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2656 };
2657 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2658 PrePostActionTy &) {
2659
2660 RegionCodeGenTy RCG(CodeGen);
2661 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2662 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2663 llvm::Value *Args[] = {RTLoc, ThreadID};
2664
2665 NVPTXActionTy Action(
2666 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2667 Args,
2668 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2669 Args);
2670 RCG.setAction(Action);
2671 RCG(CGF);
2672 };
2673
2674 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002675 // In the worker need to use the real thread id.
2676 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002677 RegionCodeGenTy RCG(CodeGen);
2678 RCG(CGF);
2679 } else {
2680 // If we are not in the target region, it is definitely L2 parallelism or
2681 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2682 // need to check for orphaned directives.
2683 RegionCodeGenTy RCG(SeqGen);
2684 RCG(CGF);
2685 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002686}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002687
Alexey Bataeva3924b52019-01-03 16:25:35 +00002688void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2689 // Always emit simple barriers!
2690 if (!CGF.HaveInsertPoint())
2691 return;
2692 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2693 // This function does not use parameters, so we can emit just default values.
2694 llvm::Value *Args[] = {
2695 llvm::ConstantPointerNull::get(
2696 cast<llvm::PointerType>(getIdentTyPointerTy())),
2697 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2698 CGF.EmitRuntimeCall(
2699 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2700}
2701
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002702void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2703 SourceLocation Loc,
2704 OpenMPDirectiveKind Kind, bool,
2705 bool) {
2706 // Always emit simple barriers!
2707 if (!CGF.HaveInsertPoint())
2708 return;
2709 // Build call __kmpc_cancel_barrier(loc, thread_id);
2710 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2711 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2712 getThreadID(CGF, Loc)};
2713 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2714}
2715
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002716void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2717 CodeGenFunction &CGF, StringRef CriticalName,
2718 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2719 const Expr *Hint) {
2720 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2721 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2722 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2723 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2724 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2725
2726 // Fetch team-local id of the thread.
2727 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2728
2729 // Get the width of the team.
2730 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2731
2732 // Initialize the counter variable for the loop.
2733 QualType Int32Ty =
2734 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2735 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2736 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2737 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2738 /*isInit=*/true);
2739
2740 // Block checks if loop counter exceeds upper bound.
2741 CGF.EmitBlock(LoopBB);
2742 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2743 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2744 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2745
2746 // Block tests which single thread should execute region, and which threads
2747 // should go straight to synchronisation point.
2748 CGF.EmitBlock(TestBB);
2749 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2750 llvm::Value *CmpThreadToCounter =
2751 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2752 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2753
2754 // Block emits the body of the critical region.
2755 CGF.EmitBlock(BodyBB);
2756
2757 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002758 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2759 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002760
2761 // After the body surrounded by the critical region, the single executing
2762 // thread will jump to the synchronisation point.
2763 // Block waits for all threads in current team to finish then increments the
2764 // counter variable and returns to the loop.
2765 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002766 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2767 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002768
2769 llvm::Value *IncCounterVal =
2770 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2771 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2772 CGF.EmitBranch(LoopBB);
2773
2774 // Block that is reached when all threads in the team complete the region.
2775 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2776}
2777
Alexey Bataevb2575932018-01-04 20:18:55 +00002778/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002779static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2780 QualType ValTy, QualType CastTy,
2781 SourceLocation Loc) {
2782 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2783 "Cast type must sized.");
2784 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2785 "Val type must sized.");
2786 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2787 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002788 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002789 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2790 CGF.getContext().getTypeSizeInChars(CastTy))
2791 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2792 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2793 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2794 CastTy->hasSignedIntegerRepresentation());
2795 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002796 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2797 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002798 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2799 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002800}
2801
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002802/// This function creates calls to one of two shuffle functions to copy
2803/// variables between lanes in a warp.
2804static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002806 QualType ElemType,
2807 llvm::Value *Offset,
2808 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002809 CodeGenModule &CGM = CGF.CGM;
2810 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002811 CGOpenMPRuntimeNVPTX &RT =
2812 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2813
Alexey Bataeva453f362018-03-19 17:53:56 +00002814 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2815 assert(Size.getQuantity() <= 8 &&
2816 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002817
Alexey Bataeva453f362018-03-19 17:53:56 +00002818 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002819 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2820 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2821
2822 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002823 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2824 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2825 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002826 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002827 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002828
Alexey Bataev9ff80832018-04-16 20:16:21 +00002829 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2830 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002831
Alexey Bataeva453f362018-03-19 17:53:56 +00002832 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002833}
2834
Alexey Bataev12c62902018-06-22 19:10:38 +00002835static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2836 Address DestAddr, QualType ElemType,
2837 llvm::Value *Offset, SourceLocation Loc) {
2838 CGBuilderTy &Bld = CGF.Builder;
2839
2840 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2841 // Create the loop over the big sized data.
2842 // ptr = (void*)Elem;
2843 // ptrEnd = (void*) Elem + 1;
2844 // Step = 8;
2845 // while (ptr + Step < ptrEnd)
2846 // shuffle((int64_t)*ptr);
2847 // Step = 4;
2848 // while (ptr + Step < ptrEnd)
2849 // shuffle((int32_t)*ptr);
2850 // ...
2851 Address ElemPtr = DestAddr;
2852 Address Ptr = SrcAddr;
2853 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2854 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2855 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2856 if (Size < CharUnits::fromQuantity(IntSize))
2857 continue;
2858 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2859 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2860 /*Signed=*/1);
2861 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2862 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2863 ElemPtr =
2864 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2865 if (Size.getQuantity() / IntSize > 1) {
2866 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2867 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2868 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2869 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2870 CGF.EmitBlock(PreCondBB);
2871 llvm::PHINode *PhiSrc =
2872 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2873 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2874 llvm::PHINode *PhiDest =
2875 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2876 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2877 Ptr = Address(PhiSrc, Ptr.getAlignment());
2878 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2879 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2880 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2881 Ptr.getPointer(), CGF.VoidPtrTy));
2882 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2883 ThenBB, ExitBB);
2884 CGF.EmitBlock(ThenBB);
2885 llvm::Value *Res = createRuntimeShuffleFunction(
2886 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2887 IntType, Offset, Loc);
2888 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002889 Address LocalPtr =
2890 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2891 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002892 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002893 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2894 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002895 CGF.EmitBranch(PreCondBB);
2896 CGF.EmitBlock(ExitBB);
2897 } else {
2898 llvm::Value *Res = createRuntimeShuffleFunction(
2899 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2900 IntType, Offset, Loc);
2901 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2902 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2903 ElemPtr =
2904 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2905 }
2906 Size = Size % IntSize;
2907 }
2908}
2909
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002910namespace {
2911enum CopyAction : unsigned {
2912 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2913 // the warp using shuffle instructions.
2914 RemoteLaneToThread,
2915 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2916 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002917 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2918 ThreadToScratchpad,
2919 // ScratchpadToThread: Copy from a scratchpad array in global memory
2920 // containing team-reduced data to a thread's stack.
2921 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002922};
2923} // namespace
2924
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002925struct CopyOptionsTy {
2926 llvm::Value *RemoteLaneOffset;
2927 llvm::Value *ScratchpadIndex;
2928 llvm::Value *ScratchpadWidth;
2929};
2930
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002931/// Emit instructions to copy a Reduce list, which contains partially
2932/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002933static void emitReductionListCopy(
2934 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2935 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2936 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937
Alexey Bataev9ff80832018-04-16 20:16:21 +00002938 CodeGenModule &CGM = CGF.CGM;
2939 ASTContext &C = CGM.getContext();
2940 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002941
Alexey Bataev9ff80832018-04-16 20:16:21 +00002942 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2943 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2944 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002945
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002946 // Iterates, element-by-element, through the source Reduce list and
2947 // make a copy.
2948 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002949 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002950 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002951 Address SrcElementAddr = Address::invalid();
2952 Address DestElementAddr = Address::invalid();
2953 Address DestElementPtrAddr = Address::invalid();
2954 // Should we shuffle in an element from a remote lane?
2955 bool ShuffleInElement = false;
2956 // Set to true to update the pointer in the dest Reduce list to a
2957 // newly created element.
2958 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002959 // Increment the src or dest pointer to the scratchpad, for each
2960 // new element.
2961 bool IncrScratchpadSrc = false;
2962 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002963
2964 switch (Action) {
2965 case RemoteLaneToThread: {
2966 // Step 1.1: Get the address for the src element in the Reduce list.
2967 Address SrcElementPtrAddr =
2968 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002969 SrcElementAddr = CGF.EmitLoadOfPointer(
2970 SrcElementPtrAddr,
2971 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002972
2973 // Step 1.2: Create a temporary to store the element in the destination
2974 // Reduce list.
2975 DestElementPtrAddr =
2976 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2977 DestElementAddr =
2978 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2979 ShuffleInElement = true;
2980 UpdateDestListPtr = true;
2981 break;
2982 }
2983 case ThreadCopy: {
2984 // Step 1.1: Get the address for the src element in the Reduce list.
2985 Address SrcElementPtrAddr =
2986 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002987 SrcElementAddr = CGF.EmitLoadOfPointer(
2988 SrcElementPtrAddr,
2989 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990
2991 // Step 1.2: Get the address for dest element. The destination
2992 // element has already been created on the thread's stack.
2993 DestElementPtrAddr =
2994 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002995 DestElementAddr = CGF.EmitLoadOfPointer(
2996 DestElementPtrAddr,
2997 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002998 break;
2999 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003000 case ThreadToScratchpad: {
3001 // Step 1.1: Get the address for the src element in the Reduce list.
3002 Address SrcElementPtrAddr =
3003 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00003004 SrcElementAddr = CGF.EmitLoadOfPointer(
3005 SrcElementPtrAddr,
3006 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003007
3008 // Step 1.2: Get the address for dest element:
3009 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003010 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003011 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003012 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003013 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003014 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003015 ScratchPadElemAbsolutePtrVal =
3016 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003017 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3018 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003019 IncrScratchpadDest = true;
3020 break;
3021 }
3022 case ScratchpadToThread: {
3023 // Step 1.1: Get the address for the src element in the scratchpad.
3024 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003025 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003026 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003027 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003028 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003029 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003030 ScratchPadElemAbsolutePtrVal =
3031 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3032 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3033 C.getTypeAlignInChars(Private->getType()));
3034 IncrScratchpadSrc = true;
3035
3036 // Step 1.2: Create a temporary to store the element in the destination
3037 // Reduce list.
3038 DestElementPtrAddr =
3039 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3040 DestElementAddr =
3041 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3042 UpdateDestListPtr = true;
3043 break;
3044 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003045 }
3046
3047 // Regardless of src and dest of copy, we emit the load of src
3048 // element as this is required in all directions
3049 SrcElementAddr = Bld.CreateElementBitCast(
3050 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003051 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3052 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003053
3054 // Now that all active lanes have read the element in the
3055 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003056 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003057 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3058 RemoteLaneOffset, Private->getExprLoc());
3059 } else {
3060 if (Private->getType()->isScalarType()) {
3061 llvm::Value *Elem =
3062 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3063 Private->getType(), Private->getExprLoc());
3064 // Store the source element value to the dest element address.
3065 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3066 Private->getType());
3067 } else {
3068 CGF.EmitAggregateCopy(
3069 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3070 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3071 Private->getType(), AggValueSlot::DoesNotOverlap);
3072 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003073 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003074
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003075 // Step 3.1: Modify reference in dest Reduce list as needed.
3076 // Modifying the reference in Reduce list to point to the newly
3077 // created element. The element is live in the current function
3078 // scope and that of functions it invokes (i.e., reduce_function).
3079 // RemoteReduceData[i] = (void*)&RemoteElem
3080 if (UpdateDestListPtr) {
3081 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3082 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3083 DestElementPtrAddr, /*Volatile=*/false,
3084 C.VoidPtrTy);
3085 }
3086
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003087 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3088 // address of the next element in scratchpad memory, unless we're currently
3089 // processing the last one. Memory alignment is also taken care of here.
3090 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3091 llvm::Value *ScratchpadBasePtr =
3092 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003093 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3094 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003095 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003096 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003097
3098 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003099 ScratchpadBasePtr = Bld.CreateNUWSub(
3100 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3101 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003102 ScratchpadBasePtr,
3103 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003104 ScratchpadBasePtr = Bld.CreateNUWAdd(
3105 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3106 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003107 ScratchpadBasePtr,
3108 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3109
3110 if (IncrScratchpadDest)
3111 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3112 else /* IncrScratchpadSrc = true */
3113 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3114 }
3115
Alexey Bataev9ff80832018-04-16 20:16:21 +00003116 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003117 }
3118}
3119
3120/// This function emits a helper that gathers Reduce lists from the first
3121/// lane of every active warp to lanes in the first warp.
3122///
3123/// void inter_warp_copy_func(void* reduce_data, num_warps)
3124/// shared smem[warp_size];
3125/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003126/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003127/// If (I am the first lane in each warp)
3128/// Copy my local D to smem[warp_id]
3129/// sync
3130/// if (I am the first warp)
3131/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003132static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3133 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003134 QualType ReductionArrayTy,
3135 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003136 ASTContext &C = CGM.getContext();
3137 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138
3139 // ReduceList: thread local Reduce list.
3140 // At the stage of the computation when this function is called, partially
3141 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003142 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3143 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003144 // NumWarps: number of warps active in the parallel region. This could
3145 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003146 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003147 C.getIntTypeForBitwidth(32, /* Signed */ true),
3148 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 FunctionArgList Args;
3150 Args.push_back(&ReduceListArg);
3151 Args.push_back(&NumWarpsArg);
3152
Alexey Bataev9ff80832018-04-16 20:16:21 +00003153 const CGFunctionInfo &CGFI =
3154 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003155 auto *Fn = llvm::Function::Create(
3156 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3157 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003158 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003159 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003161 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003162
Alexey Bataev9ff80832018-04-16 20:16:21 +00003163 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164
3165 // This array is used as a medium to transfer, one reduce element at a time,
3166 // the data from the first lane of every warp to lanes in the first warp
3167 // in order to perform the final step of a reduction in a parallel region
3168 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3169 // for reduced latency, as well as to have a distinct copy for concurrently
3170 // executing target regions. The array is declared with common linkage so
3171 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003172 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003173 "__openmp_nvptx_data_transfer_temporary_storage";
3174 llvm::GlobalVariable *TransferMedium =
3175 M.getGlobalVariable(TransferMediumName);
3176 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003177 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3179 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003180 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181 llvm::Constant::getNullValue(Ty), TransferMediumName,
3182 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3183 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003184 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 }
3186
3187 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003188 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003190 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003191 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003192 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003193
3194 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3195 Address LocalReduceList(
3196 Bld.CreatePointerBitCastOrAddrSpaceCast(
3197 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003198 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003199 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3200 CGF.getPointerAlign());
3201
3202 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003203 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003204 //
3205 // Warp master copies reduce element to transfer medium in __shared__
3206 // memory.
3207 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003208 unsigned RealTySize =
3209 C.getTypeSizeInChars(Private->getType())
3210 .alignTo(C.getTypeAlignInChars(Private->getType()))
3211 .getQuantity();
3212 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3213 unsigned NumIters = RealTySize / TySize;
3214 if (NumIters == 0)
3215 continue;
3216 QualType CType = C.getIntTypeForBitwidth(
3217 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3218 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3219 CharUnits Align = CharUnits::fromQuantity(TySize);
3220 llvm::Value *Cnt = nullptr;
3221 Address CntAddr = Address::invalid();
3222 llvm::BasicBlock *PrecondBB = nullptr;
3223 llvm::BasicBlock *ExitBB = nullptr;
3224 if (NumIters > 1) {
3225 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3226 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3227 /*Volatile=*/false, C.IntTy);
3228 PrecondBB = CGF.createBasicBlock("precond");
3229 ExitBB = CGF.createBasicBlock("exit");
3230 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3231 // There is no need to emit line number for unconditional branch.
3232 (void)ApplyDebugLocation::CreateEmpty(CGF);
3233 CGF.EmitBlock(PrecondBB);
3234 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3235 llvm::Value *Cmp =
3236 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3237 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3238 CGF.EmitBlock(BodyBB);
3239 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003240 // kmpc_barrier.
3241 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3242 /*EmitChecks=*/false,
3243 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003244 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3245 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3246 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003247
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003248 // if (lane_id == 0)
3249 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3250 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3251 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003252
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003253 // Reduce element = LocalReduceList[i]
3254 Address ElemPtrPtrAddr =
3255 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3256 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3257 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3258 // elemptr = ((CopyType*)(elemptrptr)) + I
3259 Address ElemPtr = Address(ElemPtrPtr, Align);
3260 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3261 if (NumIters > 1) {
3262 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3263 ElemPtr.getAlignment());
3264 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003265
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003266 // Get pointer to location in transfer medium.
3267 // MediumPtr = &medium[warp_id]
3268 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3269 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3270 Address MediumPtr(MediumPtrVal, Align);
3271 // Casting to actual data type.
3272 // MediumPtr = (CopyType*)MediumPtrAddr;
3273 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003275 // elem = *elemptr
3276 //*MediumPtr = elem
3277 llvm::Value *Elem =
3278 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003279 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003283
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003284 CGF.EmitBlock(ElseBB);
3285 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003288
Alexey Bataevae51b962018-12-14 21:00:58 +00003289 // kmpc_barrier.
3290 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3291 /*EmitChecks=*/false,
3292 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003293
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003294 //
3295 // Warp 0 copies reduce element from transfer medium.
3296 //
3297 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3298 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3299 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003300
Alexey Bataevae51b962018-12-14 21:00:58 +00003301 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3302 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3303 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3304
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003305 // Up to 32 threads in warp 0 are active.
3306 llvm::Value *IsActiveThread =
3307 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3308 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003309
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003310 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003311
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003312 // SrcMediumPtr = &medium[tid]
3313 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3314 TransferMedium,
3315 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3316 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3317 // SrcMediumVal = *SrcMediumPtr;
3318 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003319
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003320 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3321 Address TargetElemPtrPtr =
3322 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3323 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3324 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3325 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3326 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3327 if (NumIters > 1) {
3328 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3329 TargetElemPtr.getAlignment());
3330 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003331
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003332 // *TargetElemPtr = SrcMediumVal;
3333 llvm::Value *SrcMediumValue =
3334 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003335 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003336 CType);
3337 Bld.CreateBr(W0MergeBB);
3338
3339 CGF.EmitBlock(W0ElseBB);
3340 Bld.CreateBr(W0MergeBB);
3341
3342 CGF.EmitBlock(W0MergeBB);
3343
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003344 if (NumIters > 1) {
3345 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3346 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3347 CGF.EmitBranch(PrecondBB);
3348 (void)ApplyDebugLocation::CreateEmpty(CGF);
3349 CGF.EmitBlock(ExitBB);
3350 }
3351 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003352 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003353 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003354 }
3355
3356 CGF.FinishFunction();
3357 return Fn;
3358}
3359
3360/// Emit a helper that reduces data across two OpenMP threads (lanes)
3361/// in the same warp. It uses shuffle instructions to copy over data from
3362/// a remote lane's stack. The reduction algorithm performed is specified
3363/// by the fourth parameter.
3364///
3365/// Algorithm Versions.
3366/// Full Warp Reduce (argument value 0):
3367/// This algorithm assumes that all 32 lanes are active and gathers
3368/// data from these 32 lanes, producing a single resultant value.
3369/// Contiguous Partial Warp Reduce (argument value 1):
3370/// This algorithm assumes that only a *contiguous* subset of lanes
3371/// are active. This happens for the last warp in a parallel region
3372/// when the user specified num_threads is not an integer multiple of
3373/// 32. This contiguous subset always starts with the zeroth lane.
3374/// Partial Warp Reduce (argument value 2):
3375/// This algorithm gathers data from any number of lanes at any position.
3376/// All reduced values are stored in the lowest possible lane. The set
3377/// of problems every algorithm addresses is a super set of those
3378/// addressable by algorithms with a lower version number. Overhead
3379/// increases as algorithm version increases.
3380///
3381/// Terminology
3382/// Reduce element:
3383/// Reduce element refers to the individual data field with primitive
3384/// data types to be combined and reduced across threads.
3385/// Reduce list:
3386/// Reduce list refers to a collection of local, thread-private
3387/// reduce elements.
3388/// Remote Reduce list:
3389/// Remote Reduce list refers to a collection of remote (relative to
3390/// the current thread) reduce elements.
3391///
3392/// We distinguish between three states of threads that are important to
3393/// the implementation of this function.
3394/// Alive threads:
3395/// Threads in a warp executing the SIMT instruction, as distinguished from
3396/// threads that are inactive due to divergent control flow.
3397/// Active threads:
3398/// The minimal set of threads that has to be alive upon entry to this
3399/// function. The computation is correct iff active threads are alive.
3400/// Some threads are alive but they are not active because they do not
3401/// contribute to the computation in any useful manner. Turning them off
3402/// may introduce control flow overheads without any tangible benefits.
3403/// Effective threads:
3404/// In order to comply with the argument requirements of the shuffle
3405/// function, we must keep all lanes holding data alive. But at most
3406/// half of them perform value aggregation; we refer to this half of
3407/// threads as effective. The other half is simply handing off their
3408/// data.
3409///
3410/// Procedure
3411/// Value shuffle:
3412/// In this step active threads transfer data from higher lane positions
3413/// in the warp to lower lane positions, creating Remote Reduce list.
3414/// Value aggregation:
3415/// In this step, effective threads combine their thread local Reduce list
3416/// with Remote Reduce list and store the result in the thread local
3417/// Reduce list.
3418/// Value copy:
3419/// In this step, we deal with the assumption made by algorithm 2
3420/// (i.e. contiguity assumption). When we have an odd number of lanes
3421/// active, say 2k+1, only k threads will be effective and therefore k
3422/// new values will be produced. However, the Reduce list owned by the
3423/// (2k+1)th thread is ignored in the value aggregation. Therefore
3424/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3425/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003426static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003427 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003428 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003429 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430
3431 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003432 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3433 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003434 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003435 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3436 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003437 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003438 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3439 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003440 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003441 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3442 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443 FunctionArgList Args;
3444 Args.push_back(&ReduceListArg);
3445 Args.push_back(&LaneIDArg);
3446 Args.push_back(&RemoteLaneOffsetArg);
3447 Args.push_back(&AlgoVerArg);
3448
Alexey Bataev9ff80832018-04-16 20:16:21 +00003449 const CGFunctionInfo &CGFI =
3450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003451 auto *Fn = llvm::Function::Create(
3452 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3453 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003454 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003455 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003456 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003457 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003458
Alexey Bataev9ff80832018-04-16 20:16:21 +00003459 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460
3461 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3462 Address LocalReduceList(
3463 Bld.CreatePointerBitCastOrAddrSpaceCast(
3464 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3465 C.VoidPtrTy, SourceLocation()),
3466 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3467 CGF.getPointerAlign());
3468
3469 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3470 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3471 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3472
3473 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3474 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3475 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3476
3477 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3478 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3479 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3480
3481 // Create a local thread-private variable to host the Reduce list
3482 // from a remote lane.
3483 Address RemoteReduceList =
3484 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3485
3486 // This loop iterates through the list of reduce elements and copies,
3487 // element by element, from a remote lane in the warp to RemoteReduceList,
3488 // hosted on the thread's stack.
3489 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3490 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003491 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3492 /*ScratchpadIndex=*/nullptr,
3493 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003494
3495 // The actions to be performed on the Remote Reduce list is dependent
3496 // on the algorithm version.
3497 //
3498 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3499 // LaneId % 2 == 0 && Offset > 0):
3500 // do the reduction value aggregation
3501 //
3502 // The thread local variable Reduce list is mutated in place to host the
3503 // reduced data, which is the aggregated value produced from local and
3504 // remote lanes.
3505 //
3506 // Note that AlgoVer is expected to be a constant integer known at compile
3507 // time.
3508 // When AlgoVer==0, the first conjunction evaluates to true, making
3509 // the entire predicate true during compile time.
3510 // When AlgoVer==1, the second conjunction has only the second part to be
3511 // evaluated during runtime. Other conjunctions evaluates to false
3512 // during compile time.
3513 // When AlgoVer==2, the third conjunction has only the second part to be
3514 // evaluated during runtime. Other conjunctions evaluates to false
3515 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003516 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003517
Alexey Bataev9ff80832018-04-16 20:16:21 +00003518 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3519 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003520 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3521
Alexey Bataev9ff80832018-04-16 20:16:21 +00003522 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3523 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3524 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003525 CondAlgo2 = Bld.CreateAnd(
3526 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3527
Alexey Bataev9ff80832018-04-16 20:16:21 +00003528 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003529 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3530
3531 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3532 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3533 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3534 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3535
3536 CGF.EmitBlock(ThenBB);
3537 // reduce_function(LocalReduceList, RemoteReduceList)
3538 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3539 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3540 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3541 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003542 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3543 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003544 Bld.CreateBr(MergeBB);
3545
3546 CGF.EmitBlock(ElseBB);
3547 Bld.CreateBr(MergeBB);
3548
3549 CGF.EmitBlock(MergeBB);
3550
3551 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3552 // Reduce list.
3553 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003554 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003555 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3556
3557 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3558 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3559 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3560 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3561
3562 CGF.EmitBlock(CpyThenBB);
3563 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3564 RemoteReduceList, LocalReduceList);
3565 Bld.CreateBr(CpyMergeBB);
3566
3567 CGF.EmitBlock(CpyElseBB);
3568 Bld.CreateBr(CpyMergeBB);
3569
3570 CGF.EmitBlock(CpyMergeBB);
3571
3572 CGF.FinishFunction();
3573 return Fn;
3574}
3575
3576///
3577/// Design of OpenMP reductions on the GPU
3578///
3579/// Consider a typical OpenMP program with one or more reduction
3580/// clauses:
3581///
3582/// float foo;
3583/// double bar;
3584/// #pragma omp target teams distribute parallel for \
3585/// reduction(+:foo) reduction(*:bar)
3586/// for (int i = 0; i < N; i++) {
3587/// foo += A[i]; bar *= B[i];
3588/// }
3589///
3590/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3591/// all teams. In our OpenMP implementation on the NVPTX device an
3592/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3593/// within a team are mapped to CUDA threads within a threadblock.
3594/// Our goal is to efficiently aggregate values across all OpenMP
3595/// threads such that:
3596///
3597/// - the compiler and runtime are logically concise, and
3598/// - the reduction is performed efficiently in a hierarchical
3599/// manner as follows: within OpenMP threads in the same warp,
3600/// across warps in a threadblock, and finally across teams on
3601/// the NVPTX device.
3602///
3603/// Introduction to Decoupling
3604///
3605/// We would like to decouple the compiler and the runtime so that the
3606/// latter is ignorant of the reduction variables (number, data types)
3607/// and the reduction operators. This allows a simpler interface
3608/// and implementation while still attaining good performance.
3609///
3610/// Pseudocode for the aforementioned OpenMP program generated by the
3611/// compiler is as follows:
3612///
3613/// 1. Create private copies of reduction variables on each OpenMP
3614/// thread: 'foo_private', 'bar_private'
3615/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3616/// to it and writes the result in 'foo_private' and 'bar_private'
3617/// respectively.
3618/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3619/// and store the result on the team master:
3620///
Alexey Bataev8e009032019-01-04 17:25:09 +00003621/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003622/// reduceData, shuffleReduceFn, interWarpCpyFn)
3623///
3624/// where:
3625/// struct ReduceData {
3626/// double *foo;
3627/// double *bar;
3628/// } reduceData
3629/// reduceData.foo = &foo_private
3630/// reduceData.bar = &bar_private
3631///
3632/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3633/// auxiliary functions generated by the compiler that operate on
3634/// variables of type 'ReduceData'. They aid the runtime perform
3635/// algorithmic steps in a data agnostic manner.
3636///
3637/// 'shuffleReduceFn' is a pointer to a function that reduces data
3638/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3639/// same warp. It takes the following arguments as input:
3640///
3641/// a. variable of type 'ReduceData' on the calling lane,
3642/// b. its lane_id,
3643/// c. an offset relative to the current lane_id to generate a
3644/// remote_lane_id. The remote lane contains the second
3645/// variable of type 'ReduceData' that is to be reduced.
3646/// d. an algorithm version parameter determining which reduction
3647/// algorithm to use.
3648///
3649/// 'shuffleReduceFn' retrieves data from the remote lane using
3650/// efficient GPU shuffle intrinsics and reduces, using the
3651/// algorithm specified by the 4th parameter, the two operands
3652/// element-wise. The result is written to the first operand.
3653///
3654/// Different reduction algorithms are implemented in different
3655/// runtime functions, all calling 'shuffleReduceFn' to perform
3656/// the essential reduction step. Therefore, based on the 4th
3657/// parameter, this function behaves slightly differently to
3658/// cooperate with the runtime to ensure correctness under
3659/// different circumstances.
3660///
3661/// 'InterWarpCpyFn' is a pointer to a function that transfers
3662/// reduced variables across warps. It tunnels, through CUDA
3663/// shared memory, the thread-private data of type 'ReduceData'
3664/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003665/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3666/// The last team writes the global reduced value to memory.
3667///
3668/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3669/// reduceData, shuffleReduceFn, interWarpCpyFn,
3670/// scratchpadCopyFn, loadAndReduceFn)
3671///
3672/// 'scratchpadCopyFn' is a helper that stores reduced
3673/// data from the team master to a scratchpad array in
3674/// global memory.
3675///
3676/// 'loadAndReduceFn' is a helper that loads data from
3677/// the scratchpad array and reduces it with the input
3678/// operand.
3679///
3680/// These compiler generated functions hide address
3681/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003682/// 5. if ret == 1:
3683/// The team master of the last team stores the reduced
3684/// result to the globals in memory.
3685/// foo += reduceData.foo; bar *= reduceData.bar
3686///
3687///
3688/// Warp Reduction Algorithms
3689///
3690/// On the warp level, we have three algorithms implemented in the
3691/// OpenMP runtime depending on the number of active lanes:
3692///
3693/// Full Warp Reduction
3694///
3695/// The reduce algorithm within a warp where all lanes are active
3696/// is implemented in the runtime as follows:
3697///
3698/// full_warp_reduce(void *reduce_data,
3699/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3700/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3701/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3702/// }
3703///
3704/// The algorithm completes in log(2, WARPSIZE) steps.
3705///
3706/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3707/// not used therefore we save instructions by not retrieving lane_id
3708/// from the corresponding special registers. The 4th parameter, which
3709/// represents the version of the algorithm being used, is set to 0 to
3710/// signify full warp reduction.
3711///
3712/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3713///
3714/// #reduce_elem refers to an element in the local lane's data structure
3715/// #remote_elem is retrieved from a remote lane
3716/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3717/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3718///
3719/// Contiguous Partial Warp Reduction
3720///
3721/// This reduce algorithm is used within a warp where only the first
3722/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3723/// number of OpenMP threads in a parallel region is not a multiple of
3724/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3725///
3726/// void
3727/// contiguous_partial_reduce(void *reduce_data,
3728/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3729/// int size, int lane_id) {
3730/// int curr_size;
3731/// int offset;
3732/// curr_size = size;
3733/// mask = curr_size/2;
3734/// while (offset>0) {
3735/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3736/// curr_size = (curr_size+1)/2;
3737/// offset = curr_size/2;
3738/// }
3739/// }
3740///
3741/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3742///
3743/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3744/// if (lane_id < offset)
3745/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3746/// else
3747/// reduce_elem = remote_elem
3748///
3749/// This algorithm assumes that the data to be reduced are located in a
3750/// contiguous subset of lanes starting from the first. When there is
3751/// an odd number of active lanes, the data in the last lane is not
3752/// aggregated with any other lane's dat but is instead copied over.
3753///
3754/// Dispersed Partial Warp Reduction
3755///
3756/// This algorithm is used within a warp when any discontiguous subset of
3757/// lanes are active. It is used to implement the reduction operation
3758/// across lanes in an OpenMP simd region or in a nested parallel region.
3759///
3760/// void
3761/// dispersed_partial_reduce(void *reduce_data,
3762/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3763/// int size, remote_id;
3764/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3765/// do {
3766/// remote_id = next_active_lane_id_right_after_me();
3767/// # the above function returns 0 of no active lane
3768/// # is present right after the current lane.
3769/// size = number_of_active_lanes_in_this_warp();
3770/// logical_lane_id /= 2;
3771/// ShuffleReduceFn(reduce_data, logical_lane_id,
3772/// remote_id-1-threadIdx.x, 2);
3773/// } while (logical_lane_id % 2 == 0 && size > 1);
3774/// }
3775///
3776/// There is no assumption made about the initial state of the reduction.
3777/// Any number of lanes (>=1) could be active at any position. The reduction
3778/// result is returned in the first active lane.
3779///
3780/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3781///
3782/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3783/// if (lane_id % 2 == 0 && offset > 0)
3784/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3785/// else
3786/// reduce_elem = remote_elem
3787///
3788///
3789/// Intra-Team Reduction
3790///
3791/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00003792/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003793/// threads in a team. It first reduces within a warp using the
3794/// aforementioned algorithms. We then proceed to gather all such
3795/// reduced values at the first warp.
3796///
3797/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3798/// data from each of the "warp master" (zeroth lane of each warp, where
3799/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3800/// a mathematical sense) the problem of reduction across warp masters in
3801/// a block to the problem of warp reduction.
3802///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003803///
3804/// Inter-Team Reduction
3805///
3806/// Once a team has reduced its data to a single value, it is stored in
3807/// a global scratchpad array. Since each team has a distinct slot, this
3808/// can be done without locking.
3809///
3810/// The last team to write to the scratchpad array proceeds to reduce the
3811/// scratchpad array. One or more workers in the last team use the helper
3812/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3813/// the k'th worker reduces every k'th element.
3814///
Alexey Bataev8e009032019-01-04 17:25:09 +00003815/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003816/// reduce across workers and compute a globally reduced value.
3817///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003818void CGOpenMPRuntimeNVPTX::emitReduction(
3819 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3820 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3821 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3822 if (!CGF.HaveInsertPoint())
3823 return;
3824
3825 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003826#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003827 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003828#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003829
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003830 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003831 assert(!TeamsReduction && !ParallelReduction &&
3832 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003833 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3834 ReductionOps, Options);
3835 return;
3836 }
3837
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003838 assert((TeamsReduction || ParallelReduction) &&
3839 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003840
Alexey Bataeva1166022018-11-27 21:24:54 +00003841 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003842 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003843 // or
3844 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00003845 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003846 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003847
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003848 llvm::Value *Res;
3849 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003850 ASTContext &C = CGM.getContext();
3851 // 1. Build a list of reduction variables.
3852 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3853 auto Size = RHSExprs.size();
3854 for (const Expr *E : Privates) {
3855 if (E->getType()->isVariablyModifiedType())
3856 // Reserve place for array size.
3857 ++Size;
3858 }
3859 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3860 QualType ReductionArrayTy =
3861 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3862 /*IndexTypeQuals=*/0);
3863 Address ReductionList =
3864 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3865 auto IPriv = Privates.begin();
3866 unsigned Idx = 0;
3867 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3868 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3869 CGF.getPointerSize());
3870 CGF.Builder.CreateStore(
3871 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3872 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3873 Elem);
3874 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3875 // Store array size.
3876 ++Idx;
3877 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3878 CGF.getPointerSize());
3879 llvm::Value *Size = CGF.Builder.CreateIntCast(
3880 CGF.getVLASize(
3881 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3882 .NumElts,
3883 CGF.SizeTy, /*isSigned=*/false);
3884 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3885 Elem);
3886 }
3887 }
3888
3889 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3890 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3891 ReductionList.getPointer(), CGF.VoidPtrTy);
James Y Knight9871db02019-02-05 16:42:33 +00003892 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataeva1166022018-11-27 21:24:54 +00003893 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3894 Privates, LHSExprs, RHSExprs, ReductionOps);
James Y Knight9871db02019-02-05 16:42:33 +00003895 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataeva1166022018-11-27 21:24:54 +00003896 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3897 llvm::Value *InterWarpCopyFn =
3898 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3899
Alexey Bataev8e009032019-01-04 17:25:09 +00003900 llvm::Value *Args[] = {RTLoc,
3901 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003902 CGF.Builder.getInt32(RHSExprs.size()),
3903 ReductionArrayTySize,
3904 RL,
3905 ShuffleAndReduceFn,
3906 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003907
Alexey Bataev8e009032019-01-04 17:25:09 +00003908 Res = CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
3909 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2),
3910 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003911 } else {
3912 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003913 std::string Name = getName({"reduction"});
3914 llvm::Value *Lock = getCriticalRegionLock(Name);
3915 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003916 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003917 createNVPTXRuntimeFunction(
3918 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003919 Args);
3920 }
3921
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003922 // 5. Build if (res == 1)
3923 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3924 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3925 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3926 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3927 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003928
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003929 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003930 // thread in each team.
3931 // __kmpc_end_reduce{_nowait}(<gtid>);
3932 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003933 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003934
3935 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003936 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003937 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3938 auto IPriv = Privates.begin();
3939 auto ILHS = LHSExprs.begin();
3940 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003941 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003942 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3943 cast<DeclRefExpr>(*IRHS));
3944 ++IPriv;
3945 ++ILHS;
3946 ++IRHS;
3947 }
3948 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003949 if (ParallelReduction) {
3950 llvm::Value *EndArgs[] = {ThreadId};
3951 RegionCodeGenTy RCG(CodeGen);
3952 NVPTXActionTy Action(
3953 nullptr, llvm::None,
3954 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3955 EndArgs);
3956 RCG.setAction(Action);
3957 RCG(CGF);
3958 } else {
3959 assert(TeamsReduction && "expected teams reduction.");
3960 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3961 std::string Name = getName({"reduction"});
3962 llvm::Value *Lock = getCriticalRegionLock(Name);
3963 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3964 RegionCodeGenTy RCG(CodeGen);
3965 NVPTXActionTy Action(
3966 nullptr, llvm::None,
3967 createNVPTXRuntimeFunction(
3968 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3969 EndArgs);
3970 RCG.setAction(Action);
3971 RCG(CGF);
3972 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003973 // There is no need to emit line number for unconditional branch.
3974 (void)ApplyDebugLocation::CreateEmpty(CGF);
3975 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003976}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003977
3978const VarDecl *
3979CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3980 const VarDecl *NativeParam) const {
3981 if (!NativeParam->getType()->isReferenceType())
3982 return NativeParam;
3983 QualType ArgType = NativeParam->getType();
3984 QualifierCollector QC;
3985 const Type *NonQualTy = QC.strip(ArgType);
3986 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3987 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3988 if (Attr->getCaptureKind() == OMPC_map) {
3989 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3990 LangAS::opencl_global);
3991 }
3992 }
3993 ArgType = CGM.getContext().getPointerType(PointeeTy);
3994 QC.addRestrict();
3995 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003996 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003997 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003998 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003999 return ImplicitParamDecl::Create(
4000 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4001 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004002 return ParmVarDecl::Create(
4003 CGM.getContext(),
4004 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004005 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004006 NativeParam->getIdentifier(), ArgType,
4007 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004008}
4009
4010Address
4011CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4012 const VarDecl *NativeParam,
4013 const VarDecl *TargetParam) const {
4014 assert(NativeParam != TargetParam &&
4015 NativeParam->getType()->isReferenceType() &&
4016 "Native arg must not be the same as target arg.");
4017 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4018 QualType NativeParamType = NativeParam->getType();
4019 QualifierCollector QC;
4020 const Type *NonQualTy = QC.strip(NativeParamType);
4021 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4022 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004023 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004024 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004025 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004026 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004027 // First cast to generic.
4028 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4029 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4030 /*AddrSpace=*/0));
4031 // Cast from generic to native address space.
4032 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4033 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4034 NativePointeeAddrSpace));
4035 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4036 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004037 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004038 return NativeParamAddr;
4039}
4040
4041void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004042 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004043 ArrayRef<llvm::Value *> Args) const {
4044 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004045 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004046 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004047 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004048 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4049 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4050 break;
4051 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004052 llvm::Type *TargetType = FnType->getParamType(I);
4053 llvm::Value *NativeArg = Args[I];
4054 if (!TargetType->isPointerTy()) {
4055 TargetArgs.emplace_back(NativeArg);
4056 continue;
4057 }
4058 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004059 NativeArg,
4060 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004061 TargetArgs.emplace_back(
4062 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4063 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004064 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004065}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004066
4067/// Emit function which wraps the outline parallel region
4068/// and controls the arguments which are passed to this function.
4069/// The wrapper ensures that the outlined function is called
4070/// with the correct arguments when data is shared.
4071llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4072 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4073 ASTContext &Ctx = CGM.getContext();
4074 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4075
4076 // Create a function that takes as argument the source thread.
4077 FunctionArgList WrapperArgs;
4078 QualType Int16QTy =
4079 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4080 QualType Int32QTy =
4081 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004082 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004083 /*Id=*/nullptr, Int16QTy,
4084 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004086 /*Id=*/nullptr, Int32QTy,
4087 ImplicitParamDecl::Other);
4088 WrapperArgs.emplace_back(&ParallelLevelArg);
4089 WrapperArgs.emplace_back(&WrapperArg);
4090
Alexey Bataev9ff80832018-04-16 20:16:21 +00004091 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004092 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4093
4094 auto *Fn = llvm::Function::Create(
4095 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004096 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004097 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004098 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004099 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004100
4101 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4102 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004103 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004104
4105 const auto *RD = CS.getCapturedRecordDecl();
4106 auto CurField = RD->field_begin();
4107
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004108 Address ZeroAddr = CGF.CreateMemTemp(
4109 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4110 /*Name*/ ".zero.addr");
4111 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004112 // Get the array of arguments.
4113 SmallVector<llvm::Value *, 8> Args;
4114
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004115 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4116 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004117
4118 CGBuilderTy &Bld = CGF.Builder;
4119 auto CI = CS.capture_begin();
4120
4121 // Use global memory for data sharing.
4122 // Handle passing of global args to workers.
4123 Address GlobalArgs =
4124 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4125 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4126 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4127 CGF.EmitRuntimeCall(
4128 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4129 DataSharingArgs);
4130
4131 // Retrieve the shared variables from the list of references returned
4132 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004133 Address SharedArgListAddress = Address::invalid();
4134 if (CS.capture_size() > 0 ||
4135 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4136 SharedArgListAddress = CGF.EmitLoadOfPointer(
4137 GlobalArgs, CGF.getContext()
4138 .getPointerType(CGF.getContext().getPointerType(
4139 CGF.getContext().VoidPtrTy))
4140 .castAs<PointerType>());
4141 }
4142 unsigned Idx = 0;
4143 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4144 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4145 CGF.getPointerSize());
4146 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4147 Src, CGF.SizeTy->getPointerTo());
4148 llvm::Value *LB = CGF.EmitLoadOfScalar(
4149 TypedAddress,
4150 /*Volatile=*/false,
4151 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4152 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4153 Args.emplace_back(LB);
4154 ++Idx;
4155 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4156 CGF.getPointerSize());
4157 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4158 Src, CGF.SizeTy->getPointerTo());
4159 llvm::Value *UB = CGF.EmitLoadOfScalar(
4160 TypedAddress,
4161 /*Volatile=*/false,
4162 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4163 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4164 Args.emplace_back(UB);
4165 ++Idx;
4166 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004167 if (CS.capture_size() > 0) {
4168 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004169 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4170 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004171 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4172 CGF.getPointerSize());
4173 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004174 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4175 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4176 /*Volatile=*/false,
4177 CGFContext.getPointerType(ElemTy),
4178 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004179 if (CI->capturesVariableByCopy() &&
4180 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004181 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4182 CI->getLocation());
4183 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004184 Args.emplace_back(Arg);
4185 }
4186 }
4187
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004188 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004189 CGF.FinishFunction();
4190 return Fn;
4191}
4192
4193void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4194 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004195 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4196 return;
4197
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004198 assert(D && "Expected function or captured|block decl.");
4199 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4200 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004201 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4202 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004203 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004204 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004205 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4206 Body = FD->getBody();
4207 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4208 Body = BD->getBody();
4209 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4210 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004211 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004212 if (NeedToDelayGlobalization &&
4213 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4214 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004215 }
4216 if (!Body)
4217 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004218 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004219 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004220 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004221 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004222 TeamAndReductions.first = nullptr;
4223 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004224 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4225 VarChecker.getEscapedVariableLengthDecls();
4226 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004227 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004228 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4229 I->getSecond().MappedParams =
4230 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4231 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4232 I->getSecond().EscapedParameters.insert(
4233 VarChecker.getEscapedParameters().begin(),
4234 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004235 I->getSecond().EscapedVariableLengthDecls.append(
4236 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004237 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004238 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004239 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004240 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004241 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004242 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004243 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004244 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004245 VarChecker.Visit(Body);
4246 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004247 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004248 I->getSecond().SecondaryLocalVarData.emplace();
4249 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4250 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4251 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4252 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004253 Data.insert(
4254 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004255 }
4256 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004257 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004258 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004259 struct GlobalizationScope final : EHScopeStack::Cleanup {
4260 GlobalizationScope() = default;
4261
4262 void Emit(CodeGenFunction &CGF, Flags flags) override {
4263 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004264 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004265 }
4266 };
4267 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004268 }
4269}
4270
4271Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4272 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004273 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4274 return Address::invalid();
4275
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004276 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004277 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4278 if (I == FunctionGlobalizedDecls.end())
4279 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004280 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004281 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004282 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004283 if (VD->hasAttrs()) {
4284 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4285 E(VD->attr_end());
4286 IT != E; ++IT) {
4287 auto VDI = I->getSecond().LocalVarData.find(
4288 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4289 ->getCanonicalDecl());
4290 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004291 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004292 }
4293 }
4294 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004295}
4296
4297void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004298 FunctionGlobalizedDecls.erase(CGF.CurFn);
4299 CGOpenMPRuntime::functionFinished(CGF);
4300}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004301
4302void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4303 CodeGenFunction &CGF, const OMPLoopDirective &S,
4304 OpenMPDistScheduleClauseKind &ScheduleKind,
4305 llvm::Value *&Chunk) const {
4306 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4307 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4308 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4309 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4310 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004311 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004312 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004313 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4314 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004315}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004316
4317void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4318 CodeGenFunction &CGF, const OMPLoopDirective &S,
4319 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004320 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004321 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004322 // Chunk size is 1 in this case.
4323 llvm::APInt ChunkSize(32, 1);
4324 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4325 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4326 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004327}
Alexey Bataev60705422018-10-30 15:50:12 +00004328
4329void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4330 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4331 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4332 " Expected target-based directive.");
4333 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4334 for (const CapturedStmt::Capture &C : CS->captures()) {
4335 // Capture variables captured by reference in lambdas for target-based
4336 // directives.
4337 if (!C.capturesVariable())
4338 continue;
4339 const VarDecl *VD = C.getCapturedVar();
4340 const auto *RD = VD->getType()
4341 .getCanonicalType()
4342 .getNonReferenceType()
4343 ->getAsCXXRecordDecl();
4344 if (!RD || !RD->isLambda())
4345 continue;
4346 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4347 LValue VDLVal;
4348 if (VD->getType().getCanonicalType()->isReferenceType())
4349 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4350 else
4351 VDLVal = CGF.MakeAddrLValue(
4352 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4353 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4354 FieldDecl *ThisCapture = nullptr;
4355 RD->getCaptureFields(Captures, ThisCapture);
4356 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4357 LValue ThisLVal =
4358 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4359 llvm::Value *CXXThis = CGF.LoadCXXThis();
4360 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4361 }
4362 for (const LambdaCapture &LC : RD->captures()) {
4363 if (LC.getCaptureKind() != LCK_ByRef)
4364 continue;
4365 const VarDecl *VD = LC.getCapturedVar();
4366 if (!CS->capturesVariable(VD))
4367 continue;
4368 auto It = Captures.find(VD);
4369 assert(It != Captures.end() && "Found lambda capture without field.");
4370 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4371 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4372 if (VD->getType().getCanonicalType()->isReferenceType())
4373 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4374 VD->getType().getCanonicalType())
4375 .getAddress();
4376 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4377 }
4378 }
4379}
4380
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004381// Get current CudaArch and ignore any unknown values
4382static CudaArch getCudaArch(CodeGenModule &CGM) {
4383 if (!CGM.getTarget().hasFeature("ptx"))
4384 return CudaArch::UNKNOWN;
4385 llvm::StringMap<bool> Features;
4386 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4387 CGM.getTarget().getTargetOpts().CPU,
4388 CGM.getTarget().getTargetOpts().Features);
4389 for (const auto &Feature : Features) {
4390 if (Feature.getValue()) {
4391 CudaArch Arch = StringToCudaArch(Feature.getKey());
4392 if (Arch != CudaArch::UNKNOWN)
4393 return Arch;
4394 }
4395 }
4396 return CudaArch::UNKNOWN;
4397}
4398
4399/// Check to see if target architecture supports unified addressing which is
4400/// a restriction for OpenMP requires clause "unified_shared_memory".
4401void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4402 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4403 for (const OMPClause *Clause : D->clauselists()) {
4404 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4405 switch (getCudaArch(CGM)) {
4406 case CudaArch::SM_20:
4407 case CudaArch::SM_21:
4408 case CudaArch::SM_30:
4409 case CudaArch::SM_32:
4410 case CudaArch::SM_35:
4411 case CudaArch::SM_37:
4412 case CudaArch::SM_50:
4413 case CudaArch::SM_52:
4414 case CudaArch::SM_53:
4415 case CudaArch::SM_60:
4416 case CudaArch::SM_61:
4417 case CudaArch::SM_62:
4418 CGM.Error(Clause->getBeginLoc(),
4419 "Target architecture does not support unified addressing");
4420 return;
4421 case CudaArch::SM_70:
4422 case CudaArch::SM_72:
4423 case CudaArch::SM_75:
4424 case CudaArch::GFX600:
4425 case CudaArch::GFX601:
4426 case CudaArch::GFX700:
4427 case CudaArch::GFX701:
4428 case CudaArch::GFX702:
4429 case CudaArch::GFX703:
4430 case CudaArch::GFX704:
4431 case CudaArch::GFX801:
4432 case CudaArch::GFX802:
4433 case CudaArch::GFX803:
4434 case CudaArch::GFX810:
4435 case CudaArch::GFX900:
4436 case CudaArch::GFX902:
4437 case CudaArch::GFX904:
4438 case CudaArch::GFX906:
4439 case CudaArch::GFX909:
4440 case CudaArch::UNKNOWN:
4441 break;
4442 case CudaArch::LAST:
4443 llvm_unreachable("Unexpected Cuda arch.");
4444 }
4445 }
4446 }
4447}
4448
Alexey Bataeve4090182018-11-02 14:54:07 +00004449/// Get number of SMs and number of blocks per SM.
4450static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4451 std::pair<unsigned, unsigned> Data;
4452 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4453 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4454 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4455 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4456 if (Data.first && Data.second)
4457 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004458 switch (getCudaArch(CGM)) {
4459 case CudaArch::SM_20:
4460 case CudaArch::SM_21:
4461 case CudaArch::SM_30:
4462 case CudaArch::SM_32:
4463 case CudaArch::SM_35:
4464 case CudaArch::SM_37:
4465 case CudaArch::SM_50:
4466 case CudaArch::SM_52:
4467 case CudaArch::SM_53:
4468 return {16, 16};
4469 case CudaArch::SM_60:
4470 case CudaArch::SM_61:
4471 case CudaArch::SM_62:
4472 return {56, 32};
4473 case CudaArch::SM_70:
4474 case CudaArch::SM_72:
4475 case CudaArch::SM_75:
4476 return {84, 32};
4477 case CudaArch::GFX600:
4478 case CudaArch::GFX601:
4479 case CudaArch::GFX700:
4480 case CudaArch::GFX701:
4481 case CudaArch::GFX702:
4482 case CudaArch::GFX703:
4483 case CudaArch::GFX704:
4484 case CudaArch::GFX801:
4485 case CudaArch::GFX802:
4486 case CudaArch::GFX803:
4487 case CudaArch::GFX810:
4488 case CudaArch::GFX900:
4489 case CudaArch::GFX902:
4490 case CudaArch::GFX904:
4491 case CudaArch::GFX906:
4492 case CudaArch::GFX909:
4493 case CudaArch::UNKNOWN:
4494 break;
4495 case CudaArch::LAST:
4496 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004497 }
4498 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4499}
4500
4501void CGOpenMPRuntimeNVPTX::clear() {
Alexey Bataeve4e9ba22019-01-28 20:03:02 +00004502 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
4503 if (CGM.getCodeGenOpts().getDebugInfo() >=
4504 codegenoptions::LimitedDebugInfo) {
4505 ASTContext &C = CGM.getContext();
4506 auto *VD = VarDecl::Create(
4507 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
4508 &C.Idents.get("_$_"), C.IntTy, /*TInfo=*/nullptr, SC_Static);
4509 auto *Var = cast<llvm::GlobalVariable>(
4510 CGM.CreateRuntimeVariable(CGM.IntTy, "_$_"));
4511 Var->setInitializer(llvm::ConstantInt::getNullValue(CGM.IntTy));
4512 Var->setLinkage(llvm::GlobalVariable::CommonLinkage);
4513 CGM.addCompilerUsedGlobal(Var);
4514 DI->EmitGlobalVariable(Var, VD);
4515 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004516 if (!GlobalizedRecords.empty()) {
4517 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004518 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4519 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004520 RecordDecl *StaticRD = C.buildImplicitRecord(
4521 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4522 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004523 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4524 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4525 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004526 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4527 if (Records.Records.empty())
4528 continue;
4529 unsigned Size = 0;
4530 unsigned RecAlignment = 0;
4531 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004532 QualType RDTy = C.getRecordType(RD);
4533 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004534 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004535 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004536 Size =
4537 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4538 }
4539 Size = llvm::alignTo(Size, RecAlignment);
4540 llvm::APInt ArySize(/*numBits=*/64, Size);
4541 QualType SubTy = C.getConstantArrayType(
4542 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004543 const bool UseSharedMemory = Size <= SharedMemorySize;
4544 auto *Field =
4545 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4546 SourceLocation(), SourceLocation(), nullptr, SubTy,
4547 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4548 /*BW=*/nullptr, /*Mutable=*/false,
4549 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004550 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004551 if (UseSharedMemory) {
4552 SharedStaticRD->addDecl(Field);
4553 SharedRecs.push_back(&Records);
4554 } else {
4555 StaticRD->addDecl(Field);
4556 GlobalRecs.push_back(&Records);
4557 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004558 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004559 Records.UseSharedMemory->setInitializer(
4560 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4561 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004562 // Allocate SharedMemorySize buffer for the shared memory.
4563 // FIXME: nvlink does not handle weak linkage correctly (object with the
4564 // different size are reported as erroneous).
4565 // Restore this code as sson as nvlink is fixed.
4566 if (!SharedStaticRD->field_empty()) {
4567 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4568 QualType SubTy = C.getConstantArrayType(
4569 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4570 auto *Field = FieldDecl::Create(
4571 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4572 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4573 /*BW=*/nullptr, /*Mutable=*/false,
4574 /*InitStyle=*/ICIS_NoInit);
4575 Field->setAccess(AS_public);
4576 SharedStaticRD->addDecl(Field);
4577 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004578 SharedStaticRD->completeDefinition();
4579 if (!SharedStaticRD->field_empty()) {
4580 QualType StaticTy = C.getRecordType(SharedStaticRD);
4581 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4582 auto *GV = new llvm::GlobalVariable(
4583 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004584 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004585 llvm::Constant::getNullValue(LLVMStaticTy),
4586 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4587 llvm::GlobalValue::NotThreadLocal,
4588 C.getTargetAddressSpace(LangAS::cuda_shared));
4589 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4590 GV, CGM.VoidPtrTy);
4591 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4592 Rec->Buffer->replaceAllUsesWith(Replacement);
4593 Rec->Buffer->eraseFromParent();
4594 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004595 }
4596 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004597 if (!StaticRD->field_empty()) {
4598 QualType StaticTy = C.getRecordType(StaticRD);
4599 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4600 llvm::APInt Size1(32, SMsBlockPerSM.second);
4601 QualType Arr1Ty =
4602 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4603 /*IndexTypeQuals=*/0);
4604 llvm::APInt Size2(32, SMsBlockPerSM.first);
4605 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4606 /*IndexTypeQuals=*/0);
4607 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4608 auto *GV = new llvm::GlobalVariable(
4609 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004610 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004611 llvm::Constant::getNullValue(LLVMArr2Ty),
4612 "_openmp_static_glob_rd_$_");
4613 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4614 GV, CGM.VoidPtrTy);
4615 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4616 Rec->Buffer->replaceAllUsesWith(Replacement);
4617 Rec->Buffer->eraseFromParent();
4618 }
4619 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004620 }
4621 CGOpenMPRuntime::clear();
4622}