blob: 5f7122e4e8f8c3a7c34e14ddc19bd89aaf0d9453 [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000020#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000021#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000022
23using namespace clang;
24using namespace CodeGen;
25
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000026namespace {
27enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000028 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000029 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000030 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000031 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000032 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000033 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000034 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000035 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000036 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
37 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000039 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000040 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000043 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000044 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000046 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
47 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_serialized_parallel,
50 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
51 /// global_tid);
52 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000053 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000054 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000057 /// int16_t lane_offset, int16_t warp_size);
58 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000059 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000060 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
61 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
62 /// lane_offset, int16_t shortCircuit),
63 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
64 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Alexey Bataeva1166022018-11-27 21:24:54 +000065 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
66 /// global_tid, kmp_critical_name *lck)
67 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
68 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
69 /// kmp_int32 global_tid, kmp_critical_name *lck)
70 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000072 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000074 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000075 /// Call to void __kmpc_data_sharing_init_stack_spmd();
76 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000077 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000078 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000079 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// size_t n_args);
84 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000089 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
90 /// global_tid);
91 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000092 /// Call to int8_t __kmpc_is_spmd_exec_mode();
93 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataeve4090182018-11-02 14:54:07 +000094 /// Call to void __kmpc_get_team_static_memory(const void *buf, size_t size,
95 /// int16_t is_shared, const void **res);
96 OMPRTL_NVPTX__kmpc_get_team_static_memory,
97 /// Call to void __kmpc_restore_team_static_memory(int16_t is_shared);
98 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataevc3028ca2018-12-04 15:03:25 +000099 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
100 OMPRTL__kmpc_barrier,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000101};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102
103/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
104class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 llvm::BasicBlock *ContBlock = nullptr;
111
112public:
113 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
114 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
115 bool Conditional = false)
116 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
117 ExitArgs(ExitArgs), Conditional(Conditional) {}
118 void Enter(CodeGenFunction &CGF) override {
119 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
120 if (Conditional) {
121 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
122 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
123 ContBlock = CGF.createBasicBlock("omp_if.end");
124 // Generate the branch (If-stmt)
125 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
126 CGF.EmitBlock(ThenBlock);
127 }
128 }
129 void Done(CodeGenFunction &CGF) {
130 // Emit the rest of blocks/branches
131 CGF.EmitBranch(ContBlock);
132 CGF.EmitBlock(ContBlock, true);
133 }
134 void Exit(CodeGenFunction &CGF) override {
135 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
136 }
137};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000138
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000139/// A class to track the execution mode when codegening directives within
140/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
141/// to the target region and used by containing directives such as 'parallel'
142/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000143class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000144private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000145 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
146 CGOpenMPRuntimeNVPTX::EM_Unknown;
147 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
148 bool SavedRuntimeMode = false;
149 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000150
151public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000152 /// Constructor for Non-SPMD mode.
153 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
154 : ExecMode(ExecMode) {
155 SavedExecMode = ExecMode;
156 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000157 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000158 /// Constructor for SPMD mode.
159 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
160 bool &RuntimeMode, bool FullRuntimeMode)
161 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
162 SavedExecMode = ExecMode;
163 SavedRuntimeMode = RuntimeMode;
164 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
165 RuntimeMode = FullRuntimeMode;
166 }
167 ~ExecutionRuntimeModesRAII() {
168 ExecMode = SavedExecMode;
169 if (RuntimeMode)
170 *RuntimeMode = SavedRuntimeMode;
171 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000172};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000173
174/// GPU Configuration: This information can be derived from cuda registers,
175/// however, providing compile time constants helps generate more efficient
176/// code. For all practical purposes this is fine because the configuration
177/// is the same for all known NVPTX architectures.
178enum MachineConfiguration : unsigned {
179 WarpSize = 32,
180 /// Number of bits required to represent a lane identifier, which is
181 /// computed as log_2(WarpSize).
182 LaneIDBits = 5,
183 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000184
185 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000186 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000187
188 /// Maximal size of the shared memory buffer.
189 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000190};
191
192enum NamedBarrier : unsigned {
193 /// Synchronize on this barrier #ID using a named barrier primitive.
194 /// Only the subset of active threads in a parallel region arrive at the
195 /// barrier.
196 NB_Parallel = 1,
197};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000198
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000199static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
200 RefExpr = RefExpr->IgnoreParens();
201 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
202 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
203 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
204 Base = TempASE->getBase()->IgnoreParenImpCasts();
205 RefExpr = Base;
206 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
207 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
208 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
209 Base = TempOASE->getBase()->IgnoreParenImpCasts();
210 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
211 Base = TempASE->getBase()->IgnoreParenImpCasts();
212 RefExpr = Base;
213 }
214 RefExpr = RefExpr->IgnoreParenImpCasts();
215 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
216 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
217 const auto *ME = cast<MemberExpr>(RefExpr);
218 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
219}
220
Alexey Bataev2adecff2018-09-21 14:22:53 +0000221typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
222static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
223 return P1.first > P2.first;
224}
225
226static RecordDecl *buildRecordForGlobalizedVars(
227 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000228 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000229 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
230 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 return nullptr;
233 SmallVector<VarsDataTy, 4> GlobalizedVars;
234 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 GlobalizedVars.emplace_back(
236 CharUnits::fromQuantity(std::max(
237 C.getDeclAlign(D).getQuantity(),
238 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
239 D);
240 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000241 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
242 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
243 stable_sort_comparator);
244 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000245 // /* globalized vars */[WarSize] align (max(decl_align,
246 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000247 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000248 // };
249 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
250 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000251 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
252 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000253 for (const auto &Pair : GlobalizedVars) {
254 const ValueDecl *VD = Pair.second;
255 QualType Type = VD->getType();
256 if (Type->isLValueReferenceType())
257 Type = C.getPointerType(Type.getNonReferenceType());
258 else
259 Type = Type.getNonReferenceType();
260 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000261 FieldDecl *Field;
262 if (SingleEscaped.count(VD)) {
263 Field = FieldDecl::Create(
264 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
265 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
266 /*BW=*/nullptr, /*Mutable=*/false,
267 /*InitStyle=*/ICIS_NoInit);
268 Field->setAccess(AS_public);
269 if (VD->hasAttrs()) {
270 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
271 E(VD->getAttrs().end());
272 I != E; ++I)
273 Field->addAttr(*I);
274 }
275 } else {
276 llvm::APInt ArraySize(32, WarpSize);
277 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
278 Field = FieldDecl::Create(
279 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
280 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
281 /*BW=*/nullptr, /*Mutable=*/false,
282 /*InitStyle=*/ICIS_NoInit);
283 Field->setAccess(AS_public);
284 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
285 static_cast<CharUnits::QuantityType>(
286 GlobalMemoryAlignment)));
287 Field->addAttr(AlignedAttr::CreateImplicit(
288 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
289 IntegerLiteral::Create(C, Align,
290 C.getIntTypeForBitwidth(32, /*Signed=*/0),
291 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000292 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000293 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000294 MappedDeclsFields.try_emplace(VD, Field);
295 }
296 GlobalizedRD->completeDefinition();
297 return GlobalizedRD;
298}
299
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000300/// Get the list of variables that can escape their declaration context.
301class CheckVarsEscapingDeclContext final
302 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
303 CodeGenFunction &CGF;
304 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000305 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000306 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307 RecordDecl *GlobalizedRD = nullptr;
308 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000309 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000310 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000311
312 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000313 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000314 if (!isa<VarDecl>(VD) ||
315 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000316 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000317 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000318 // Variables captured by value must be globalized.
319 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000320 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000321 // Check if need to capture the variable that was already captured by
322 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000323 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000324 if (!FD->hasAttrs())
325 return;
326 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
327 if (!Attr)
328 return;
329 if (!isOpenMPPrivate(
330 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
331 Attr->getCaptureKind() == OMPC_map)
332 return;
333 }
334 if (!FD->getType()->isReferenceType()) {
335 assert(!VD->getType()->isVariablyModifiedType() &&
336 "Parameter captured by value with variably modified type");
337 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000338 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000339 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000341 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000342 }
343 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000344 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000345 VD->getType()->isReferenceType())
346 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000347 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000348 if (VD->getType()->isVariablyModifiedType())
349 EscapedVariableLengthDecls.insert(VD);
350 else
351 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000352 }
353
354 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000356 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000357 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
358 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
359 const bool SavedAllEscaped = AllEscaped;
360 AllEscaped = VD->getType()->isLValueReferenceType();
361 Visit(VarD->getInit());
362 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000363 }
364 }
365 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000366 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
367 ArrayRef<OMPClause *> Clauses,
368 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000369 if (!S)
370 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000371 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000372 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
373 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000374 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
375 if (IsCombinedParallelRegion) {
376 // Check if the variable is privatized in the combined construct and
377 // those private copies must be shared in the inner parallel
378 // directive.
379 IsForCombinedParallelRegion = false;
380 for (const OMPClause *C : Clauses) {
381 if (!isOpenMPPrivate(C->getClauseKind()) ||
382 C->getClauseKind() == OMPC_reduction ||
383 C->getClauseKind() == OMPC_linear ||
384 C->getClauseKind() == OMPC_private)
385 continue;
386 ArrayRef<const Expr *> Vars;
387 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
388 Vars = PC->getVarRefs();
389 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
390 Vars = PC->getVarRefs();
391 else
392 llvm_unreachable("Unexpected clause.");
393 for (const auto *E : Vars) {
394 const Decl *D =
395 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
396 if (D == VD->getCanonicalDecl()) {
397 IsForCombinedParallelRegion = true;
398 break;
399 }
400 }
401 if (IsForCombinedParallelRegion)
402 break;
403 }
404 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000405 markAsEscaped(VD);
406 if (isa<OMPCapturedExprDecl>(VD))
407 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000408 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000409 }
410 }
411 }
412
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000413 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000414 assert(!GlobalizedRD &&
415 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000416 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000417 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000418 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
419 else
420 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000421 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000422 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000423 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000424 }
425
426public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000427 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
428 ArrayRef<const ValueDecl *> TeamsReductions)
429 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
430 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 virtual ~CheckVarsEscapingDeclContext() = default;
432 void VisitDeclStmt(const DeclStmt *S) {
433 if (!S)
434 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000435 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
437 VisitValueDecl(VD);
438 }
439 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
440 if (!D)
441 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000442 if (!D->hasAssociatedStmt())
443 return;
444 if (const auto *S =
445 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
446 // Do not analyze directives that do not actually require capturing,
447 // like `omp for` or `omp simd` directives.
448 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
449 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
450 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
451 VisitStmt(S->getCapturedStmt());
452 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000453 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000454 VisitOpenMPCapturedStmt(
455 S, D->clauses(),
456 CaptureRegions.back() == OMPD_parallel &&
457 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000458 }
459 }
460 void VisitCapturedStmt(const CapturedStmt *S) {
461 if (!S)
462 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000463 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000464 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
465 const ValueDecl *VD = C.getCapturedVar();
466 markAsEscaped(VD);
467 if (isa<OMPCapturedExprDecl>(VD))
468 VisitValueDecl(VD);
469 }
470 }
471 }
472 void VisitLambdaExpr(const LambdaExpr *E) {
473 if (!E)
474 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000475 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000476 if (C.capturesVariable()) {
477 if (C.getCaptureKind() == LCK_ByRef) {
478 const ValueDecl *VD = C.getCapturedVar();
479 markAsEscaped(VD);
480 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
481 VisitValueDecl(VD);
482 }
483 }
484 }
485 }
486 void VisitBlockExpr(const BlockExpr *E) {
487 if (!E)
488 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000489 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000490 if (C.isByRef()) {
491 const VarDecl *VD = C.getVariable();
492 markAsEscaped(VD);
493 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
494 VisitValueDecl(VD);
495 }
496 }
497 }
498 void VisitCallExpr(const CallExpr *E) {
499 if (!E)
500 return;
501 for (const Expr *Arg : E->arguments()) {
502 if (!Arg)
503 continue;
504 if (Arg->isLValue()) {
505 const bool SavedAllEscaped = AllEscaped;
506 AllEscaped = true;
507 Visit(Arg);
508 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000509 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000511 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000512 }
513 Visit(E->getCallee());
514 }
515 void VisitDeclRefExpr(const DeclRefExpr *E) {
516 if (!E)
517 return;
518 const ValueDecl *VD = E->getDecl();
519 if (AllEscaped)
520 markAsEscaped(VD);
521 if (isa<OMPCapturedExprDecl>(VD))
522 VisitValueDecl(VD);
523 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
524 if (VarD->isInitCapture())
525 VisitValueDecl(VD);
526 }
527 void VisitUnaryOperator(const UnaryOperator *E) {
528 if (!E)
529 return;
530 if (E->getOpcode() == UO_AddrOf) {
531 const bool SavedAllEscaped = AllEscaped;
532 AllEscaped = true;
533 Visit(E->getSubExpr());
534 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000535 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000536 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000537 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000538 }
539 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
540 if (!E)
541 return;
542 if (E->getCastKind() == CK_ArrayToPointerDecay) {
543 const bool SavedAllEscaped = AllEscaped;
544 AllEscaped = true;
545 Visit(E->getSubExpr());
546 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000547 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000548 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000549 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000550 }
551 void VisitExpr(const Expr *E) {
552 if (!E)
553 return;
554 bool SavedAllEscaped = AllEscaped;
555 if (!E->isLValue())
556 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000557 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000558 if (Child)
559 Visit(Child);
560 AllEscaped = SavedAllEscaped;
561 }
562 void VisitStmt(const Stmt *S) {
563 if (!S)
564 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000565 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000566 if (Child)
567 Visit(Child);
568 }
569
Alexey Bataevc99042b2018-03-15 18:10:54 +0000570 /// Returns the record that handles all the escaped local variables and used
571 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000572 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000574 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000575 return GlobalizedRD;
576 }
577
Alexey Bataevc99042b2018-03-15 18:10:54 +0000578 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000579 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
580 assert(GlobalizedRD &&
581 "Record for globalized variables must be generated already.");
582 auto I = MappedDeclsFields.find(VD);
583 if (I == MappedDeclsFields.end())
584 return nullptr;
585 return I->getSecond();
586 }
587
Alexey Bataevc99042b2018-03-15 18:10:54 +0000588 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000589 ArrayRef<const ValueDecl *> getEscapedDecls() const {
590 return EscapedDecls.getArrayRef();
591 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000592
593 /// Checks if the escaped local variable is actually a parameter passed by
594 /// value.
595 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
596 return EscapedParameters;
597 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000598
599 /// Returns the list of the escaped variables with the variably modified
600 /// types.
601 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
602 return EscapedVariableLengthDecls.getArrayRef();
603 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000604};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000605} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000606
607/// Get the GPU warp size.
608static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000609 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000610 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000611 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000612 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613}
614
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000615/// Get the id of the current thread on the GPU.
616static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000619 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000621}
622
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000623/// Get the id of the warp in the block.
624/// We assume that the warp size is 32, which is always the case
625/// on the NVPTX device, to generate more efficient code.
626static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
627 CGBuilderTy &Bld = CGF.Builder;
628 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
629}
630
631/// Get the id of the current lane in the Warp.
632/// We assume that the warp size is 32, which is always the case
633/// on the NVPTX device, to generate more efficient code.
634static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
635 CGBuilderTy &Bld = CGF.Builder;
636 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
637 "nvptx_lane_id");
638}
639
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000640/// Get the maximum number of threads in a block of the GPU.
641static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000642 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000643 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000644 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000645 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000646}
647
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000648/// Get barrier to synchronize all threads in a block.
649static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000650 llvm::Function *F = llvm::Intrinsic::getDeclaration(
651 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0);
652 F->addFnAttr(llvm::Attribute::Convergent);
653 CGF.EmitRuntimeCall(F);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000654}
655
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000656/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
657/// a CTA.
658static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
659 llvm::Value *NumThreads) {
660 CGBuilderTy &Bld = CGF.Builder;
661 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000662 llvm::Function *F = llvm::Intrinsic::getDeclaration(
663 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier);
664 F->addFnAttr(llvm::Attribute::Convergent);
665 CGF.EmitRuntimeCall(F, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000666}
667
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000668/// Synchronize all GPU threads in a block.
669static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000670
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000671/// Synchronize worker threads in a parallel region.
672static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
673 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
674}
675
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000676/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000677/// For the 'generic' execution mode, the runtime encodes thread_limit in
678/// the launch parameters, always starting thread_limit+warpSize threads per
679/// CTA. The threads in the last warp are reserved for master execution.
680/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
681static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000682 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000683 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000684 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000685 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000686 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
687 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000688}
689
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000690/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691/// The master thread id is the first thread (lane) of the last warp in the
692/// GPU block. Warp size is assumed to be some power of 2.
693/// Thread id is 0 indexed.
694/// E.g: If NumThreads is 33, master id is 32.
695/// If NumThreads is 64, master id is 32.
696/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000697static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000698 CGBuilderTy &Bld = CGF.Builder;
699 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
700
701 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000702 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703
Alexey Bataeve290ec02018-04-06 16:03:36 +0000704 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000705 Bld.CreateNot(Mask), "master_tid");
706}
707
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000708CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000709 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000710 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
711 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000712 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000713}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000714
715void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
716 CodeGenModule &CGM) {
717 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000718
719 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000720 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000721 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000722 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000723 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000724}
725
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000726CGOpenMPRuntimeNVPTX::ExecutionMode
727CGOpenMPRuntimeNVPTX::getExecutionMode() const {
728 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000729}
730
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000731static CGOpenMPRuntimeNVPTX::DataSharingMode
732getDataSharingMode(CodeGenModule &CGM) {
733 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
734 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000735}
736
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000737// Checks if the expression is constant or does not have non-trivial function
738// calls.
739static bool isTrivial(ASTContext &Ctx, const Expr * E) {
740 // We can skip constant expressions.
741 // We can skip expressions with trivial calls or simple expressions.
742 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
743 !E->hasNonTrivialCall(Ctx)) &&
744 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
745}
746
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000747/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000748/// iff there is only one that is not evaluatable at the compile time.
749static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
750 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
751 const Stmt *Child = nullptr;
752 for (const Stmt *S : C->body()) {
753 if (const auto *E = dyn_cast<Expr>(S)) {
754 if (isTrivial(Ctx, E))
755 continue;
756 }
757 // Some of the statements can be ignored.
758 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
759 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
760 continue;
761 // Analyze declarations.
762 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
763 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
764 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
765 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
766 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
767 isa<UsingDirectiveDecl>(D) ||
768 isa<OMPDeclareReductionDecl>(D) ||
769 isa<OMPThreadPrivateDecl>(D))
770 return true;
771 const auto *VD = dyn_cast<VarDecl>(D);
772 if (!VD)
773 return false;
774 return VD->isConstexpr() ||
775 ((VD->getType().isTrivialType(Ctx) ||
776 VD->getType()->isReferenceType()) &&
777 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
778 }))
779 continue;
780 }
781 // Found multiple children - cannot get the one child only.
782 if (Child)
783 return Body;
784 Child = S;
785 }
786 if (Child)
787 return Child;
788 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000789 return Body;
790}
791
792/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000793/// false condition. Also, check if the number of threads is strictly specified
794/// and run those directives in non-SPMD mode.
795static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
796 const OMPExecutableDirective &D) {
797 if (D.hasClausesOfKind<OMPNumThreadsClause>())
798 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000799 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
800 OpenMPDirectiveKind NameModifier = C->getNameModifier();
801 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
802 continue;
803 const Expr *Cond = C->getCondition();
804 bool Result;
805 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
806 return true;
807 }
808 return false;
809}
810
811/// Check for inner (nested) SPMD construct, if any
812static bool hasNestedSPMDDirective(ASTContext &Ctx,
813 const OMPExecutableDirective &D) {
814 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000815 const auto *Body =
816 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000817 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818
819 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
820 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 switch (D.getDirectiveKind()) {
822 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000823 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000824 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000825 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000826 if (DKind == OMPD_teams) {
827 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
828 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000829 if (!Body)
830 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000831 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000832 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
833 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000834 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000835 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000836 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000837 }
838 }
839 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000840 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000841 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000842 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000843 case OMPD_target_simd:
844 case OMPD_target_parallel:
845 case OMPD_target_parallel_for:
846 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000847 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000848 case OMPD_target_teams_distribute_simd:
849 case OMPD_target_teams_distribute_parallel_for:
850 case OMPD_target_teams_distribute_parallel_for_simd:
851 case OMPD_parallel:
852 case OMPD_for:
853 case OMPD_parallel_for:
854 case OMPD_parallel_sections:
855 case OMPD_for_simd:
856 case OMPD_parallel_for_simd:
857 case OMPD_cancel:
858 case OMPD_cancellation_point:
859 case OMPD_ordered:
860 case OMPD_threadprivate:
861 case OMPD_task:
862 case OMPD_simd:
863 case OMPD_sections:
864 case OMPD_section:
865 case OMPD_single:
866 case OMPD_master:
867 case OMPD_critical:
868 case OMPD_taskyield:
869 case OMPD_barrier:
870 case OMPD_taskwait:
871 case OMPD_taskgroup:
872 case OMPD_atomic:
873 case OMPD_flush:
874 case OMPD_teams:
875 case OMPD_target_data:
876 case OMPD_target_exit_data:
877 case OMPD_target_enter_data:
878 case OMPD_distribute:
879 case OMPD_distribute_simd:
880 case OMPD_distribute_parallel_for:
881 case OMPD_distribute_parallel_for_simd:
882 case OMPD_teams_distribute:
883 case OMPD_teams_distribute_simd:
884 case OMPD_teams_distribute_parallel_for:
885 case OMPD_teams_distribute_parallel_for_simd:
886 case OMPD_target_update:
887 case OMPD_declare_simd:
888 case OMPD_declare_target:
889 case OMPD_end_declare_target:
890 case OMPD_declare_reduction:
891 case OMPD_taskloop:
892 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000893 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000894 case OMPD_unknown:
895 llvm_unreachable("Unexpected directive.");
896 }
897 }
898
899 return false;
900}
901
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000902static bool supportsSPMDExecutionMode(ASTContext &Ctx,
903 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000904 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
905 switch (DirectiveKind) {
906 case OMPD_target:
907 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000908 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000909 case OMPD_target_parallel:
910 case OMPD_target_parallel_for:
911 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000912 case OMPD_target_teams_distribute_parallel_for:
913 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000914 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000915 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000916 case OMPD_target_teams_distribute:
917 case OMPD_target_teams_distribute_simd:
918 return false;
919 case OMPD_parallel:
920 case OMPD_for:
921 case OMPD_parallel_for:
922 case OMPD_parallel_sections:
923 case OMPD_for_simd:
924 case OMPD_parallel_for_simd:
925 case OMPD_cancel:
926 case OMPD_cancellation_point:
927 case OMPD_ordered:
928 case OMPD_threadprivate:
929 case OMPD_task:
930 case OMPD_simd:
931 case OMPD_sections:
932 case OMPD_section:
933 case OMPD_single:
934 case OMPD_master:
935 case OMPD_critical:
936 case OMPD_taskyield:
937 case OMPD_barrier:
938 case OMPD_taskwait:
939 case OMPD_taskgroup:
940 case OMPD_atomic:
941 case OMPD_flush:
942 case OMPD_teams:
943 case OMPD_target_data:
944 case OMPD_target_exit_data:
945 case OMPD_target_enter_data:
946 case OMPD_distribute:
947 case OMPD_distribute_simd:
948 case OMPD_distribute_parallel_for:
949 case OMPD_distribute_parallel_for_simd:
950 case OMPD_teams_distribute:
951 case OMPD_teams_distribute_simd:
952 case OMPD_teams_distribute_parallel_for:
953 case OMPD_teams_distribute_parallel_for_simd:
954 case OMPD_target_update:
955 case OMPD_declare_simd:
956 case OMPD_declare_target:
957 case OMPD_end_declare_target:
958 case OMPD_declare_reduction:
959 case OMPD_taskloop:
960 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000961 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000962 case OMPD_unknown:
963 break;
964 }
965 llvm_unreachable(
966 "Unknown programming model for OpenMP directive on NVPTX target.");
967}
968
969/// Check if the directive is loops based and has schedule clause at all or has
970/// static scheduling.
971static bool hasStaticScheduling(const OMPExecutableDirective &D) {
972 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
973 isOpenMPLoopDirective(D.getDirectiveKind()) &&
974 "Expected loop-based directive.");
975 return !D.hasClausesOfKind<OMPOrderedClause>() &&
976 (!D.hasClausesOfKind<OMPScheduleClause>() ||
977 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
978 [](const OMPScheduleClause *C) {
979 return C->getScheduleKind() == OMPC_SCHEDULE_static;
980 }));
981}
982
983/// Check for inner (nested) lightweight runtime construct, if any
984static bool hasNestedLightweightDirective(ASTContext &Ctx,
985 const OMPExecutableDirective &D) {
986 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
987 const auto *CS = D.getInnermostCapturedStmt();
988 const auto *Body =
989 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000990 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000991
992 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
993 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
994 switch (D.getDirectiveKind()) {
995 case OMPD_target:
996 if (isOpenMPParallelDirective(DKind) &&
997 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
998 hasStaticScheduling(*NestedDir))
999 return true;
1000 if (DKind == OMPD_parallel) {
1001 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1002 /*IgnoreCaptured=*/true);
1003 if (!Body)
1004 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001005 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001006 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1007 DKind = NND->getDirectiveKind();
1008 if (isOpenMPWorksharingDirective(DKind) &&
1009 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1010 return true;
1011 }
1012 } else if (DKind == OMPD_teams) {
1013 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1014 /*IgnoreCaptured=*/true);
1015 if (!Body)
1016 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001017 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001018 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1019 DKind = NND->getDirectiveKind();
1020 if (isOpenMPParallelDirective(DKind) &&
1021 isOpenMPWorksharingDirective(DKind) &&
1022 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1023 return true;
1024 if (DKind == OMPD_parallel) {
1025 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1026 /*IgnoreCaptured=*/true);
1027 if (!Body)
1028 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001029 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001030 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1031 DKind = NND->getDirectiveKind();
1032 if (isOpenMPWorksharingDirective(DKind) &&
1033 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1034 return true;
1035 }
1036 }
1037 }
1038 }
1039 return false;
1040 case OMPD_target_teams:
1041 if (isOpenMPParallelDirective(DKind) &&
1042 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1043 hasStaticScheduling(*NestedDir))
1044 return true;
1045 if (DKind == OMPD_parallel) {
1046 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1047 /*IgnoreCaptured=*/true);
1048 if (!Body)
1049 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001050 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001051 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1052 DKind = NND->getDirectiveKind();
1053 if (isOpenMPWorksharingDirective(DKind) &&
1054 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1055 return true;
1056 }
1057 }
1058 return false;
1059 case OMPD_target_parallel:
1060 return isOpenMPWorksharingDirective(DKind) &&
1061 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1062 case OMPD_target_teams_distribute:
1063 case OMPD_target_simd:
1064 case OMPD_target_parallel_for:
1065 case OMPD_target_parallel_for_simd:
1066 case OMPD_target_teams_distribute_simd:
1067 case OMPD_target_teams_distribute_parallel_for:
1068 case OMPD_target_teams_distribute_parallel_for_simd:
1069 case OMPD_parallel:
1070 case OMPD_for:
1071 case OMPD_parallel_for:
1072 case OMPD_parallel_sections:
1073 case OMPD_for_simd:
1074 case OMPD_parallel_for_simd:
1075 case OMPD_cancel:
1076 case OMPD_cancellation_point:
1077 case OMPD_ordered:
1078 case OMPD_threadprivate:
1079 case OMPD_task:
1080 case OMPD_simd:
1081 case OMPD_sections:
1082 case OMPD_section:
1083 case OMPD_single:
1084 case OMPD_master:
1085 case OMPD_critical:
1086 case OMPD_taskyield:
1087 case OMPD_barrier:
1088 case OMPD_taskwait:
1089 case OMPD_taskgroup:
1090 case OMPD_atomic:
1091 case OMPD_flush:
1092 case OMPD_teams:
1093 case OMPD_target_data:
1094 case OMPD_target_exit_data:
1095 case OMPD_target_enter_data:
1096 case OMPD_distribute:
1097 case OMPD_distribute_simd:
1098 case OMPD_distribute_parallel_for:
1099 case OMPD_distribute_parallel_for_simd:
1100 case OMPD_teams_distribute:
1101 case OMPD_teams_distribute_simd:
1102 case OMPD_teams_distribute_parallel_for:
1103 case OMPD_teams_distribute_parallel_for_simd:
1104 case OMPD_target_update:
1105 case OMPD_declare_simd:
1106 case OMPD_declare_target:
1107 case OMPD_end_declare_target:
1108 case OMPD_declare_reduction:
1109 case OMPD_taskloop:
1110 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001111 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001112 case OMPD_unknown:
1113 llvm_unreachable("Unexpected directive.");
1114 }
1115 }
1116
1117 return false;
1118}
1119
1120/// Checks if the construct supports lightweight runtime. It must be SPMD
1121/// construct + inner loop-based construct with static scheduling.
1122static bool supportsLightweightRuntime(ASTContext &Ctx,
1123 const OMPExecutableDirective &D) {
1124 if (!supportsSPMDExecutionMode(Ctx, D))
1125 return false;
1126 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1127 switch (DirectiveKind) {
1128 case OMPD_target:
1129 case OMPD_target_teams:
1130 case OMPD_target_parallel:
1131 return hasNestedLightweightDirective(Ctx, D);
1132 case OMPD_target_parallel_for:
1133 case OMPD_target_parallel_for_simd:
1134 case OMPD_target_teams_distribute_parallel_for:
1135 case OMPD_target_teams_distribute_parallel_for_simd:
1136 // (Last|First)-privates must be shared in parallel region.
1137 return hasStaticScheduling(D);
1138 case OMPD_target_simd:
1139 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001140 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001141 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001142 case OMPD_parallel:
1143 case OMPD_for:
1144 case OMPD_parallel_for:
1145 case OMPD_parallel_sections:
1146 case OMPD_for_simd:
1147 case OMPD_parallel_for_simd:
1148 case OMPD_cancel:
1149 case OMPD_cancellation_point:
1150 case OMPD_ordered:
1151 case OMPD_threadprivate:
1152 case OMPD_task:
1153 case OMPD_simd:
1154 case OMPD_sections:
1155 case OMPD_section:
1156 case OMPD_single:
1157 case OMPD_master:
1158 case OMPD_critical:
1159 case OMPD_taskyield:
1160 case OMPD_barrier:
1161 case OMPD_taskwait:
1162 case OMPD_taskgroup:
1163 case OMPD_atomic:
1164 case OMPD_flush:
1165 case OMPD_teams:
1166 case OMPD_target_data:
1167 case OMPD_target_exit_data:
1168 case OMPD_target_enter_data:
1169 case OMPD_distribute:
1170 case OMPD_distribute_simd:
1171 case OMPD_distribute_parallel_for:
1172 case OMPD_distribute_parallel_for_simd:
1173 case OMPD_teams_distribute:
1174 case OMPD_teams_distribute_simd:
1175 case OMPD_teams_distribute_parallel_for:
1176 case OMPD_teams_distribute_parallel_for_simd:
1177 case OMPD_target_update:
1178 case OMPD_declare_simd:
1179 case OMPD_declare_target:
1180 case OMPD_end_declare_target:
1181 case OMPD_declare_reduction:
1182 case OMPD_taskloop:
1183 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001184 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001185 case OMPD_unknown:
1186 break;
1187 }
1188 llvm_unreachable(
1189 "Unknown programming model for OpenMP directive on NVPTX target.");
1190}
1191
1192void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 StringRef ParentName,
1194 llvm::Function *&OutlinedFn,
1195 llvm::Constant *&OutlinedFnID,
1196 bool IsOffloadEntry,
1197 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001198 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001199 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001200 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001201 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001202 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001203
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 // Emit target region as a standalone region.
1205 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001206 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1207 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001208
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001210 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001212 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001214 auto &RT =
1215 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001216 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1217 // Skip target region initialization.
1218 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 }
1220 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001221 auto &RT =
1222 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001223 RT.clearLocThreadIdInsertPt(CGF);
1224 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001226 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001228 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001229 // Reserve place for the globalized memory.
1230 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001231 if (!KernelStaticGlobalized) {
1232 KernelStaticGlobalized = new llvm::GlobalVariable(
1233 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1234 llvm::GlobalValue::InternalLinkage,
1235 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1236 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1237 llvm::GlobalValue::NotThreadLocal,
1238 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1239 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001240 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1241 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001242 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001244 // Now change the name of the worker function to correspond to this target
1245 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001246 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001247
1248 // Create the worker function
1249 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001250}
1251
1252// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001253void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 EntryFunctionState &EST,
1255 WorkerFunctionState &WST) {
1256 CGBuilderTy &Bld = CGF.Builder;
1257
1258 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1259 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1260 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1261 EST.ExitBB = CGF.createBasicBlock(".exit");
1262
Alexey Bataev9ff80832018-04-16 20:16:21 +00001263 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001264 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1265 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1266
1267 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001268 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001269 CGF.EmitBranch(EST.ExitBB);
1270
1271 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001272 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001273 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1274 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1275
1276 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001277 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001278 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001279 // First action in sequential region:
1280 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001281 // TODO: Optimize runtime initialization and pass in correct value.
1282 llvm::Value *Args[] = {getThreadLimit(CGF),
1283 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001284 CGF.EmitRuntimeCall(
1285 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001286
1287 // For data sharing, we need to initialize the stack.
1288 CGF.EmitRuntimeCall(
1289 createNVPTXRuntimeFunction(
1290 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1291
Alexey Bataevc99042b2018-03-15 18:10:54 +00001292 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001293}
1294
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001295void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001296 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001297 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001298 if (!CGF.HaveInsertPoint())
1299 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001300
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001301 emitGenericVarsEpilog(CGF);
1302
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001303 if (!EST.ExitBB)
1304 EST.ExitBB = CGF.createBasicBlock(".exit");
1305
1306 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1307 CGF.EmitBranch(TerminateBB);
1308
1309 CGF.EmitBlock(TerminateBB);
1310 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001311 // TODO: Optimize runtime initialization and pass in correct value.
1312 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001313 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001314 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001315 // Barrier to terminate worker threads.
1316 syncCTAThreads(CGF);
1317 // Master thread jumps to exit point.
1318 CGF.EmitBranch(EST.ExitBB);
1319
1320 CGF.EmitBlock(EST.ExitBB);
1321 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001322}
1323
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001324void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001325 StringRef ParentName,
1326 llvm::Function *&OutlinedFn,
1327 llvm::Constant *&OutlinedFnID,
1328 bool IsOffloadEntry,
1329 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001330 ExecutionRuntimeModesRAII ModeRAII(
1331 CurrentExecutionMode, RequiresFullRuntime,
1332 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1333 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001334 EntryFunctionState EST;
1335
1336 // Emit target region as a standalone region.
1337 class NVPTXPrePostActionTy : public PrePostActionTy {
1338 CGOpenMPRuntimeNVPTX &RT;
1339 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1340 const OMPExecutableDirective &D;
1341
1342 public:
1343 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1344 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1345 const OMPExecutableDirective &D)
1346 : RT(RT), EST(EST), D(D) {}
1347 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001348 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001349 // Skip target region initialization.
1350 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351 }
1352 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001353 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001354 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001355 }
1356 } Action(*this, EST, D);
1357 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001358 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001359 // Reserve place for the globalized memory.
1360 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001361 if (!KernelStaticGlobalized) {
1362 KernelStaticGlobalized = new llvm::GlobalVariable(
1363 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1364 llvm::GlobalValue::InternalLinkage,
1365 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1366 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1367 llvm::GlobalValue::NotThreadLocal,
1368 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1369 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001370 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1371 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001372 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001373}
1374
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001375void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001376 CodeGenFunction &CGF, EntryFunctionState &EST,
1377 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001378 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001379
1380 // Setup BBs in entry function.
1381 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1382 EST.ExitBB = CGF.createBasicBlock(".exit");
1383
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001384 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1385 /*RequiresOMPRuntime=*/
1386 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1387 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001388 CGF.EmitRuntimeCall(
1389 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001390
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001391 if (RequiresFullRuntime) {
1392 // For data sharing, we need to initialize the stack.
1393 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1394 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1395 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001396
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001397 CGF.EmitBranch(ExecuteBB);
1398
1399 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001400
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001401 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001402}
1403
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001404void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001405 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001406 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001407 if (!CGF.HaveInsertPoint())
1408 return;
1409
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001410 if (!EST.ExitBB)
1411 EST.ExitBB = CGF.createBasicBlock(".exit");
1412
1413 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1414 CGF.EmitBranch(OMPDeInitBB);
1415
1416 CGF.EmitBlock(OMPDeInitBB);
1417 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001418 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1419 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001420 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001421 createNVPTXRuntimeFunction(
1422 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001423 CGF.EmitBranch(EST.ExitBB);
1424
1425 CGF.EmitBlock(EST.ExitBB);
1426 EST.ExitBB = nullptr;
1427}
1428
1429// Create a unique global variable to indicate the execution mode of this target
1430// region. The execution mode is either 'generic', or 'spmd' depending on the
1431// target directive. This variable is picked up by the offload library to setup
1432// the device appropriately before kernel launch. If the execution mode is
1433// 'generic', the runtime reserves one warp for the master, otherwise, all
1434// warps participate in parallel work.
1435static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001436 bool Mode) {
1437 auto *GVMode =
1438 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1439 llvm::GlobalValue::WeakAnyLinkage,
1440 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1441 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001442 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001443}
1444
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001445void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001446 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001447
1448 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001449 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001450 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001451 emitWorkerLoop(CGF, WST);
1452 CGF.FinishFunction();
1453}
1454
1455void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1456 WorkerFunctionState &WST) {
1457 //
1458 // The workers enter this loop and wait for parallel work from the master.
1459 // When the master encounters a parallel region it sets up the work + variable
1460 // arguments, and wakes up the workers. The workers first check to see if
1461 // they are required for the parallel region, i.e., within the # of requested
1462 // parallel threads. The activated workers load the variable arguments and
1463 // execute the parallel work.
1464 //
1465
1466 CGBuilderTy &Bld = CGF.Builder;
1467
1468 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1469 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1470 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1471 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1472 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1473 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1474
1475 CGF.EmitBranch(AwaitBB);
1476
1477 // Workers wait for work from master.
1478 CGF.EmitBlock(AwaitBB);
1479 // Wait for parallel work
1480 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001481
1482 Address WorkFn =
1483 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1484 Address ExecStatus =
1485 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1486 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1487 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1488
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001489 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001490 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001491 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001492 llvm::Value *Ret = CGF.EmitRuntimeCall(
1493 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1494 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001495
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001496 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001497 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1498 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001499 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1500
1501 // Activate requested workers.
1502 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001503 llvm::Value *IsActive =
1504 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1505 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001506
1507 // Signal start of parallel region.
1508 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001509 // Skip initialization.
1510 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001511
1512 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001513 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001514 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001515 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001516
1517 llvm::Value *WorkFnMatch =
1518 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1519
1520 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1521 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1522 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1523
1524 // Execute this outlined function.
1525 CGF.EmitBlock(ExecuteFNBB);
1526
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001527 // Insert call to work function via shared wrapper. The shared
1528 // wrapper takes two arguments:
1529 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001530 // - the thread ID;
1531 emitCall(CGF, WST.Loc, W,
1532 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001533
1534 // Go to end of parallel region.
1535 CGF.EmitBranch(TerminateBB);
1536
1537 CGF.EmitBlock(CheckNextBB);
1538 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001539 // Default case: call to outlined function through pointer if the target
1540 // region makes a declare target call that may contain an orphaned parallel
1541 // directive.
1542 auto *ParallelFnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1544 /*isVarArg=*/false)
1545 ->getPointerTo();
1546 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1547 // Insert call to work function via shared wrapper. The shared
1548 // wrapper takes two arguments:
1549 // - the parallelism level;
1550 // - the thread ID;
1551 emitCall(CGF, WST.Loc, WorkFnCast,
1552 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1553 // Go to end of parallel region.
1554 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001555
1556 // Signal end of parallel region.
1557 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001558 CGF.EmitRuntimeCall(
1559 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1560 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561 CGF.EmitBranch(BarrierBB);
1562
1563 // All active and inactive workers wait at a barrier after parallel region.
1564 CGF.EmitBlock(BarrierBB);
1565 // Barrier after parallel region.
1566 syncCTAThreads(CGF);
1567 CGF.EmitBranch(AwaitBB);
1568
1569 // Exit target region.
1570 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001571 // Skip initialization.
1572 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001573}
1574
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001575/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001576/// implementation. Specialized for the NVPTX device.
1577/// \param Function OpenMP runtime function.
1578/// \return Specified function.
1579llvm::Constant *
1580CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1581 llvm::Constant *RTLFn = nullptr;
1582 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1583 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001584 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1585 // RequiresOMPRuntime);
1586 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001587 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1590 break;
1591 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001592 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001593 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1594 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001595 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001596 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001597 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1598 break;
1599 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001600 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1601 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001602 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001603 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001604 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001605 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1606 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1607 break;
1608 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001609 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1610 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1611 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001612 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001613 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001615 break;
1616 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001617 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1618 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001619 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001620 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001621 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001622 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1624 break;
1625 }
1626 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001627 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1628 /// int16_t IsOMPRuntimeInitialized);
1629 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001630 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001631 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001632 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1634 break;
1635 }
1636 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1637 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001638 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001639 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1641 break;
1642 }
1643 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1644 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1645 // global_tid);
1646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001647 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001648 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1650 break;
1651 }
1652 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1653 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1654 // global_tid);
1655 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001656 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1659 break;
1660 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001661 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1662 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1663 // int16_t lane_offset, int16_t warp_size);
1664 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001665 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1668 break;
1669 }
1670 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1671 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1672 // int16_t lane_offset, int16_t warp_size);
1673 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001674 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001675 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1677 break;
1678 }
1679 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1680 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1681 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1682 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1683 // lane_offset, int16_t Algorithm Version),
1684 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1685 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1686 CGM.Int16Ty, CGM.Int16Ty};
1687 auto *ShuffleReduceFnTy =
1688 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1689 /*isVarArg=*/false);
1690 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1691 auto *InterWarpCopyFnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1693 /*isVarArg=*/false);
1694 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1695 CGM.Int32Ty,
1696 CGM.SizeTy,
1697 CGM.VoidPtrTy,
1698 ShuffleReduceFnTy->getPointerTo(),
1699 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001700 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001701 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1702 RTLFn = CGM.CreateRuntimeFunction(
1703 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1704 break;
1705 }
1706 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1707 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1708 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001709 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1711 RTLFn = CGM.CreateRuntimeFunction(
1712 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1713 break;
1714 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001715 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1716 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1717 // global_tid, kmp_critical_name *lck)
1718 llvm::Type *TypeParams[] = {
1719 getIdentTyPointerTy(), CGM.Int32Ty,
1720 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1721 auto *FnTy =
1722 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1723 RTLFn = CGM.CreateRuntimeFunction(
1724 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1728 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1729 // global_tid, kmp_critical_name *lck)
1730 llvm::Type *TypeParams[] = {
1731 getIdentTyPointerTy(), CGM.Int32Ty,
1732 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1733 auto *FnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(
1736 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1737 break;
1738 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001739 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1740 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001741 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001742 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1744 break;
1745 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001746 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1747 /// Build void __kmpc_data_sharing_init_stack_spmd();
1748 auto *FnTy =
1749 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001750 RTLFn =
1751 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001752 break;
1753 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001754 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1755 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001756 // int16_t UseSharedMemory);
1757 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001758 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001759 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001761 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001762 break;
1763 }
1764 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1765 // Build void __kmpc_data_sharing_pop_stack(void *a);
1766 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001767 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1770 /*Name=*/"__kmpc_data_sharing_pop_stack");
1771 break;
1772 }
1773 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1774 /// Build void __kmpc_begin_sharing_variables(void ***args,
1775 /// size_t n_args);
1776 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001777 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001778 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1780 break;
1781 }
1782 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1783 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001784 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001785 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1787 break;
1788 }
1789 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1790 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1791 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001792 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1795 break;
1796 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001797 case OMPRTL_NVPTX__kmpc_parallel_level: {
1798 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1800 auto *FnTy =
1801 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1803 break;
1804 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001805 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1806 // Build int8_t __kmpc_is_spmd_exec_mode();
1807 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1808 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1809 break;
1810 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001811 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1812 // Build void __kmpc_get_team_static_memory(const void *buf, size_t size,
1813 // int16_t is_shared, const void **res);
1814 llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.SizeTy, CGM.Int16Ty,
1815 CGM.VoidPtrPtrTy};
1816 auto *FnTy =
1817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1818 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1819 break;
1820 }
1821 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1822 // Build void __kmpc_restore_team_static_memory(int16_t is_shared);
1823 auto *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, CGM.Int16Ty, /*isVarArg=*/false);
1825 RTLFn =
1826 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1827 break;
1828 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001829 case OMPRTL__kmpc_barrier: {
1830 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1831 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1832 auto *FnTy =
1833 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1834 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1835 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1836 break;
1837 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001838 }
1839 return RTLFn;
1840}
1841
1842void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1843 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001844 uint64_t Size, int32_t,
1845 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846 // TODO: Add support for global variables on the device after declare target
1847 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001848 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001849 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001850 llvm::Module &M = CGM.getModule();
1851 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001852
1853 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001854 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001855
1856 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001857 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001858 llvm::ConstantAsMetadata::get(
1859 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1860 // Append metadata to nvvm.annotations
1861 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1862}
1863
1864void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1865 const OMPExecutableDirective &D, StringRef ParentName,
1866 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001867 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001868 if (!IsOffloadEntry) // Nothing to do.
1869 return;
1870
1871 assert(!ParentName.empty() && "Invalid target region parent name!");
1872
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001873 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001874 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001875 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001876 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001877 else
1878 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1879 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001880
1881 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001882}
1883
Alexey Bataevceeaa482018-11-21 21:04:34 +00001884namespace {
1885LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1886/// Enum for accesseing the reserved_2 field of the ident_t struct.
1887enum ModeFlagsTy : unsigned {
1888 /// Bit set to 1 when in SPMD mode.
1889 KMP_IDENT_SPMD_MODE = 0x01,
1890 /// Bit set to 1 when a simplified runtime is used.
1891 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1892 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1893};
1894
1895/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1896static const ModeFlagsTy UndefinedMode =
1897 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1898} // anonymous namespace
1899
1900unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001901 switch (getExecutionMode()) {
1902 case EM_SPMD:
1903 if (requiresFullRuntime())
1904 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1905 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1906 case EM_NonSPMD:
1907 assert(requiresFullRuntime() && "Expected full runtime.");
1908 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1909 case EM_Unknown:
1910 return UndefinedMode;
1911 }
1912 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001913}
1914
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001915CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001916 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001917 if (!CGM.getLangOpts().OpenMPIsDevice)
1918 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001919}
Carlo Bertollic6872252016-04-04 15:55:02 +00001920
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001921void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1922 OpenMPProcBindClauseKind ProcBind,
1923 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001924 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001925 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001926 return;
1927
1928 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1929}
1930
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001931void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1932 llvm::Value *NumThreads,
1933 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001934 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001935 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001936 return;
1937
1938 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1939}
1940
Carlo Bertollic6872252016-04-04 15:55:02 +00001941void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1942 const Expr *NumTeams,
1943 const Expr *ThreadLimit,
1944 SourceLocation Loc) {}
1945
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001946llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1947 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1948 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001949 // Emit target region as a standalone region.
1950 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001951 bool &IsInParallelRegion;
1952 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953
1954 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001955 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1956 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001957 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 PrevIsInParallelRegion = IsInParallelRegion;
1959 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001960 }
1961 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001962 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001963 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001964 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001965 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001966 bool PrevIsInTTDRegion = IsInTTDRegion;
1967 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001968 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1969 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001970 auto *OutlinedFun =
1971 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1972 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001973 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001974 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001975 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1976 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001977 llvm::Function *WrapperFun =
1978 createParallelDataSharingWrapper(OutlinedFun, D);
1979 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1980 }
1981
1982 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001983}
1984
Alexey Bataev2adecff2018-09-21 14:22:53 +00001985/// Get list of lastprivate variables from the teams distribute ... or
1986/// teams {distribute ...} directives.
1987static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001988getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001989 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1990 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1991 "expected teams directive.");
1992 const OMPExecutableDirective *Dir = &D;
1993 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1994 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001995 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001996 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1997 /*IgnoreCaptured=*/true))) {
1998 Dir = dyn_cast<OMPExecutableDirective>(S);
1999 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2000 Dir = nullptr;
2001 }
2002 }
2003 if (!Dir)
2004 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002005 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002006 for (const Expr *E : C->getVarRefs())
2007 Vars.push_back(getPrivateItem(E));
2008 }
2009}
2010
2011/// Get list of reduction variables from the teams ... directives.
2012static void
2013getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2014 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2015 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2016 "expected teams directive.");
2017 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2018 for (const Expr *E : C->privates())
2019 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002020 }
2021}
2022
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002023llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002024 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2025 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002026 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002027
Alexey Bataev2adecff2018-09-21 14:22:53 +00002028 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002029 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002030 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002031 // Globalize team reductions variable unconditionally in all modes.
2032 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002034 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2035 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002036 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002037 CGM.getContext(), llvm::None, LastPrivatesReductions,
2038 MappedDeclsFields);
2039 }
2040 } else if (!LastPrivatesReductions.empty()) {
2041 assert(!TeamAndReductions.first &&
2042 "Previous team declaration is not expected.");
2043 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2044 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002045 }
2046
Alexey Bataevc99042b2018-03-15 18:10:54 +00002047 // Emit target region as a standalone region.
2048 class NVPTXPrePostActionTy : public PrePostActionTy {
2049 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002050 const RecordDecl *GlobalizedRD;
2051 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2052 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002053
2054 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002055 NVPTXPrePostActionTy(
2056 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2057 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2058 &MappedDeclsFields)
2059 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2060 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002061 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002062 auto &Rt =
2063 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2064 if (GlobalizedRD) {
2065 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2066 I->getSecond().GlobalRecord = GlobalizedRD;
2067 I->getSecond().MappedParams =
2068 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2069 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2070 for (const auto &Pair : MappedDeclsFields) {
2071 assert(Pair.getFirst()->isCanonicalDecl() &&
2072 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002073 Data.insert(std::make_pair(Pair.getFirst(),
2074 MappedVarData(Pair.getSecond(),
2075 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002076 }
2077 }
2078 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002079 }
2080 void Exit(CodeGenFunction &CGF) override {
2081 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2082 .emitGenericVarsEpilog(CGF);
2083 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2085 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002086 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2087 D, ThreadIDVar, InnermostKind, CodeGen);
2088 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2089 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002090 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002091 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002092
2093 return OutlinedFun;
2094}
2095
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002097 SourceLocation Loc,
2098 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002099 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2100 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002101 return;
2102
Alexey Bataevc99042b2018-03-15 18:10:54 +00002103 CGBuilderTy &Bld = CGF.Builder;
2104
2105 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2106 if (I == FunctionGlobalizedDecls.end())
2107 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002108 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002109 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002111
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002112 // Recover pointer to this function's global record. The runtime will
2113 // handle the specifics of the allocation of the memory.
2114 // Use actual memory size of the record including the padding
2115 // for alignment purposes.
2116 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002117 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002118 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002119 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002120 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002121
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002122 llvm::PointerType *GlobalRecPtrTy =
2123 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002124 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002125 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002126 if (!IsInTTDRegion &&
2127 (WithSPMDCheck ||
2128 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002129 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2130 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2131 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002132 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2133 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2134 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2135 llvm::Value *PL = CGF.EmitRuntimeCall(
2136 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2137 {RTLoc, ThreadID});
2138 IsTTD = Bld.CreateIsNull(PL);
2139 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2141 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2142 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2143 // There is no need to emit line number for unconditional branch.
2144 (void)ApplyDebugLocation::CreateEmpty(CGF);
2145 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002146 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2147 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002148 CGF.EmitBranch(ExitBB);
2149 // There is no need to emit line number for unconditional branch.
2150 (void)ApplyDebugLocation::CreateEmpty(CGF);
2151 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002152 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2153 if (const RecordDecl *SecGlobalizedVarsRecord =
2154 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2155 SecGlobalRecTy =
2156 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2157
2158 // Recover pointer to this function's global record. The runtime will
2159 // handle the specifics of the allocation of the memory.
2160 // Use actual memory size of the record including the padding
2161 // for alignment purposes.
2162 unsigned Alignment =
2163 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2164 unsigned GlobalRecordSize =
2165 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2166 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2167 Size = Bld.CreateSelect(
2168 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2169 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002170 // TODO: allow the usage of shared memory to be controlled by
2171 // the user, for now, default to global.
2172 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002173 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002174 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2175 createNVPTXRuntimeFunction(
2176 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2177 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002178 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002179 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002180 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002181 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002182 /*NumReservedValues=*/2, "_select_stack");
2183 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2184 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2185 GlobalRecCastAddr = Phi;
2186 I->getSecond().GlobalRecordAddr = Phi;
2187 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002188 } else if (IsInTTDRegion) {
2189 assert(GlobalizedRecords.back().Records.size() < 2 &&
2190 "Expected less than 2 globalized records: one for target and one "
2191 "for teams.");
2192 unsigned Offset = 0;
2193 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2194 QualType RDTy = CGM.getContext().getRecordType(RD);
2195 unsigned Alignment =
2196 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2197 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2198 Offset =
2199 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2200 }
2201 unsigned Alignment =
2202 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2203 Offset = llvm::alignTo(Offset, Alignment);
2204 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2205 ++GlobalizedRecords.back().RegionCounter;
2206 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002207 assert(KernelStaticGlobalized &&
2208 "Kernel static pointer must be initialized already.");
2209 auto *UseSharedMemory = new llvm::GlobalVariable(
2210 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2211 llvm::GlobalValue::InternalLinkage, nullptr,
2212 "_openmp_static_kernel$is_shared");
2213 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2214 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2215 /*DestWidth=*/16, /*Signed=*/0);
2216 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2217 Address(UseSharedMemory,
2218 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2219 /*Volatile=*/false, Int16Ty, Loc);
2220 auto *StaticGlobalized = new llvm::GlobalVariable(
2221 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002222 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002223 auto *RecSize = new llvm::GlobalVariable(
2224 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2225 llvm::GlobalValue::InternalLinkage, nullptr,
2226 "_openmp_static_kernel$size");
2227 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2228 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002229 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 CGM.getContext().getSizeType(), Loc);
2231 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2232 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002233 llvm::Value *GlobalRecordSizeArg[] = {StaticGlobalized, Ld,
2234 IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002235 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2236 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2237 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002238 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002239 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002240 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2241 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002242 }
2243 assert(KernelStaticGlobalized && "Global address must be set already.");
2244 Address FrameAddr = CGF.EmitLoadOfPointer(
2245 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2246 CGM.getContext()
2247 .getPointerType(CGM.getContext().VoidPtrTy)
2248 .castAs<PointerType>());
2249 llvm::Value *GlobalRecValue =
2250 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2251 .getPointer();
2252 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2253 I->getSecond().IsInSPMDModeFlag = nullptr;
2254 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2255 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002256 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002257 // TODO: allow the usage of shared memory to be controlled by
2258 // the user, for now, default to global.
2259 llvm::Value *GlobalRecordSizeArg[] = {
2260 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2261 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002262 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2263 createNVPTXRuntimeFunction(
2264 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2265 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002266 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002267 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002268 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2269 I->getSecond().IsInSPMDModeFlag = nullptr;
2270 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002271 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002272 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002273
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002274 // Emit the "global alloca" which is a GEP from the global declaration
2275 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002276 LValue SecBase;
2277 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2278 if (IsTTD) {
2279 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2280 llvm::PointerType *SecGlobalRecPtrTy =
2281 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2282 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2283 Bld.CreatePointerBitCastOrAddrSpaceCast(
2284 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2285 SecGlobalRecTy);
2286 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002287 for (auto &Rec : I->getSecond().LocalVarData) {
2288 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2289 llvm::Value *ParValue;
2290 if (EscapedParam) {
2291 const auto *VD = cast<VarDecl>(Rec.first);
2292 LValue ParLVal =
2293 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2294 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2295 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002296 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2297 // Emit VarAddr basing on lane-id if required.
2298 QualType VarTy;
2299 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002300 VarTy = Rec.second.FD->getType();
2301 } else {
2302 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2303 VarAddr.getAddress().getPointer(),
2304 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 VarTy =
2306 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002307 VarAddr = CGF.MakeAddrLValue(
2308 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2309 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002310 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002311 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002312 if (!IsInTTDRegion &&
2313 (WithSPMDCheck ||
2314 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002315 assert(I->getSecond().IsInSPMDModeFlag &&
2316 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002317 if (IsTTD) {
2318 assert(SecIt->second.IsOnePerTeam &&
2319 "Secondary glob data must be one per team.");
2320 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2321 VarAddr.setAddress(
2322 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2323 VarAddr.getPointer()),
2324 VarAddr.getAlignment()));
2325 Rec.second.PrivateAddr = VarAddr.getAddress();
2326 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002327 Address GlobalPtr = Rec.second.PrivateAddr;
2328 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2329 Rec.second.PrivateAddr = Address(
2330 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2331 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2332 LocalAddr.getAlignment());
2333 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002334 if (EscapedParam) {
2335 const auto *VD = cast<VarDecl>(Rec.first);
2336 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2337 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2338 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002339 if (IsTTD)
2340 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002341 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002342 }
2343 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2344 // Recover pointer to this function's global record. The runtime will
2345 // handle the specifics of the allocation of the memory.
2346 // Use actual memory size of the record including the padding
2347 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002348 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002349 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2350 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2351 Size = Bld.CreateNUWAdd(
2352 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2353 llvm::Value *AlignVal =
2354 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2355 Size = Bld.CreateUDiv(Size, AlignVal);
2356 Size = Bld.CreateNUWMul(Size, AlignVal);
2357 // TODO: allow the usage of shared memory to be controlled by
2358 // the user, for now, default to global.
2359 llvm::Value *GlobalRecordSizeArg[] = {
2360 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2361 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002362 createNVPTXRuntimeFunction(
2363 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002364 GlobalRecordSizeArg);
2365 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2366 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2367 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2368 CGM.getContext().getDeclAlign(VD),
2369 AlignmentSource::Decl);
2370 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2371 Base.getAddress());
2372 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002373 }
2374 I->getSecond().MappedParams->apply(CGF);
2375}
2376
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002377void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2378 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002379 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2380 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002381 return;
2382
Alexey Bataevc99042b2018-03-15 18:10:54 +00002383 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002384 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002385 I->getSecond().MappedParams->restore(CGF);
2386 if (!CGF.HaveInsertPoint())
2387 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002388 for (llvm::Value *Addr :
2389 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2390 CGF.EmitRuntimeCall(
2391 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2392 Addr);
2393 }
2394 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002395 if (!IsInTTDRegion &&
2396 (WithSPMDCheck ||
2397 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002398 CGBuilderTy &Bld = CGF.Builder;
2399 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2400 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2401 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2402 // There is no need to emit line number for unconditional branch.
2403 (void)ApplyDebugLocation::CreateEmpty(CGF);
2404 CGF.EmitBlock(NonSPMDBB);
2405 CGF.EmitRuntimeCall(
2406 createNVPTXRuntimeFunction(
2407 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2408 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2409 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002410 } else if (IsInTTDRegion) {
2411 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2412 "region counter must be > 0.");
2413 --GlobalizedRecords.back().RegionCounter;
2414 // Emit the restore function only in the target region.
2415 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002416 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2417 /*DestWidth=*/16, /*Signed=*/0);
2418 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2419 Address(GlobalizedRecords.back().UseSharedMemory,
2420 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2421 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataeve4090182018-11-02 14:54:07 +00002422 CGF.EmitRuntimeCall(
2423 createNVPTXRuntimeFunction(
2424 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002425 IsInSharedMemory);
Alexey Bataeve4090182018-11-02 14:54:07 +00002426 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002427 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002428 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2429 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2430 I->getSecond().GlobalRecordAddr);
2431 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002432 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002433 }
2434}
2435
Carlo Bertollic6872252016-04-04 15:55:02 +00002436void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2437 const OMPExecutableDirective &D,
2438 SourceLocation Loc,
2439 llvm::Value *OutlinedFn,
2440 ArrayRef<llvm::Value *> CapturedVars) {
2441 if (!CGF.HaveInsertPoint())
2442 return;
2443
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002444 Address ZeroAddr = CGF.CreateMemTemp(
2445 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2446 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002447 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2448 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002449 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002450 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2451 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002452 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002453}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002454
2455void CGOpenMPRuntimeNVPTX::emitParallelCall(
2456 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2457 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2458 if (!CGF.HaveInsertPoint())
2459 return;
2460
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002461 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002462 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002463 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002464 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002465}
2466
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002467void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002468 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2469 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2470 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002471
2472 // Force inline this outlined function at its call site.
2473 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2474
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002475 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2476 /*DestWidth=*/32, /*Signed=*/1),
2477 ".zero.addr");
2478 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002479 // ThreadId for serialized parallels is 0.
2480 Address ThreadIDAddr = ZeroAddr;
2481 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002482 CodeGenFunction &CGF, PrePostActionTy &Action) {
2483 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002484
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002485 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2486 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2487 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2488 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2489 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2490 };
2491 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2492 PrePostActionTy &) {
2493
2494 RegionCodeGenTy RCG(CodeGen);
2495 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2496 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2497 llvm::Value *Args[] = {RTLoc, ThreadID};
2498
2499 NVPTXActionTy Action(
2500 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2501 Args,
2502 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2503 Args);
2504 RCG.setAction(Action);
2505 RCG(CGF);
2506 };
2507
2508 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2509 PrePostActionTy &Action) {
2510 CGBuilderTy &Bld = CGF.Builder;
2511 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2512 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002513 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2514
2515 // Prepare for parallel region. Indicate the outlined function.
2516 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002517 CGF.EmitRuntimeCall(
2518 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2519 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002520
2521 // Create a private scope that will globalize the arguments
2522 // passed from the outside of the target region.
2523 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2524
2525 // There's somehting to share.
2526 if (!CapturedVars.empty()) {
2527 // Prepare for parallel region. Indicate the outlined function.
2528 Address SharedArgs =
2529 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2530 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2531
2532 llvm::Value *DataSharingArgs[] = {
2533 SharedArgsPtr,
2534 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2535 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2536 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2537 DataSharingArgs);
2538
2539 // Store variable address in a list of references to pass to workers.
2540 unsigned Idx = 0;
2541 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002542 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2543 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2544 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002545 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002546 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2547 CGF.getPointerSize());
2548 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002549 if (V->getType()->isIntegerTy())
2550 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2551 else
2552 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002553 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2554 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002555 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002556 }
2557 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002558
2559 // Activate workers. This barrier is used by the master to signal
2560 // work for the workers.
2561 syncCTAThreads(CGF);
2562
2563 // OpenMP [2.5, Parallel Construct, p.49]
2564 // There is an implied barrier at the end of a parallel region. After the
2565 // end of a parallel region, only the master thread of the team resumes
2566 // execution of the enclosing task region.
2567 //
2568 // The master waits at this barrier until all workers are done.
2569 syncCTAThreads(CGF);
2570
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002571 if (!CapturedVars.empty())
2572 CGF.EmitRuntimeCall(
2573 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2574
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002575 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002576 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002577 };
2578
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002579 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2580 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 if (IsInParallelRegion) {
2582 SeqGen(CGF, Action);
2583 } else if (IsInTargetMasterThreadRegion) {
2584 L0ParallelGen(CGF, Action);
2585 } else {
2586 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002587 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002588 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002589 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002590 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002591 // }
2592 CGBuilderTy &Bld = CGF.Builder;
2593 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002594 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2595 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002596 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002597 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2598 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002599 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002600 // There is no need to emit line number for unconditional branch.
2601 (void)ApplyDebugLocation::CreateEmpty(CGF);
2602 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2604 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2605 llvm::Value *PL = CGF.EmitRuntimeCall(
2606 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2607 {RTLoc, ThreadID});
2608 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002609 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002610 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002613 // There is no need to emit line number for unconditional branch.
2614 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002615 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002616 L0ParallelGen(CGF, Action);
2617 CGF.EmitBranch(ExitBB);
2618 // There is no need to emit line number for unconditional branch.
2619 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002620 // Emit the continuation block for code after the if.
2621 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2622 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002623 };
2624
Alexey Bataev9ff80832018-04-16 20:16:21 +00002625 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002626 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002627 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002628 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002629 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002630 ThenRCG(CGF);
2631 }
2632}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002633
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002634void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002635 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2636 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2637 // Just call the outlined function to execute the parallel region.
2638 // OutlinedFn(&GTid, &zero, CapturedStruct);
2639 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002640 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002641
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002642 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2643 /*DestWidth=*/32, /*Signed=*/1),
2644 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002645 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002646 // ThreadId for serialized parallels is 0.
2647 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002648 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002649 &ThreadIDAddr](CodeGenFunction &CGF,
2650 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002651 Action.Enter(CGF);
2652
2653 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2654 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2655 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2656 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2657 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2658 };
2659 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2660 PrePostActionTy &) {
2661
2662 RegionCodeGenTy RCG(CodeGen);
2663 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2664 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2665 llvm::Value *Args[] = {RTLoc, ThreadID};
2666
2667 NVPTXActionTy Action(
2668 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2669 Args,
2670 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2671 Args);
2672 RCG.setAction(Action);
2673 RCG(CGF);
2674 };
2675
2676 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002677 // In the worker need to use the real thread id.
2678 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002679 RegionCodeGenTy RCG(CodeGen);
2680 RCG(CGF);
2681 } else {
2682 // If we are not in the target region, it is definitely L2 parallelism or
2683 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2684 // need to check for orphaned directives.
2685 RegionCodeGenTy RCG(SeqGen);
2686 RCG(CGF);
2687 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002688}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002689
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002690void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2691 SourceLocation Loc,
2692 OpenMPDirectiveKind Kind, bool,
2693 bool) {
2694 // Always emit simple barriers!
2695 if (!CGF.HaveInsertPoint())
2696 return;
2697 // Build call __kmpc_cancel_barrier(loc, thread_id);
2698 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2699 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2700 getThreadID(CGF, Loc)};
2701 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2702}
2703
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002704void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2705 CodeGenFunction &CGF, StringRef CriticalName,
2706 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2707 const Expr *Hint) {
2708 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2709 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2710 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2711 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2712 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2713
2714 // Fetch team-local id of the thread.
2715 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2716
2717 // Get the width of the team.
2718 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2719
2720 // Initialize the counter variable for the loop.
2721 QualType Int32Ty =
2722 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2723 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2724 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2725 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2726 /*isInit=*/true);
2727
2728 // Block checks if loop counter exceeds upper bound.
2729 CGF.EmitBlock(LoopBB);
2730 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2731 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2732 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2733
2734 // Block tests which single thread should execute region, and which threads
2735 // should go straight to synchronisation point.
2736 CGF.EmitBlock(TestBB);
2737 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2738 llvm::Value *CmpThreadToCounter =
2739 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2740 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2741
2742 // Block emits the body of the critical region.
2743 CGF.EmitBlock(BodyBB);
2744
2745 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002746 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2747 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002748
2749 // After the body surrounded by the critical region, the single executing
2750 // thread will jump to the synchronisation point.
2751 // Block waits for all threads in current team to finish then increments the
2752 // counter variable and returns to the loop.
2753 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002754 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2755 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002756
2757 llvm::Value *IncCounterVal =
2758 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2759 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2760 CGF.EmitBranch(LoopBB);
2761
2762 // Block that is reached when all threads in the team complete the region.
2763 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2764}
2765
Alexey Bataevb2575932018-01-04 20:18:55 +00002766/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002767static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2768 QualType ValTy, QualType CastTy,
2769 SourceLocation Loc) {
2770 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2771 "Cast type must sized.");
2772 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2773 "Val type must sized.");
2774 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2775 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002776 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002777 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2778 CGF.getContext().getTypeSizeInChars(CastTy))
2779 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2780 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2781 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2782 CastTy->hasSignedIntegerRepresentation());
2783 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002784 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2785 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002786 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2787 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002788}
2789
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002790/// This function creates calls to one of two shuffle functions to copy
2791/// variables between lanes in a warp.
2792static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002793 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002794 QualType ElemType,
2795 llvm::Value *Offset,
2796 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002797 CodeGenModule &CGM = CGF.CGM;
2798 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799 CGOpenMPRuntimeNVPTX &RT =
2800 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2801
Alexey Bataeva453f362018-03-19 17:53:56 +00002802 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2803 assert(Size.getQuantity() <= 8 &&
2804 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002805
Alexey Bataeva453f362018-03-19 17:53:56 +00002806 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002807 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2808 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2809
2810 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002811 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2812 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2813 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002814 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002815 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002816
Alexey Bataev9ff80832018-04-16 20:16:21 +00002817 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2818 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002819
Alexey Bataeva453f362018-03-19 17:53:56 +00002820 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002821}
2822
Alexey Bataev12c62902018-06-22 19:10:38 +00002823static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2824 Address DestAddr, QualType ElemType,
2825 llvm::Value *Offset, SourceLocation Loc) {
2826 CGBuilderTy &Bld = CGF.Builder;
2827
2828 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2829 // Create the loop over the big sized data.
2830 // ptr = (void*)Elem;
2831 // ptrEnd = (void*) Elem + 1;
2832 // Step = 8;
2833 // while (ptr + Step < ptrEnd)
2834 // shuffle((int64_t)*ptr);
2835 // Step = 4;
2836 // while (ptr + Step < ptrEnd)
2837 // shuffle((int32_t)*ptr);
2838 // ...
2839 Address ElemPtr = DestAddr;
2840 Address Ptr = SrcAddr;
2841 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2842 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2843 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2844 if (Size < CharUnits::fromQuantity(IntSize))
2845 continue;
2846 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2847 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2848 /*Signed=*/1);
2849 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2850 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2851 ElemPtr =
2852 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2853 if (Size.getQuantity() / IntSize > 1) {
2854 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2855 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2856 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2857 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2858 CGF.EmitBlock(PreCondBB);
2859 llvm::PHINode *PhiSrc =
2860 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2861 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2862 llvm::PHINode *PhiDest =
2863 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2864 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2865 Ptr = Address(PhiSrc, Ptr.getAlignment());
2866 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2867 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2868 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2869 Ptr.getPointer(), CGF.VoidPtrTy));
2870 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2871 ThenBB, ExitBB);
2872 CGF.EmitBlock(ThenBB);
2873 llvm::Value *Res = createRuntimeShuffleFunction(
2874 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2875 IntType, Offset, Loc);
2876 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002877 Address LocalPtr =
2878 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2879 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002880 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002881 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2882 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002883 CGF.EmitBranch(PreCondBB);
2884 CGF.EmitBlock(ExitBB);
2885 } else {
2886 llvm::Value *Res = createRuntimeShuffleFunction(
2887 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2888 IntType, Offset, Loc);
2889 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2890 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2891 ElemPtr =
2892 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2893 }
2894 Size = Size % IntSize;
2895 }
2896}
2897
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002898namespace {
2899enum CopyAction : unsigned {
2900 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2901 // the warp using shuffle instructions.
2902 RemoteLaneToThread,
2903 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2904 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002905 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2906 ThreadToScratchpad,
2907 // ScratchpadToThread: Copy from a scratchpad array in global memory
2908 // containing team-reduced data to a thread's stack.
2909 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002910};
2911} // namespace
2912
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002913struct CopyOptionsTy {
2914 llvm::Value *RemoteLaneOffset;
2915 llvm::Value *ScratchpadIndex;
2916 llvm::Value *ScratchpadWidth;
2917};
2918
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002919/// Emit instructions to copy a Reduce list, which contains partially
2920/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002921static void emitReductionListCopy(
2922 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2923 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2924 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925
Alexey Bataev9ff80832018-04-16 20:16:21 +00002926 CodeGenModule &CGM = CGF.CGM;
2927 ASTContext &C = CGM.getContext();
2928 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929
Alexey Bataev9ff80832018-04-16 20:16:21 +00002930 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2931 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2932 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002933
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002934 // Iterates, element-by-element, through the source Reduce list and
2935 // make a copy.
2936 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002937 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002938 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002939 Address SrcElementAddr = Address::invalid();
2940 Address DestElementAddr = Address::invalid();
2941 Address DestElementPtrAddr = Address::invalid();
2942 // Should we shuffle in an element from a remote lane?
2943 bool ShuffleInElement = false;
2944 // Set to true to update the pointer in the dest Reduce list to a
2945 // newly created element.
2946 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002947 // Increment the src or dest pointer to the scratchpad, for each
2948 // new element.
2949 bool IncrScratchpadSrc = false;
2950 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002951
2952 switch (Action) {
2953 case RemoteLaneToThread: {
2954 // Step 1.1: Get the address for the src element in the Reduce list.
2955 Address SrcElementPtrAddr =
2956 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002957 SrcElementAddr = CGF.EmitLoadOfPointer(
2958 SrcElementPtrAddr,
2959 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002960
2961 // Step 1.2: Create a temporary to store the element in the destination
2962 // Reduce list.
2963 DestElementPtrAddr =
2964 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2965 DestElementAddr =
2966 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2967 ShuffleInElement = true;
2968 UpdateDestListPtr = true;
2969 break;
2970 }
2971 case ThreadCopy: {
2972 // Step 1.1: Get the address for the src element in the Reduce list.
2973 Address SrcElementPtrAddr =
2974 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002975 SrcElementAddr = CGF.EmitLoadOfPointer(
2976 SrcElementPtrAddr,
2977 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002978
2979 // Step 1.2: Get the address for dest element. The destination
2980 // element has already been created on the thread's stack.
2981 DestElementPtrAddr =
2982 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002983 DestElementAddr = CGF.EmitLoadOfPointer(
2984 DestElementPtrAddr,
2985 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002986 break;
2987 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002988 case ThreadToScratchpad: {
2989 // Step 1.1: Get the address for the src element in the Reduce list.
2990 Address SrcElementPtrAddr =
2991 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002992 SrcElementAddr = CGF.EmitLoadOfPointer(
2993 SrcElementPtrAddr,
2994 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002995
2996 // Step 1.2: Get the address for dest element:
2997 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002998 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002999 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003000 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003001 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003002 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003003 ScratchPadElemAbsolutePtrVal =
3004 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003005 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3006 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003007 IncrScratchpadDest = true;
3008 break;
3009 }
3010 case ScratchpadToThread: {
3011 // Step 1.1: Get the address for the src element in the scratchpad.
3012 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003013 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003014 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003015 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003016 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003017 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003018 ScratchPadElemAbsolutePtrVal =
3019 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3020 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3021 C.getTypeAlignInChars(Private->getType()));
3022 IncrScratchpadSrc = true;
3023
3024 // Step 1.2: Create a temporary to store the element in the destination
3025 // Reduce list.
3026 DestElementPtrAddr =
3027 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3028 DestElementAddr =
3029 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3030 UpdateDestListPtr = true;
3031 break;
3032 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003033 }
3034
3035 // Regardless of src and dest of copy, we emit the load of src
3036 // element as this is required in all directions
3037 SrcElementAddr = Bld.CreateElementBitCast(
3038 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003039 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3040 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003041
3042 // Now that all active lanes have read the element in the
3043 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003044 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003045 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3046 RemoteLaneOffset, Private->getExprLoc());
3047 } else {
3048 if (Private->getType()->isScalarType()) {
3049 llvm::Value *Elem =
3050 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3051 Private->getType(), Private->getExprLoc());
3052 // Store the source element value to the dest element address.
3053 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3054 Private->getType());
3055 } else {
3056 CGF.EmitAggregateCopy(
3057 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3058 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3059 Private->getType(), AggValueSlot::DoesNotOverlap);
3060 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003061 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003062
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003063 // Step 3.1: Modify reference in dest Reduce list as needed.
3064 // Modifying the reference in Reduce list to point to the newly
3065 // created element. The element is live in the current function
3066 // scope and that of functions it invokes (i.e., reduce_function).
3067 // RemoteReduceData[i] = (void*)&RemoteElem
3068 if (UpdateDestListPtr) {
3069 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3070 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3071 DestElementPtrAddr, /*Volatile=*/false,
3072 C.VoidPtrTy);
3073 }
3074
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003075 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3076 // address of the next element in scratchpad memory, unless we're currently
3077 // processing the last one. Memory alignment is also taken care of here.
3078 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3079 llvm::Value *ScratchpadBasePtr =
3080 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003081 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3082 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003083 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003084 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003085
3086 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003087 ScratchpadBasePtr = Bld.CreateNUWSub(
3088 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3089 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003090 ScratchpadBasePtr,
3091 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003092 ScratchpadBasePtr = Bld.CreateNUWAdd(
3093 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3094 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003095 ScratchpadBasePtr,
3096 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3097
3098 if (IncrScratchpadDest)
3099 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3100 else /* IncrScratchpadSrc = true */
3101 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3102 }
3103
Alexey Bataev9ff80832018-04-16 20:16:21 +00003104 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003105 }
3106}
3107
3108/// This function emits a helper that gathers Reduce lists from the first
3109/// lane of every active warp to lanes in the first warp.
3110///
3111/// void inter_warp_copy_func(void* reduce_data, num_warps)
3112/// shared smem[warp_size];
3113/// For all data entries D in reduce_data:
3114/// If (I am the first lane in each warp)
3115/// Copy my local D to smem[warp_id]
3116/// sync
3117/// if (I am the first warp)
3118/// Copy smem[thread_id] to my local D
3119/// sync
3120static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3121 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003122 QualType ReductionArrayTy,
3123 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003124 ASTContext &C = CGM.getContext();
3125 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003126
3127 // ReduceList: thread local Reduce list.
3128 // At the stage of the computation when this function is called, partially
3129 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003130 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3131 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003132 // NumWarps: number of warps active in the parallel region. This could
3133 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003134 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003135 C.getIntTypeForBitwidth(32, /* Signed */ true),
3136 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003137 FunctionArgList Args;
3138 Args.push_back(&ReduceListArg);
3139 Args.push_back(&NumWarpsArg);
3140
Alexey Bataev9ff80832018-04-16 20:16:21 +00003141 const CGFunctionInfo &CGFI =
3142 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143 auto *Fn = llvm::Function::Create(
3144 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3145 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003146 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003147 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003148 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003149 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150
Alexey Bataev9ff80832018-04-16 20:16:21 +00003151 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003152
3153 // This array is used as a medium to transfer, one reduce element at a time,
3154 // the data from the first lane of every warp to lanes in the first warp
3155 // in order to perform the final step of a reduction in a parallel region
3156 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3157 // for reduced latency, as well as to have a distinct copy for concurrently
3158 // executing target regions. The array is declared with common linkage so
3159 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003160 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161 "__openmp_nvptx_data_transfer_temporary_storage";
3162 llvm::GlobalVariable *TransferMedium =
3163 M.getGlobalVariable(TransferMediumName);
3164 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003165 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3167 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003168 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003169 llvm::Constant::getNullValue(Ty), TransferMediumName,
3170 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3171 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003172 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003173 }
3174
3175 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003176 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003178 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003179 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003180 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181
3182 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3183 Address LocalReduceList(
3184 Bld.CreatePointerBitCastOrAddrSpaceCast(
3185 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003186 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3188 CGF.getPointerAlign());
3189
3190 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003191 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003192 //
3193 // Warp master copies reduce element to transfer medium in __shared__
3194 // memory.
3195 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003196 unsigned RealTySize =
3197 C.getTypeSizeInChars(Private->getType())
3198 .alignTo(C.getTypeAlignInChars(Private->getType()))
3199 .getQuantity();
3200 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3201 unsigned NumIters = RealTySize / TySize;
3202 if (NumIters == 0)
3203 continue;
3204 QualType CType = C.getIntTypeForBitwidth(
3205 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3206 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3207 CharUnits Align = CharUnits::fromQuantity(TySize);
3208 llvm::Value *Cnt = nullptr;
3209 Address CntAddr = Address::invalid();
3210 llvm::BasicBlock *PrecondBB = nullptr;
3211 llvm::BasicBlock *ExitBB = nullptr;
3212 if (NumIters > 1) {
3213 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3214 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3215 /*Volatile=*/false, C.IntTy);
3216 PrecondBB = CGF.createBasicBlock("precond");
3217 ExitBB = CGF.createBasicBlock("exit");
3218 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3219 // There is no need to emit line number for unconditional branch.
3220 (void)ApplyDebugLocation::CreateEmpty(CGF);
3221 CGF.EmitBlock(PrecondBB);
3222 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3223 llvm::Value *Cmp =
3224 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3225 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3226 CGF.EmitBlock(BodyBB);
3227 }
3228 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3229 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3230 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003231
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003232 // if (lane_id == 0)
3233 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3234 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3235 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003237 // Reduce element = LocalReduceList[i]
3238 Address ElemPtrPtrAddr =
3239 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3240 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3241 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3242 // elemptr = ((CopyType*)(elemptrptr)) + I
3243 Address ElemPtr = Address(ElemPtrPtr, Align);
3244 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3245 if (NumIters > 1) {
3246 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3247 ElemPtr.getAlignment());
3248 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003249
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003250 // Get pointer to location in transfer medium.
3251 // MediumPtr = &medium[warp_id]
3252 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3253 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3254 Address MediumPtr(MediumPtrVal, Align);
3255 // Casting to actual data type.
3256 // MediumPtr = (CopyType*)MediumPtrAddr;
3257 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003258
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003259 // elem = *elemptr
3260 //*MediumPtr = elem
3261 llvm::Value *Elem =
3262 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003263 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003264 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003265
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003266 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003268 CGF.EmitBlock(ElseBB);
3269 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003270
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003271 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003273 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3274 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3275 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003277 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
3278 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3279 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3280 syncParallelThreads(CGF, NumActiveThreads);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 //
3283 // Warp 0 copies reduce element from transfer medium.
3284 //
3285 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3286 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3287 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003288
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003289 // Up to 32 threads in warp 0 are active.
3290 llvm::Value *IsActiveThread =
3291 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3292 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003293
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003294 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003295
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003296 // SrcMediumPtr = &medium[tid]
3297 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3298 TransferMedium,
3299 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3300 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3301 // SrcMediumVal = *SrcMediumPtr;
3302 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003303
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003304 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3305 Address TargetElemPtrPtr =
3306 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3307 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3308 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3309 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3310 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3311 if (NumIters > 1) {
3312 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3313 TargetElemPtr.getAlignment());
3314 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003315
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003316 // *TargetElemPtr = SrcMediumVal;
3317 llvm::Value *SrcMediumValue =
3318 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003319 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003320 CType);
3321 Bld.CreateBr(W0MergeBB);
3322
3323 CGF.EmitBlock(W0ElseBB);
3324 Bld.CreateBr(W0MergeBB);
3325
3326 CGF.EmitBlock(W0MergeBB);
3327
3328 // While warp 0 copies values from transfer medium, all other warps must
3329 // wait.
3330 syncParallelThreads(CGF, NumActiveThreads);
3331 if (NumIters > 1) {
3332 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3333 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3334 CGF.EmitBranch(PrecondBB);
3335 (void)ApplyDebugLocation::CreateEmpty(CGF);
3336 CGF.EmitBlock(ExitBB);
3337 }
3338 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003339 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003340 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003341 }
3342
3343 CGF.FinishFunction();
3344 return Fn;
3345}
3346
3347/// Emit a helper that reduces data across two OpenMP threads (lanes)
3348/// in the same warp. It uses shuffle instructions to copy over data from
3349/// a remote lane's stack. The reduction algorithm performed is specified
3350/// by the fourth parameter.
3351///
3352/// Algorithm Versions.
3353/// Full Warp Reduce (argument value 0):
3354/// This algorithm assumes that all 32 lanes are active and gathers
3355/// data from these 32 lanes, producing a single resultant value.
3356/// Contiguous Partial Warp Reduce (argument value 1):
3357/// This algorithm assumes that only a *contiguous* subset of lanes
3358/// are active. This happens for the last warp in a parallel region
3359/// when the user specified num_threads is not an integer multiple of
3360/// 32. This contiguous subset always starts with the zeroth lane.
3361/// Partial Warp Reduce (argument value 2):
3362/// This algorithm gathers data from any number of lanes at any position.
3363/// All reduced values are stored in the lowest possible lane. The set
3364/// of problems every algorithm addresses is a super set of those
3365/// addressable by algorithms with a lower version number. Overhead
3366/// increases as algorithm version increases.
3367///
3368/// Terminology
3369/// Reduce element:
3370/// Reduce element refers to the individual data field with primitive
3371/// data types to be combined and reduced across threads.
3372/// Reduce list:
3373/// Reduce list refers to a collection of local, thread-private
3374/// reduce elements.
3375/// Remote Reduce list:
3376/// Remote Reduce list refers to a collection of remote (relative to
3377/// the current thread) reduce elements.
3378///
3379/// We distinguish between three states of threads that are important to
3380/// the implementation of this function.
3381/// Alive threads:
3382/// Threads in a warp executing the SIMT instruction, as distinguished from
3383/// threads that are inactive due to divergent control flow.
3384/// Active threads:
3385/// The minimal set of threads that has to be alive upon entry to this
3386/// function. The computation is correct iff active threads are alive.
3387/// Some threads are alive but they are not active because they do not
3388/// contribute to the computation in any useful manner. Turning them off
3389/// may introduce control flow overheads without any tangible benefits.
3390/// Effective threads:
3391/// In order to comply with the argument requirements of the shuffle
3392/// function, we must keep all lanes holding data alive. But at most
3393/// half of them perform value aggregation; we refer to this half of
3394/// threads as effective. The other half is simply handing off their
3395/// data.
3396///
3397/// Procedure
3398/// Value shuffle:
3399/// In this step active threads transfer data from higher lane positions
3400/// in the warp to lower lane positions, creating Remote Reduce list.
3401/// Value aggregation:
3402/// In this step, effective threads combine their thread local Reduce list
3403/// with Remote Reduce list and store the result in the thread local
3404/// Reduce list.
3405/// Value copy:
3406/// In this step, we deal with the assumption made by algorithm 2
3407/// (i.e. contiguity assumption). When we have an odd number of lanes
3408/// active, say 2k+1, only k threads will be effective and therefore k
3409/// new values will be produced. However, the Reduce list owned by the
3410/// (2k+1)th thread is ignored in the value aggregation. Therefore
3411/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3412/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003413static llvm::Value *emitShuffleAndReduceFunction(
3414 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3415 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003416 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003417
3418 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003419 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3420 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003421 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003422 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3423 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003424 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003425 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3426 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003427 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003428 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3429 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430 FunctionArgList Args;
3431 Args.push_back(&ReduceListArg);
3432 Args.push_back(&LaneIDArg);
3433 Args.push_back(&RemoteLaneOffsetArg);
3434 Args.push_back(&AlgoVerArg);
3435
Alexey Bataev9ff80832018-04-16 20:16:21 +00003436 const CGFunctionInfo &CGFI =
3437 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003438 auto *Fn = llvm::Function::Create(
3439 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3440 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003441 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003442 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003444 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445
Alexey Bataev9ff80832018-04-16 20:16:21 +00003446 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003447
3448 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3449 Address LocalReduceList(
3450 Bld.CreatePointerBitCastOrAddrSpaceCast(
3451 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3452 C.VoidPtrTy, SourceLocation()),
3453 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3454 CGF.getPointerAlign());
3455
3456 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3457 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3458 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3459
3460 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3461 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3462 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3463
3464 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3465 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3466 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3467
3468 // Create a local thread-private variable to host the Reduce list
3469 // from a remote lane.
3470 Address RemoteReduceList =
3471 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3472
3473 // This loop iterates through the list of reduce elements and copies,
3474 // element by element, from a remote lane in the warp to RemoteReduceList,
3475 // hosted on the thread's stack.
3476 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3477 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003478 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3479 /*ScratchpadIndex=*/nullptr,
3480 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003481
3482 // The actions to be performed on the Remote Reduce list is dependent
3483 // on the algorithm version.
3484 //
3485 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3486 // LaneId % 2 == 0 && Offset > 0):
3487 // do the reduction value aggregation
3488 //
3489 // The thread local variable Reduce list is mutated in place to host the
3490 // reduced data, which is the aggregated value produced from local and
3491 // remote lanes.
3492 //
3493 // Note that AlgoVer is expected to be a constant integer known at compile
3494 // time.
3495 // When AlgoVer==0, the first conjunction evaluates to true, making
3496 // the entire predicate true during compile time.
3497 // When AlgoVer==1, the second conjunction has only the second part to be
3498 // evaluated during runtime. Other conjunctions evaluates to false
3499 // during compile time.
3500 // When AlgoVer==2, the third conjunction has only the second part to be
3501 // evaluated during runtime. Other conjunctions evaluates to false
3502 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003504
Alexey Bataev9ff80832018-04-16 20:16:21 +00003505 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3506 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003507 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3508
Alexey Bataev9ff80832018-04-16 20:16:21 +00003509 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3510 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3511 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003512 CondAlgo2 = Bld.CreateAnd(
3513 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3514
Alexey Bataev9ff80832018-04-16 20:16:21 +00003515 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003516 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3517
3518 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3519 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3520 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3521 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3522
3523 CGF.EmitBlock(ThenBB);
3524 // reduce_function(LocalReduceList, RemoteReduceList)
3525 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3526 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3527 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3528 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003529 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3530 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003531 Bld.CreateBr(MergeBB);
3532
3533 CGF.EmitBlock(ElseBB);
3534 Bld.CreateBr(MergeBB);
3535
3536 CGF.EmitBlock(MergeBB);
3537
3538 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3539 // Reduce list.
3540 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003541 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003542 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3543
3544 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3545 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3546 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3547 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3548
3549 CGF.EmitBlock(CpyThenBB);
3550 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3551 RemoteReduceList, LocalReduceList);
3552 Bld.CreateBr(CpyMergeBB);
3553
3554 CGF.EmitBlock(CpyElseBB);
3555 Bld.CreateBr(CpyMergeBB);
3556
3557 CGF.EmitBlock(CpyMergeBB);
3558
3559 CGF.FinishFunction();
3560 return Fn;
3561}
3562
3563///
3564/// Design of OpenMP reductions on the GPU
3565///
3566/// Consider a typical OpenMP program with one or more reduction
3567/// clauses:
3568///
3569/// float foo;
3570/// double bar;
3571/// #pragma omp target teams distribute parallel for \
3572/// reduction(+:foo) reduction(*:bar)
3573/// for (int i = 0; i < N; i++) {
3574/// foo += A[i]; bar *= B[i];
3575/// }
3576///
3577/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3578/// all teams. In our OpenMP implementation on the NVPTX device an
3579/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3580/// within a team are mapped to CUDA threads within a threadblock.
3581/// Our goal is to efficiently aggregate values across all OpenMP
3582/// threads such that:
3583///
3584/// - the compiler and runtime are logically concise, and
3585/// - the reduction is performed efficiently in a hierarchical
3586/// manner as follows: within OpenMP threads in the same warp,
3587/// across warps in a threadblock, and finally across teams on
3588/// the NVPTX device.
3589///
3590/// Introduction to Decoupling
3591///
3592/// We would like to decouple the compiler and the runtime so that the
3593/// latter is ignorant of the reduction variables (number, data types)
3594/// and the reduction operators. This allows a simpler interface
3595/// and implementation while still attaining good performance.
3596///
3597/// Pseudocode for the aforementioned OpenMP program generated by the
3598/// compiler is as follows:
3599///
3600/// 1. Create private copies of reduction variables on each OpenMP
3601/// thread: 'foo_private', 'bar_private'
3602/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3603/// to it and writes the result in 'foo_private' and 'bar_private'
3604/// respectively.
3605/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3606/// and store the result on the team master:
3607///
3608/// __kmpc_nvptx_parallel_reduce_nowait(...,
3609/// reduceData, shuffleReduceFn, interWarpCpyFn)
3610///
3611/// where:
3612/// struct ReduceData {
3613/// double *foo;
3614/// double *bar;
3615/// } reduceData
3616/// reduceData.foo = &foo_private
3617/// reduceData.bar = &bar_private
3618///
3619/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3620/// auxiliary functions generated by the compiler that operate on
3621/// variables of type 'ReduceData'. They aid the runtime perform
3622/// algorithmic steps in a data agnostic manner.
3623///
3624/// 'shuffleReduceFn' is a pointer to a function that reduces data
3625/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3626/// same warp. It takes the following arguments as input:
3627///
3628/// a. variable of type 'ReduceData' on the calling lane,
3629/// b. its lane_id,
3630/// c. an offset relative to the current lane_id to generate a
3631/// remote_lane_id. The remote lane contains the second
3632/// variable of type 'ReduceData' that is to be reduced.
3633/// d. an algorithm version parameter determining which reduction
3634/// algorithm to use.
3635///
3636/// 'shuffleReduceFn' retrieves data from the remote lane using
3637/// efficient GPU shuffle intrinsics and reduces, using the
3638/// algorithm specified by the 4th parameter, the two operands
3639/// element-wise. The result is written to the first operand.
3640///
3641/// Different reduction algorithms are implemented in different
3642/// runtime functions, all calling 'shuffleReduceFn' to perform
3643/// the essential reduction step. Therefore, based on the 4th
3644/// parameter, this function behaves slightly differently to
3645/// cooperate with the runtime to ensure correctness under
3646/// different circumstances.
3647///
3648/// 'InterWarpCpyFn' is a pointer to a function that transfers
3649/// reduced variables across warps. It tunnels, through CUDA
3650/// shared memory, the thread-private data of type 'ReduceData'
3651/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003652/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3653/// The last team writes the global reduced value to memory.
3654///
3655/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3656/// reduceData, shuffleReduceFn, interWarpCpyFn,
3657/// scratchpadCopyFn, loadAndReduceFn)
3658///
3659/// 'scratchpadCopyFn' is a helper that stores reduced
3660/// data from the team master to a scratchpad array in
3661/// global memory.
3662///
3663/// 'loadAndReduceFn' is a helper that loads data from
3664/// the scratchpad array and reduces it with the input
3665/// operand.
3666///
3667/// These compiler generated functions hide address
3668/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003669/// 5. if ret == 1:
3670/// The team master of the last team stores the reduced
3671/// result to the globals in memory.
3672/// foo += reduceData.foo; bar *= reduceData.bar
3673///
3674///
3675/// Warp Reduction Algorithms
3676///
3677/// On the warp level, we have three algorithms implemented in the
3678/// OpenMP runtime depending on the number of active lanes:
3679///
3680/// Full Warp Reduction
3681///
3682/// The reduce algorithm within a warp where all lanes are active
3683/// is implemented in the runtime as follows:
3684///
3685/// full_warp_reduce(void *reduce_data,
3686/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3687/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3688/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3689/// }
3690///
3691/// The algorithm completes in log(2, WARPSIZE) steps.
3692///
3693/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3694/// not used therefore we save instructions by not retrieving lane_id
3695/// from the corresponding special registers. The 4th parameter, which
3696/// represents the version of the algorithm being used, is set to 0 to
3697/// signify full warp reduction.
3698///
3699/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3700///
3701/// #reduce_elem refers to an element in the local lane's data structure
3702/// #remote_elem is retrieved from a remote lane
3703/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3704/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3705///
3706/// Contiguous Partial Warp Reduction
3707///
3708/// This reduce algorithm is used within a warp where only the first
3709/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3710/// number of OpenMP threads in a parallel region is not a multiple of
3711/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3712///
3713/// void
3714/// contiguous_partial_reduce(void *reduce_data,
3715/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3716/// int size, int lane_id) {
3717/// int curr_size;
3718/// int offset;
3719/// curr_size = size;
3720/// mask = curr_size/2;
3721/// while (offset>0) {
3722/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3723/// curr_size = (curr_size+1)/2;
3724/// offset = curr_size/2;
3725/// }
3726/// }
3727///
3728/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3729///
3730/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3731/// if (lane_id < offset)
3732/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3733/// else
3734/// reduce_elem = remote_elem
3735///
3736/// This algorithm assumes that the data to be reduced are located in a
3737/// contiguous subset of lanes starting from the first. When there is
3738/// an odd number of active lanes, the data in the last lane is not
3739/// aggregated with any other lane's dat but is instead copied over.
3740///
3741/// Dispersed Partial Warp Reduction
3742///
3743/// This algorithm is used within a warp when any discontiguous subset of
3744/// lanes are active. It is used to implement the reduction operation
3745/// across lanes in an OpenMP simd region or in a nested parallel region.
3746///
3747/// void
3748/// dispersed_partial_reduce(void *reduce_data,
3749/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3750/// int size, remote_id;
3751/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3752/// do {
3753/// remote_id = next_active_lane_id_right_after_me();
3754/// # the above function returns 0 of no active lane
3755/// # is present right after the current lane.
3756/// size = number_of_active_lanes_in_this_warp();
3757/// logical_lane_id /= 2;
3758/// ShuffleReduceFn(reduce_data, logical_lane_id,
3759/// remote_id-1-threadIdx.x, 2);
3760/// } while (logical_lane_id % 2 == 0 && size > 1);
3761/// }
3762///
3763/// There is no assumption made about the initial state of the reduction.
3764/// Any number of lanes (>=1) could be active at any position. The reduction
3765/// result is returned in the first active lane.
3766///
3767/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3768///
3769/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3770/// if (lane_id % 2 == 0 && offset > 0)
3771/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3772/// else
3773/// reduce_elem = remote_elem
3774///
3775///
3776/// Intra-Team Reduction
3777///
3778/// This function, as implemented in the runtime call
3779/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3780/// threads in a team. It first reduces within a warp using the
3781/// aforementioned algorithms. We then proceed to gather all such
3782/// reduced values at the first warp.
3783///
3784/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3785/// data from each of the "warp master" (zeroth lane of each warp, where
3786/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3787/// a mathematical sense) the problem of reduction across warp masters in
3788/// a block to the problem of warp reduction.
3789///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003790///
3791/// Inter-Team Reduction
3792///
3793/// Once a team has reduced its data to a single value, it is stored in
3794/// a global scratchpad array. Since each team has a distinct slot, this
3795/// can be done without locking.
3796///
3797/// The last team to write to the scratchpad array proceeds to reduce the
3798/// scratchpad array. One or more workers in the last team use the helper
3799/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3800/// the k'th worker reduces every k'th element.
3801///
3802/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3803/// reduce across workers and compute a globally reduced value.
3804///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003805void CGOpenMPRuntimeNVPTX::emitReduction(
3806 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3807 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3808 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3809 if (!CGF.HaveInsertPoint())
3810 return;
3811
3812 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003813#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003814 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003815#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003816
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003817 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003818 assert(!TeamsReduction && !ParallelReduction &&
3819 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003820 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3821 ReductionOps, Options);
3822 return;
3823 }
3824
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003825 assert((TeamsReduction || ParallelReduction) &&
3826 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003827
Alexey Bataeva1166022018-11-27 21:24:54 +00003828 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003829 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003830 // or
3831 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003832 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003833
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003834 llvm::Value *Res;
3835 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003836 ASTContext &C = CGM.getContext();
3837 // 1. Build a list of reduction variables.
3838 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3839 auto Size = RHSExprs.size();
3840 for (const Expr *E : Privates) {
3841 if (E->getType()->isVariablyModifiedType())
3842 // Reserve place for array size.
3843 ++Size;
3844 }
3845 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3846 QualType ReductionArrayTy =
3847 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3848 /*IndexTypeQuals=*/0);
3849 Address ReductionList =
3850 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3851 auto IPriv = Privates.begin();
3852 unsigned Idx = 0;
3853 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3854 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3855 CGF.getPointerSize());
3856 CGF.Builder.CreateStore(
3857 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3858 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3859 Elem);
3860 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3861 // Store array size.
3862 ++Idx;
3863 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3864 CGF.getPointerSize());
3865 llvm::Value *Size = CGF.Builder.CreateIntCast(
3866 CGF.getVLASize(
3867 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3868 .NumElts,
3869 CGF.SizeTy, /*isSigned=*/false);
3870 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3871 Elem);
3872 }
3873 }
3874
3875 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3876 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3877 ReductionList.getPointer(), CGF.VoidPtrTy);
3878 llvm::Value *ReductionFn = emitReductionFunction(
3879 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3880 Privates, LHSExprs, RHSExprs, ReductionOps);
3881 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3882 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3883 llvm::Value *InterWarpCopyFn =
3884 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3885
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003886 llvm::Value *Args[] = {ThreadId,
3887 CGF.Builder.getInt32(RHSExprs.size()),
3888 ReductionArrayTySize,
3889 RL,
3890 ShuffleAndReduceFn,
3891 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003892
3893 Res = CGF.EmitRuntimeCall(
3894 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3895 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003896 } else {
3897 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003898 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3899 std::string Name = getName({"reduction"});
3900 llvm::Value *Lock = getCriticalRegionLock(Name);
3901 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003902 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003903 createNVPTXRuntimeFunction(
3904 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003905 Args);
3906 }
3907
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003908 // 5. Build if (res == 1)
3909 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3910 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3911 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3912 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3913 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003914
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003915 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003916 // thread in each team.
3917 // __kmpc_end_reduce{_nowait}(<gtid>);
3918 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003919 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003920
3921 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003922 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003923 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3924 auto IPriv = Privates.begin();
3925 auto ILHS = LHSExprs.begin();
3926 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003927 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003928 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3929 cast<DeclRefExpr>(*IRHS));
3930 ++IPriv;
3931 ++ILHS;
3932 ++IRHS;
3933 }
3934 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003935 if (ParallelReduction) {
3936 llvm::Value *EndArgs[] = {ThreadId};
3937 RegionCodeGenTy RCG(CodeGen);
3938 NVPTXActionTy Action(
3939 nullptr, llvm::None,
3940 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3941 EndArgs);
3942 RCG.setAction(Action);
3943 RCG(CGF);
3944 } else {
3945 assert(TeamsReduction && "expected teams reduction.");
3946 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3947 std::string Name = getName({"reduction"});
3948 llvm::Value *Lock = getCriticalRegionLock(Name);
3949 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3950 RegionCodeGenTy RCG(CodeGen);
3951 NVPTXActionTy Action(
3952 nullptr, llvm::None,
3953 createNVPTXRuntimeFunction(
3954 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3955 EndArgs);
3956 RCG.setAction(Action);
3957 RCG(CGF);
3958 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003959 // There is no need to emit line number for unconditional branch.
3960 (void)ApplyDebugLocation::CreateEmpty(CGF);
3961 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003962}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003963
3964const VarDecl *
3965CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3966 const VarDecl *NativeParam) const {
3967 if (!NativeParam->getType()->isReferenceType())
3968 return NativeParam;
3969 QualType ArgType = NativeParam->getType();
3970 QualifierCollector QC;
3971 const Type *NonQualTy = QC.strip(ArgType);
3972 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3973 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3974 if (Attr->getCaptureKind() == OMPC_map) {
3975 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3976 LangAS::opencl_global);
3977 }
3978 }
3979 ArgType = CGM.getContext().getPointerType(PointeeTy);
3980 QC.addRestrict();
3981 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003982 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003983 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003984 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003985 return ImplicitParamDecl::Create(
3986 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3987 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003988 return ParmVarDecl::Create(
3989 CGM.getContext(),
3990 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003991 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003992 NativeParam->getIdentifier(), ArgType,
3993 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003994}
3995
3996Address
3997CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3998 const VarDecl *NativeParam,
3999 const VarDecl *TargetParam) const {
4000 assert(NativeParam != TargetParam &&
4001 NativeParam->getType()->isReferenceType() &&
4002 "Native arg must not be the same as target arg.");
4003 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4004 QualType NativeParamType = NativeParam->getType();
4005 QualifierCollector QC;
4006 const Type *NonQualTy = QC.strip(NativeParamType);
4007 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4008 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004009 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004010 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004011 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004012 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004013 // First cast to generic.
4014 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4015 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4016 /*AddrSpace=*/0));
4017 // Cast from generic to native address space.
4018 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4019 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4020 NativePointeeAddrSpace));
4021 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4022 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004023 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004024 return NativeParamAddr;
4025}
4026
4027void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004028 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004029 ArrayRef<llvm::Value *> Args) const {
4030 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004031 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004032 auto *FnType =
4033 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4034 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004035 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4036 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4037 break;
4038 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004039 llvm::Type *TargetType = FnType->getParamType(I);
4040 llvm::Value *NativeArg = Args[I];
4041 if (!TargetType->isPointerTy()) {
4042 TargetArgs.emplace_back(NativeArg);
4043 continue;
4044 }
4045 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004046 NativeArg,
4047 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004048 TargetArgs.emplace_back(
4049 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4050 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004051 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004052}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004053
4054/// Emit function which wraps the outline parallel region
4055/// and controls the arguments which are passed to this function.
4056/// The wrapper ensures that the outlined function is called
4057/// with the correct arguments when data is shared.
4058llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4059 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4060 ASTContext &Ctx = CGM.getContext();
4061 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4062
4063 // Create a function that takes as argument the source thread.
4064 FunctionArgList WrapperArgs;
4065 QualType Int16QTy =
4066 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4067 QualType Int32QTy =
4068 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004069 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004070 /*Id=*/nullptr, Int16QTy,
4071 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004072 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004073 /*Id=*/nullptr, Int32QTy,
4074 ImplicitParamDecl::Other);
4075 WrapperArgs.emplace_back(&ParallelLevelArg);
4076 WrapperArgs.emplace_back(&WrapperArg);
4077
Alexey Bataev9ff80832018-04-16 20:16:21 +00004078 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004079 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4080
4081 auto *Fn = llvm::Function::Create(
4082 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004083 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004084 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004086 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004087
4088 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4089 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004090 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004091
4092 const auto *RD = CS.getCapturedRecordDecl();
4093 auto CurField = RD->field_begin();
4094
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004095 Address ZeroAddr = CGF.CreateMemTemp(
4096 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4097 /*Name*/ ".zero.addr");
4098 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004099 // Get the array of arguments.
4100 SmallVector<llvm::Value *, 8> Args;
4101
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004102 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4103 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004104
4105 CGBuilderTy &Bld = CGF.Builder;
4106 auto CI = CS.capture_begin();
4107
4108 // Use global memory for data sharing.
4109 // Handle passing of global args to workers.
4110 Address GlobalArgs =
4111 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4112 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4113 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4114 CGF.EmitRuntimeCall(
4115 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4116 DataSharingArgs);
4117
4118 // Retrieve the shared variables from the list of references returned
4119 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004120 Address SharedArgListAddress = Address::invalid();
4121 if (CS.capture_size() > 0 ||
4122 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4123 SharedArgListAddress = CGF.EmitLoadOfPointer(
4124 GlobalArgs, CGF.getContext()
4125 .getPointerType(CGF.getContext().getPointerType(
4126 CGF.getContext().VoidPtrTy))
4127 .castAs<PointerType>());
4128 }
4129 unsigned Idx = 0;
4130 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4131 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4132 CGF.getPointerSize());
4133 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4134 Src, CGF.SizeTy->getPointerTo());
4135 llvm::Value *LB = CGF.EmitLoadOfScalar(
4136 TypedAddress,
4137 /*Volatile=*/false,
4138 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4139 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4140 Args.emplace_back(LB);
4141 ++Idx;
4142 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4143 CGF.getPointerSize());
4144 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4145 Src, CGF.SizeTy->getPointerTo());
4146 llvm::Value *UB = CGF.EmitLoadOfScalar(
4147 TypedAddress,
4148 /*Volatile=*/false,
4149 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4150 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4151 Args.emplace_back(UB);
4152 ++Idx;
4153 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004154 if (CS.capture_size() > 0) {
4155 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004156 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4157 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004158 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4159 CGF.getPointerSize());
4160 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004161 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4162 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4163 /*Volatile=*/false,
4164 CGFContext.getPointerType(ElemTy),
4165 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004166 if (CI->capturesVariableByCopy() &&
4167 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004168 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4169 CI->getLocation());
4170 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004171 Args.emplace_back(Arg);
4172 }
4173 }
4174
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004175 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004176 CGF.FinishFunction();
4177 return Fn;
4178}
4179
4180void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4181 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004182 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4183 return;
4184
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004185 assert(D && "Expected function or captured|block decl.");
4186 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4187 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004188 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4189 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004190 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004191 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004192 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4193 Body = FD->getBody();
4194 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4195 Body = BD->getBody();
4196 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4197 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004198 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004199 if (NeedToDelayGlobalization &&
4200 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4201 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004202 }
4203 if (!Body)
4204 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004205 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004206 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004207 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004208 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004209 TeamAndReductions.first = nullptr;
4210 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004211 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4212 VarChecker.getEscapedVariableLengthDecls();
4213 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004214 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004215 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4216 I->getSecond().MappedParams =
4217 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4218 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4219 I->getSecond().EscapedParameters.insert(
4220 VarChecker.getEscapedParameters().begin(),
4221 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004222 I->getSecond().EscapedVariableLengthDecls.append(
4223 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004224 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004225 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004226 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004227 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004228 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004229 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004230 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004231 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004232 VarChecker.Visit(Body);
4233 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004234 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004235 I->getSecond().SecondaryLocalVarData.emplace();
4236 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4237 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4238 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4239 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004240 Data.insert(
4241 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004242 }
4243 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004244 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004245 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004246 struct GlobalizationScope final : EHScopeStack::Cleanup {
4247 GlobalizationScope() = default;
4248
4249 void Emit(CodeGenFunction &CGF, Flags flags) override {
4250 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004251 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004252 }
4253 };
4254 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004255 }
4256}
4257
4258Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4259 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004260 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4261 return Address::invalid();
4262
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004263 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004264 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4265 if (I == FunctionGlobalizedDecls.end())
4266 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004267 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004268 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004269 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004270 if (VD->hasAttrs()) {
4271 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4272 E(VD->attr_end());
4273 IT != E; ++IT) {
4274 auto VDI = I->getSecond().LocalVarData.find(
4275 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4276 ->getCanonicalDecl());
4277 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004278 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004279 }
4280 }
4281 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004282}
4283
4284void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004285 FunctionGlobalizedDecls.erase(CGF.CurFn);
4286 CGOpenMPRuntime::functionFinished(CGF);
4287}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004288
4289void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4290 CodeGenFunction &CGF, const OMPLoopDirective &S,
4291 OpenMPDistScheduleClauseKind &ScheduleKind,
4292 llvm::Value *&Chunk) const {
4293 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4294 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4295 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4296 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4297 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004298 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004299 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004300 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4301 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004302}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004303
4304void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4305 CodeGenFunction &CGF, const OMPLoopDirective &S,
4306 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004307 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004308 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004309 // Chunk size is 1 in this case.
4310 llvm::APInt ChunkSize(32, 1);
4311 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4312 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4313 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004314}
Alexey Bataev60705422018-10-30 15:50:12 +00004315
4316void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4317 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4318 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4319 " Expected target-based directive.");
4320 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4321 for (const CapturedStmt::Capture &C : CS->captures()) {
4322 // Capture variables captured by reference in lambdas for target-based
4323 // directives.
4324 if (!C.capturesVariable())
4325 continue;
4326 const VarDecl *VD = C.getCapturedVar();
4327 const auto *RD = VD->getType()
4328 .getCanonicalType()
4329 .getNonReferenceType()
4330 ->getAsCXXRecordDecl();
4331 if (!RD || !RD->isLambda())
4332 continue;
4333 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4334 LValue VDLVal;
4335 if (VD->getType().getCanonicalType()->isReferenceType())
4336 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4337 else
4338 VDLVal = CGF.MakeAddrLValue(
4339 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4340 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4341 FieldDecl *ThisCapture = nullptr;
4342 RD->getCaptureFields(Captures, ThisCapture);
4343 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4344 LValue ThisLVal =
4345 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4346 llvm::Value *CXXThis = CGF.LoadCXXThis();
4347 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4348 }
4349 for (const LambdaCapture &LC : RD->captures()) {
4350 if (LC.getCaptureKind() != LCK_ByRef)
4351 continue;
4352 const VarDecl *VD = LC.getCapturedVar();
4353 if (!CS->capturesVariable(VD))
4354 continue;
4355 auto It = Captures.find(VD);
4356 assert(It != Captures.end() && "Found lambda capture without field.");
4357 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4358 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4359 if (VD->getType().getCanonicalType()->isReferenceType())
4360 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4361 VD->getType().getCanonicalType())
4362 .getAddress();
4363 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4364 }
4365 }
4366}
4367
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004368// Get current CudaArch and ignore any unknown values
4369static CudaArch getCudaArch(CodeGenModule &CGM) {
4370 if (!CGM.getTarget().hasFeature("ptx"))
4371 return CudaArch::UNKNOWN;
4372 llvm::StringMap<bool> Features;
4373 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4374 CGM.getTarget().getTargetOpts().CPU,
4375 CGM.getTarget().getTargetOpts().Features);
4376 for (const auto &Feature : Features) {
4377 if (Feature.getValue()) {
4378 CudaArch Arch = StringToCudaArch(Feature.getKey());
4379 if (Arch != CudaArch::UNKNOWN)
4380 return Arch;
4381 }
4382 }
4383 return CudaArch::UNKNOWN;
4384}
4385
4386/// Check to see if target architecture supports unified addressing which is
4387/// a restriction for OpenMP requires clause "unified_shared_memory".
4388void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4389 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4390 for (const OMPClause *Clause : D->clauselists()) {
4391 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4392 switch (getCudaArch(CGM)) {
4393 case CudaArch::SM_20:
4394 case CudaArch::SM_21:
4395 case CudaArch::SM_30:
4396 case CudaArch::SM_32:
4397 case CudaArch::SM_35:
4398 case CudaArch::SM_37:
4399 case CudaArch::SM_50:
4400 case CudaArch::SM_52:
4401 case CudaArch::SM_53:
4402 case CudaArch::SM_60:
4403 case CudaArch::SM_61:
4404 case CudaArch::SM_62:
4405 CGM.Error(Clause->getBeginLoc(),
4406 "Target architecture does not support unified addressing");
4407 return;
4408 case CudaArch::SM_70:
4409 case CudaArch::SM_72:
4410 case CudaArch::SM_75:
4411 case CudaArch::GFX600:
4412 case CudaArch::GFX601:
4413 case CudaArch::GFX700:
4414 case CudaArch::GFX701:
4415 case CudaArch::GFX702:
4416 case CudaArch::GFX703:
4417 case CudaArch::GFX704:
4418 case CudaArch::GFX801:
4419 case CudaArch::GFX802:
4420 case CudaArch::GFX803:
4421 case CudaArch::GFX810:
4422 case CudaArch::GFX900:
4423 case CudaArch::GFX902:
4424 case CudaArch::GFX904:
4425 case CudaArch::GFX906:
4426 case CudaArch::GFX909:
4427 case CudaArch::UNKNOWN:
4428 break;
4429 case CudaArch::LAST:
4430 llvm_unreachable("Unexpected Cuda arch.");
4431 }
4432 }
4433 }
4434}
4435
Alexey Bataeve4090182018-11-02 14:54:07 +00004436/// Get number of SMs and number of blocks per SM.
4437static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4438 std::pair<unsigned, unsigned> Data;
4439 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4440 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4441 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4442 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4443 if (Data.first && Data.second)
4444 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004445 switch (getCudaArch(CGM)) {
4446 case CudaArch::SM_20:
4447 case CudaArch::SM_21:
4448 case CudaArch::SM_30:
4449 case CudaArch::SM_32:
4450 case CudaArch::SM_35:
4451 case CudaArch::SM_37:
4452 case CudaArch::SM_50:
4453 case CudaArch::SM_52:
4454 case CudaArch::SM_53:
4455 return {16, 16};
4456 case CudaArch::SM_60:
4457 case CudaArch::SM_61:
4458 case CudaArch::SM_62:
4459 return {56, 32};
4460 case CudaArch::SM_70:
4461 case CudaArch::SM_72:
4462 case CudaArch::SM_75:
4463 return {84, 32};
4464 case CudaArch::GFX600:
4465 case CudaArch::GFX601:
4466 case CudaArch::GFX700:
4467 case CudaArch::GFX701:
4468 case CudaArch::GFX702:
4469 case CudaArch::GFX703:
4470 case CudaArch::GFX704:
4471 case CudaArch::GFX801:
4472 case CudaArch::GFX802:
4473 case CudaArch::GFX803:
4474 case CudaArch::GFX810:
4475 case CudaArch::GFX900:
4476 case CudaArch::GFX902:
4477 case CudaArch::GFX904:
4478 case CudaArch::GFX906:
4479 case CudaArch::GFX909:
4480 case CudaArch::UNKNOWN:
4481 break;
4482 case CudaArch::LAST:
4483 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004484 }
4485 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4486}
4487
4488void CGOpenMPRuntimeNVPTX::clear() {
4489 if (!GlobalizedRecords.empty()) {
4490 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004491 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4492 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004493 RecordDecl *StaticRD = C.buildImplicitRecord(
4494 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4495 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004496 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4497 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4498 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004499 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4500 if (Records.Records.empty())
4501 continue;
4502 unsigned Size = 0;
4503 unsigned RecAlignment = 0;
4504 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004505 QualType RDTy = C.getRecordType(RD);
4506 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004507 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004508 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004509 Size =
4510 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4511 }
4512 Size = llvm::alignTo(Size, RecAlignment);
4513 llvm::APInt ArySize(/*numBits=*/64, Size);
4514 QualType SubTy = C.getConstantArrayType(
4515 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004516 const bool UseSharedMemory = Size <= SharedMemorySize;
4517 auto *Field =
4518 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4519 SourceLocation(), SourceLocation(), nullptr, SubTy,
4520 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4521 /*BW=*/nullptr, /*Mutable=*/false,
4522 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004523 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004524 if (UseSharedMemory) {
4525 SharedStaticRD->addDecl(Field);
4526 SharedRecs.push_back(&Records);
4527 } else {
4528 StaticRD->addDecl(Field);
4529 GlobalRecs.push_back(&Records);
4530 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004531 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004532 Records.UseSharedMemory->setInitializer(
4533 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4534 }
4535 SharedStaticRD->completeDefinition();
4536 if (!SharedStaticRD->field_empty()) {
4537 QualType StaticTy = C.getRecordType(SharedStaticRD);
4538 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4539 auto *GV = new llvm::GlobalVariable(
4540 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004541 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004542 llvm::Constant::getNullValue(LLVMStaticTy),
4543 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4544 llvm::GlobalValue::NotThreadLocal,
4545 C.getTargetAddressSpace(LangAS::cuda_shared));
4546 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4547 GV, CGM.VoidPtrTy);
4548 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4549 Rec->Buffer->replaceAllUsesWith(Replacement);
4550 Rec->Buffer->eraseFromParent();
4551 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004552 }
4553 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004554 if (!StaticRD->field_empty()) {
4555 QualType StaticTy = C.getRecordType(StaticRD);
4556 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4557 llvm::APInt Size1(32, SMsBlockPerSM.second);
4558 QualType Arr1Ty =
4559 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4560 /*IndexTypeQuals=*/0);
4561 llvm::APInt Size2(32, SMsBlockPerSM.first);
4562 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4563 /*IndexTypeQuals=*/0);
4564 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4565 auto *GV = new llvm::GlobalVariable(
4566 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004567 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004568 llvm::Constant::getNullValue(LLVMArr2Ty),
4569 "_openmp_static_glob_rd_$_");
4570 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4571 GV, CGM.VoidPtrTy);
4572 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4573 Rec->Buffer->replaceAllUsesWith(Replacement);
4574 Rec->Buffer->eraseFromParent();
4575 }
4576 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004577 }
4578 CGOpenMPRuntime::clear();
4579}