blob: 5e2676bf1677bb6fef6f4ea025fe72632780deea [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
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000192static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
193 RefExpr = RefExpr->IgnoreParens();
194 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
195 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
196 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
197 Base = TempASE->getBase()->IgnoreParenImpCasts();
198 RefExpr = Base;
199 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
200 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
201 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
202 Base = TempOASE->getBase()->IgnoreParenImpCasts();
203 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
204 Base = TempASE->getBase()->IgnoreParenImpCasts();
205 RefExpr = Base;
206 }
207 RefExpr = RefExpr->IgnoreParenImpCasts();
208 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
209 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
210 const auto *ME = cast<MemberExpr>(RefExpr);
211 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
212}
213
Alexey Bataev2adecff2018-09-21 14:22:53 +0000214typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
215static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
216 return P1.first > P2.first;
217}
218
219static RecordDecl *buildRecordForGlobalizedVars(
220 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000221 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000222 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
223 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000224 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000225 return nullptr;
226 SmallVector<VarsDataTy, 4> GlobalizedVars;
227 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000228 GlobalizedVars.emplace_back(
229 CharUnits::fromQuantity(std::max(
230 C.getDeclAlign(D).getQuantity(),
231 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
232 D);
233 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000234 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
235 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
236 stable_sort_comparator);
237 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000238 // /* globalized vars */[WarSize] align (max(decl_align,
239 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000240 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000241 // };
242 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
243 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000244 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
245 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000246 for (const auto &Pair : GlobalizedVars) {
247 const ValueDecl *VD = Pair.second;
248 QualType Type = VD->getType();
249 if (Type->isLValueReferenceType())
250 Type = C.getPointerType(Type.getNonReferenceType());
251 else
252 Type = Type.getNonReferenceType();
253 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000254 FieldDecl *Field;
255 if (SingleEscaped.count(VD)) {
256 Field = FieldDecl::Create(
257 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
258 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
259 /*BW=*/nullptr, /*Mutable=*/false,
260 /*InitStyle=*/ICIS_NoInit);
261 Field->setAccess(AS_public);
262 if (VD->hasAttrs()) {
263 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
264 E(VD->getAttrs().end());
265 I != E; ++I)
266 Field->addAttr(*I);
267 }
268 } else {
269 llvm::APInt ArraySize(32, WarpSize);
270 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
271 Field = FieldDecl::Create(
272 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
273 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
274 /*BW=*/nullptr, /*Mutable=*/false,
275 /*InitStyle=*/ICIS_NoInit);
276 Field->setAccess(AS_public);
277 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
278 static_cast<CharUnits::QuantityType>(
279 GlobalMemoryAlignment)));
280 Field->addAttr(AlignedAttr::CreateImplicit(
281 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
282 IntegerLiteral::Create(C, Align,
283 C.getIntTypeForBitwidth(32, /*Signed=*/0),
284 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000285 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000286 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000287 MappedDeclsFields.try_emplace(VD, Field);
288 }
289 GlobalizedRD->completeDefinition();
290 return GlobalizedRD;
291}
292
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000293/// Get the list of variables that can escape their declaration context.
294class CheckVarsEscapingDeclContext final
295 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
296 CodeGenFunction &CGF;
297 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000298 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000299 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000300 RecordDecl *GlobalizedRD = nullptr;
301 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000302 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000303 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000304
305 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000306 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000307 if (!isa<VarDecl>(VD) ||
308 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000309 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000310 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000311 // Variables captured by value must be globalized.
312 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000313 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000314 // Check if need to capture the variable that was already captured by
315 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000316 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000317 if (!FD->hasAttrs())
318 return;
319 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
320 if (!Attr)
321 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000322 if (((Attr->getCaptureKind() != OMPC_map) &&
323 !isOpenMPPrivate(
324 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
325 ((Attr->getCaptureKind() == OMPC_map) &&
326 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000327 return;
328 }
329 if (!FD->getType()->isReferenceType()) {
330 assert(!VD->getType()->isVariablyModifiedType() &&
331 "Parameter captured by value with variably modified type");
332 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000333 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000334 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000335 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000336 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000337 }
338 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000339 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 VD->getType()->isReferenceType())
341 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000342 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000343 if (VD->getType()->isVariablyModifiedType())
344 EscapedVariableLengthDecls.insert(VD);
345 else
346 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000347 }
348
349 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000350 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000351 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000352 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
353 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
354 const bool SavedAllEscaped = AllEscaped;
355 AllEscaped = VD->getType()->isLValueReferenceType();
356 Visit(VarD->getInit());
357 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000358 }
359 }
360 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000361 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
362 ArrayRef<OMPClause *> Clauses,
363 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000364 if (!S)
365 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000366 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000367 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
368 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000369 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
370 if (IsCombinedParallelRegion) {
371 // Check if the variable is privatized in the combined construct and
372 // those private copies must be shared in the inner parallel
373 // directive.
374 IsForCombinedParallelRegion = false;
375 for (const OMPClause *C : Clauses) {
376 if (!isOpenMPPrivate(C->getClauseKind()) ||
377 C->getClauseKind() == OMPC_reduction ||
378 C->getClauseKind() == OMPC_linear ||
379 C->getClauseKind() == OMPC_private)
380 continue;
381 ArrayRef<const Expr *> Vars;
382 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
383 Vars = PC->getVarRefs();
384 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
385 Vars = PC->getVarRefs();
386 else
387 llvm_unreachable("Unexpected clause.");
388 for (const auto *E : Vars) {
389 const Decl *D =
390 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
391 if (D == VD->getCanonicalDecl()) {
392 IsForCombinedParallelRegion = true;
393 break;
394 }
395 }
396 if (IsForCombinedParallelRegion)
397 break;
398 }
399 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000400 markAsEscaped(VD);
401 if (isa<OMPCapturedExprDecl>(VD))
402 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000403 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000404 }
405 }
406 }
407
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000408 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000409 assert(!GlobalizedRD &&
410 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000411 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000412 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000413 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
414 else
415 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000416 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000417 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000418 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000419 }
420
421public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000422 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
423 ArrayRef<const ValueDecl *> TeamsReductions)
424 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
425 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000426 virtual ~CheckVarsEscapingDeclContext() = default;
427 void VisitDeclStmt(const DeclStmt *S) {
428 if (!S)
429 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000430 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
432 VisitValueDecl(VD);
433 }
434 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
435 if (!D)
436 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000437 if (!D->hasAssociatedStmt())
438 return;
439 if (const auto *S =
440 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
441 // Do not analyze directives that do not actually require capturing,
442 // like `omp for` or `omp simd` directives.
443 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
444 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
445 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
446 VisitStmt(S->getCapturedStmt());
447 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000448 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000449 VisitOpenMPCapturedStmt(
450 S, D->clauses(),
451 CaptureRegions.back() == OMPD_parallel &&
452 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000453 }
454 }
455 void VisitCapturedStmt(const CapturedStmt *S) {
456 if (!S)
457 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000458 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000459 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
460 const ValueDecl *VD = C.getCapturedVar();
461 markAsEscaped(VD);
462 if (isa<OMPCapturedExprDecl>(VD))
463 VisitValueDecl(VD);
464 }
465 }
466 }
467 void VisitLambdaExpr(const LambdaExpr *E) {
468 if (!E)
469 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000470 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 if (C.capturesVariable()) {
472 if (C.getCaptureKind() == LCK_ByRef) {
473 const ValueDecl *VD = C.getCapturedVar();
474 markAsEscaped(VD);
475 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
476 VisitValueDecl(VD);
477 }
478 }
479 }
480 }
481 void VisitBlockExpr(const BlockExpr *E) {
482 if (!E)
483 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000484 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000485 if (C.isByRef()) {
486 const VarDecl *VD = C.getVariable();
487 markAsEscaped(VD);
488 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
489 VisitValueDecl(VD);
490 }
491 }
492 }
493 void VisitCallExpr(const CallExpr *E) {
494 if (!E)
495 return;
496 for (const Expr *Arg : E->arguments()) {
497 if (!Arg)
498 continue;
499 if (Arg->isLValue()) {
500 const bool SavedAllEscaped = AllEscaped;
501 AllEscaped = true;
502 Visit(Arg);
503 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000504 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000505 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000506 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000507 }
508 Visit(E->getCallee());
509 }
510 void VisitDeclRefExpr(const DeclRefExpr *E) {
511 if (!E)
512 return;
513 const ValueDecl *VD = E->getDecl();
514 if (AllEscaped)
515 markAsEscaped(VD);
516 if (isa<OMPCapturedExprDecl>(VD))
517 VisitValueDecl(VD);
518 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
519 if (VarD->isInitCapture())
520 VisitValueDecl(VD);
521 }
522 void VisitUnaryOperator(const UnaryOperator *E) {
523 if (!E)
524 return;
525 if (E->getOpcode() == UO_AddrOf) {
526 const bool SavedAllEscaped = AllEscaped;
527 AllEscaped = true;
528 Visit(E->getSubExpr());
529 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000530 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000531 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000532 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000533 }
534 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
535 if (!E)
536 return;
537 if (E->getCastKind() == CK_ArrayToPointerDecay) {
538 const bool SavedAllEscaped = AllEscaped;
539 AllEscaped = true;
540 Visit(E->getSubExpr());
541 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000542 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000543 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000544 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000545 }
546 void VisitExpr(const Expr *E) {
547 if (!E)
548 return;
549 bool SavedAllEscaped = AllEscaped;
550 if (!E->isLValue())
551 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000552 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000553 if (Child)
554 Visit(Child);
555 AllEscaped = SavedAllEscaped;
556 }
557 void VisitStmt(const Stmt *S) {
558 if (!S)
559 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000560 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000561 if (Child)
562 Visit(Child);
563 }
564
Alexey Bataevc99042b2018-03-15 18:10:54 +0000565 /// Returns the record that handles all the escaped local variables and used
566 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000567 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000568 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000569 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000570 return GlobalizedRD;
571 }
572
Alexey Bataevc99042b2018-03-15 18:10:54 +0000573 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000574 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
575 assert(GlobalizedRD &&
576 "Record for globalized variables must be generated already.");
577 auto I = MappedDeclsFields.find(VD);
578 if (I == MappedDeclsFields.end())
579 return nullptr;
580 return I->getSecond();
581 }
582
Alexey Bataevc99042b2018-03-15 18:10:54 +0000583 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000584 ArrayRef<const ValueDecl *> getEscapedDecls() const {
585 return EscapedDecls.getArrayRef();
586 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000587
588 /// Checks if the escaped local variable is actually a parameter passed by
589 /// value.
590 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
591 return EscapedParameters;
592 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000593
594 /// Returns the list of the escaped variables with the variably modified
595 /// types.
596 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
597 return EscapedVariableLengthDecls.getArrayRef();
598 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000599};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000600} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000601
602/// Get the GPU warp size.
603static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000604 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000605 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000606 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000607 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000608}
609
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000610/// Get the id of the current thread on the GPU.
611static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000612 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000614 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000615 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000616}
617
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000618/// Get the id of the warp in the block.
619/// We assume that the warp size is 32, which is always the case
620/// on the NVPTX device, to generate more efficient code.
621static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
622 CGBuilderTy &Bld = CGF.Builder;
623 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
624}
625
626/// Get the id of the current lane in the Warp.
627/// We assume that the warp size is 32, which is always the case
628/// on the NVPTX device, to generate more efficient code.
629static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
630 CGBuilderTy &Bld = CGF.Builder;
631 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
632 "nvptx_lane_id");
633}
634
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000635/// Get the maximum number of threads in a block of the GPU.
636static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000637 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000638 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000639 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000640 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000641}
642
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000643/// Get barrier to synchronize all threads in a block.
644static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000645 llvm::Function *F = llvm::Intrinsic::getDeclaration(
646 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0);
647 F->addFnAttr(llvm::Attribute::Convergent);
648 CGF.EmitRuntimeCall(F);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000649}
650
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000651/// Synchronize all GPU threads in a block.
652static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000653
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000654/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000655/// For the 'generic' execution mode, the runtime encodes thread_limit in
656/// the launch parameters, always starting thread_limit+warpSize threads per
657/// CTA. The threads in the last warp are reserved for master execution.
658/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
659static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000660 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000661 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000662 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000663 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000664 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
665 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000666}
667
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000668/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000669/// The master thread id is the first thread (lane) of the last warp in the
670/// GPU block. Warp size is assumed to be some power of 2.
671/// Thread id is 0 indexed.
672/// E.g: If NumThreads is 33, master id is 32.
673/// If NumThreads is 64, master id is 32.
674/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000675static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000676 CGBuilderTy &Bld = CGF.Builder;
677 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
678
679 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000680 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000681
Alexey Bataeve290ec02018-04-06 16:03:36 +0000682 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683 Bld.CreateNot(Mask), "master_tid");
684}
685
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000686CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000687 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000688 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
689 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000690 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000691}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000692
693void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
694 CodeGenModule &CGM) {
695 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000696
697 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000698 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000699 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000700 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000701 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000702}
703
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000704CGOpenMPRuntimeNVPTX::ExecutionMode
705CGOpenMPRuntimeNVPTX::getExecutionMode() const {
706 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000707}
708
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000709static CGOpenMPRuntimeNVPTX::DataSharingMode
710getDataSharingMode(CodeGenModule &CGM) {
711 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
712 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000713}
714
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000715// Checks if the expression is constant or does not have non-trivial function
716// calls.
717static bool isTrivial(ASTContext &Ctx, const Expr * E) {
718 // We can skip constant expressions.
719 // We can skip expressions with trivial calls or simple expressions.
720 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
721 !E->hasNonTrivialCall(Ctx)) &&
722 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
723}
724
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000725/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000726/// iff there is only one that is not evaluatable at the compile time.
727static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
728 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
729 const Stmt *Child = nullptr;
730 for (const Stmt *S : C->body()) {
731 if (const auto *E = dyn_cast<Expr>(S)) {
732 if (isTrivial(Ctx, E))
733 continue;
734 }
735 // Some of the statements can be ignored.
736 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
737 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
738 continue;
739 // Analyze declarations.
740 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
741 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
742 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
743 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
744 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
745 isa<UsingDirectiveDecl>(D) ||
746 isa<OMPDeclareReductionDecl>(D) ||
747 isa<OMPThreadPrivateDecl>(D))
748 return true;
749 const auto *VD = dyn_cast<VarDecl>(D);
750 if (!VD)
751 return false;
752 return VD->isConstexpr() ||
753 ((VD->getType().isTrivialType(Ctx) ||
754 VD->getType()->isReferenceType()) &&
755 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
756 }))
757 continue;
758 }
759 // Found multiple children - cannot get the one child only.
760 if (Child)
761 return Body;
762 Child = S;
763 }
764 if (Child)
765 return Child;
766 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000767 return Body;
768}
769
770/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000771/// false condition. Also, check if the number of threads is strictly specified
772/// and run those directives in non-SPMD mode.
773static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
774 const OMPExecutableDirective &D) {
775 if (D.hasClausesOfKind<OMPNumThreadsClause>())
776 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000777 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
778 OpenMPDirectiveKind NameModifier = C->getNameModifier();
779 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
780 continue;
781 const Expr *Cond = C->getCondition();
782 bool Result;
783 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
784 return true;
785 }
786 return false;
787}
788
789/// Check for inner (nested) SPMD construct, if any
790static bool hasNestedSPMDDirective(ASTContext &Ctx,
791 const OMPExecutableDirective &D) {
792 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000793 const auto *Body =
794 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000795 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000796
797 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
798 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000799 switch (D.getDirectiveKind()) {
800 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000801 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000802 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000803 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000804 if (DKind == OMPD_teams) {
805 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
806 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000807 if (!Body)
808 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000809 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000810 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
811 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000812 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000813 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000815 }
816 }
817 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000819 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000820 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 case OMPD_target_simd:
822 case OMPD_target_parallel:
823 case OMPD_target_parallel_for:
824 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000825 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000826 case OMPD_target_teams_distribute_simd:
827 case OMPD_target_teams_distribute_parallel_for:
828 case OMPD_target_teams_distribute_parallel_for_simd:
829 case OMPD_parallel:
830 case OMPD_for:
831 case OMPD_parallel_for:
832 case OMPD_parallel_sections:
833 case OMPD_for_simd:
834 case OMPD_parallel_for_simd:
835 case OMPD_cancel:
836 case OMPD_cancellation_point:
837 case OMPD_ordered:
838 case OMPD_threadprivate:
839 case OMPD_task:
840 case OMPD_simd:
841 case OMPD_sections:
842 case OMPD_section:
843 case OMPD_single:
844 case OMPD_master:
845 case OMPD_critical:
846 case OMPD_taskyield:
847 case OMPD_barrier:
848 case OMPD_taskwait:
849 case OMPD_taskgroup:
850 case OMPD_atomic:
851 case OMPD_flush:
852 case OMPD_teams:
853 case OMPD_target_data:
854 case OMPD_target_exit_data:
855 case OMPD_target_enter_data:
856 case OMPD_distribute:
857 case OMPD_distribute_simd:
858 case OMPD_distribute_parallel_for:
859 case OMPD_distribute_parallel_for_simd:
860 case OMPD_teams_distribute:
861 case OMPD_teams_distribute_simd:
862 case OMPD_teams_distribute_parallel_for:
863 case OMPD_teams_distribute_parallel_for_simd:
864 case OMPD_target_update:
865 case OMPD_declare_simd:
866 case OMPD_declare_target:
867 case OMPD_end_declare_target:
868 case OMPD_declare_reduction:
869 case OMPD_taskloop:
870 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000871 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000872 case OMPD_unknown:
873 llvm_unreachable("Unexpected directive.");
874 }
875 }
876
877 return false;
878}
879
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000880static bool supportsSPMDExecutionMode(ASTContext &Ctx,
881 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000882 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
883 switch (DirectiveKind) {
884 case OMPD_target:
885 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000886 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000887 case OMPD_target_parallel:
888 case OMPD_target_parallel_for:
889 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000890 case OMPD_target_teams_distribute_parallel_for:
891 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000892 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000893 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000894 case OMPD_target_teams_distribute:
895 case OMPD_target_teams_distribute_simd:
896 return false;
897 case OMPD_parallel:
898 case OMPD_for:
899 case OMPD_parallel_for:
900 case OMPD_parallel_sections:
901 case OMPD_for_simd:
902 case OMPD_parallel_for_simd:
903 case OMPD_cancel:
904 case OMPD_cancellation_point:
905 case OMPD_ordered:
906 case OMPD_threadprivate:
907 case OMPD_task:
908 case OMPD_simd:
909 case OMPD_sections:
910 case OMPD_section:
911 case OMPD_single:
912 case OMPD_master:
913 case OMPD_critical:
914 case OMPD_taskyield:
915 case OMPD_barrier:
916 case OMPD_taskwait:
917 case OMPD_taskgroup:
918 case OMPD_atomic:
919 case OMPD_flush:
920 case OMPD_teams:
921 case OMPD_target_data:
922 case OMPD_target_exit_data:
923 case OMPD_target_enter_data:
924 case OMPD_distribute:
925 case OMPD_distribute_simd:
926 case OMPD_distribute_parallel_for:
927 case OMPD_distribute_parallel_for_simd:
928 case OMPD_teams_distribute:
929 case OMPD_teams_distribute_simd:
930 case OMPD_teams_distribute_parallel_for:
931 case OMPD_teams_distribute_parallel_for_simd:
932 case OMPD_target_update:
933 case OMPD_declare_simd:
934 case OMPD_declare_target:
935 case OMPD_end_declare_target:
936 case OMPD_declare_reduction:
937 case OMPD_taskloop:
938 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000939 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000940 case OMPD_unknown:
941 break;
942 }
943 llvm_unreachable(
944 "Unknown programming model for OpenMP directive on NVPTX target.");
945}
946
947/// Check if the directive is loops based and has schedule clause at all or has
948/// static scheduling.
949static bool hasStaticScheduling(const OMPExecutableDirective &D) {
950 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
951 isOpenMPLoopDirective(D.getDirectiveKind()) &&
952 "Expected loop-based directive.");
953 return !D.hasClausesOfKind<OMPOrderedClause>() &&
954 (!D.hasClausesOfKind<OMPScheduleClause>() ||
955 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
956 [](const OMPScheduleClause *C) {
957 return C->getScheduleKind() == OMPC_SCHEDULE_static;
958 }));
959}
960
961/// Check for inner (nested) lightweight runtime construct, if any
962static bool hasNestedLightweightDirective(ASTContext &Ctx,
963 const OMPExecutableDirective &D) {
964 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
965 const auto *CS = D.getInnermostCapturedStmt();
966 const auto *Body =
967 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000968 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000969
970 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
971 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
972 switch (D.getDirectiveKind()) {
973 case OMPD_target:
974 if (isOpenMPParallelDirective(DKind) &&
975 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
976 hasStaticScheduling(*NestedDir))
977 return true;
978 if (DKind == OMPD_parallel) {
979 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
980 /*IgnoreCaptured=*/true);
981 if (!Body)
982 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000983 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000984 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
985 DKind = NND->getDirectiveKind();
986 if (isOpenMPWorksharingDirective(DKind) &&
987 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
988 return true;
989 }
990 } else if (DKind == OMPD_teams) {
991 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
992 /*IgnoreCaptured=*/true);
993 if (!Body)
994 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000995 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000996 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
997 DKind = NND->getDirectiveKind();
998 if (isOpenMPParallelDirective(DKind) &&
999 isOpenMPWorksharingDirective(DKind) &&
1000 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1001 return true;
1002 if (DKind == OMPD_parallel) {
1003 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1004 /*IgnoreCaptured=*/true);
1005 if (!Body)
1006 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001007 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001008 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1009 DKind = NND->getDirectiveKind();
1010 if (isOpenMPWorksharingDirective(DKind) &&
1011 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1012 return true;
1013 }
1014 }
1015 }
1016 }
1017 return false;
1018 case OMPD_target_teams:
1019 if (isOpenMPParallelDirective(DKind) &&
1020 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1021 hasStaticScheduling(*NestedDir))
1022 return true;
1023 if (DKind == OMPD_parallel) {
1024 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1025 /*IgnoreCaptured=*/true);
1026 if (!Body)
1027 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001028 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001029 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1030 DKind = NND->getDirectiveKind();
1031 if (isOpenMPWorksharingDirective(DKind) &&
1032 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1033 return true;
1034 }
1035 }
1036 return false;
1037 case OMPD_target_parallel:
1038 return isOpenMPWorksharingDirective(DKind) &&
1039 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1040 case OMPD_target_teams_distribute:
1041 case OMPD_target_simd:
1042 case OMPD_target_parallel_for:
1043 case OMPD_target_parallel_for_simd:
1044 case OMPD_target_teams_distribute_simd:
1045 case OMPD_target_teams_distribute_parallel_for:
1046 case OMPD_target_teams_distribute_parallel_for_simd:
1047 case OMPD_parallel:
1048 case OMPD_for:
1049 case OMPD_parallel_for:
1050 case OMPD_parallel_sections:
1051 case OMPD_for_simd:
1052 case OMPD_parallel_for_simd:
1053 case OMPD_cancel:
1054 case OMPD_cancellation_point:
1055 case OMPD_ordered:
1056 case OMPD_threadprivate:
1057 case OMPD_task:
1058 case OMPD_simd:
1059 case OMPD_sections:
1060 case OMPD_section:
1061 case OMPD_single:
1062 case OMPD_master:
1063 case OMPD_critical:
1064 case OMPD_taskyield:
1065 case OMPD_barrier:
1066 case OMPD_taskwait:
1067 case OMPD_taskgroup:
1068 case OMPD_atomic:
1069 case OMPD_flush:
1070 case OMPD_teams:
1071 case OMPD_target_data:
1072 case OMPD_target_exit_data:
1073 case OMPD_target_enter_data:
1074 case OMPD_distribute:
1075 case OMPD_distribute_simd:
1076 case OMPD_distribute_parallel_for:
1077 case OMPD_distribute_parallel_for_simd:
1078 case OMPD_teams_distribute:
1079 case OMPD_teams_distribute_simd:
1080 case OMPD_teams_distribute_parallel_for:
1081 case OMPD_teams_distribute_parallel_for_simd:
1082 case OMPD_target_update:
1083 case OMPD_declare_simd:
1084 case OMPD_declare_target:
1085 case OMPD_end_declare_target:
1086 case OMPD_declare_reduction:
1087 case OMPD_taskloop:
1088 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001089 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001090 case OMPD_unknown:
1091 llvm_unreachable("Unexpected directive.");
1092 }
1093 }
1094
1095 return false;
1096}
1097
1098/// Checks if the construct supports lightweight runtime. It must be SPMD
1099/// construct + inner loop-based construct with static scheduling.
1100static bool supportsLightweightRuntime(ASTContext &Ctx,
1101 const OMPExecutableDirective &D) {
1102 if (!supportsSPMDExecutionMode(Ctx, D))
1103 return false;
1104 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1105 switch (DirectiveKind) {
1106 case OMPD_target:
1107 case OMPD_target_teams:
1108 case OMPD_target_parallel:
1109 return hasNestedLightweightDirective(Ctx, D);
1110 case OMPD_target_parallel_for:
1111 case OMPD_target_parallel_for_simd:
1112 case OMPD_target_teams_distribute_parallel_for:
1113 case OMPD_target_teams_distribute_parallel_for_simd:
1114 // (Last|First)-privates must be shared in parallel region.
1115 return hasStaticScheduling(D);
1116 case OMPD_target_simd:
1117 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001118 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001119 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001120 case OMPD_parallel:
1121 case OMPD_for:
1122 case OMPD_parallel_for:
1123 case OMPD_parallel_sections:
1124 case OMPD_for_simd:
1125 case OMPD_parallel_for_simd:
1126 case OMPD_cancel:
1127 case OMPD_cancellation_point:
1128 case OMPD_ordered:
1129 case OMPD_threadprivate:
1130 case OMPD_task:
1131 case OMPD_simd:
1132 case OMPD_sections:
1133 case OMPD_section:
1134 case OMPD_single:
1135 case OMPD_master:
1136 case OMPD_critical:
1137 case OMPD_taskyield:
1138 case OMPD_barrier:
1139 case OMPD_taskwait:
1140 case OMPD_taskgroup:
1141 case OMPD_atomic:
1142 case OMPD_flush:
1143 case OMPD_teams:
1144 case OMPD_target_data:
1145 case OMPD_target_exit_data:
1146 case OMPD_target_enter_data:
1147 case OMPD_distribute:
1148 case OMPD_distribute_simd:
1149 case OMPD_distribute_parallel_for:
1150 case OMPD_distribute_parallel_for_simd:
1151 case OMPD_teams_distribute:
1152 case OMPD_teams_distribute_simd:
1153 case OMPD_teams_distribute_parallel_for:
1154 case OMPD_teams_distribute_parallel_for_simd:
1155 case OMPD_target_update:
1156 case OMPD_declare_simd:
1157 case OMPD_declare_target:
1158 case OMPD_end_declare_target:
1159 case OMPD_declare_reduction:
1160 case OMPD_taskloop:
1161 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001162 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001163 case OMPD_unknown:
1164 break;
1165 }
1166 llvm_unreachable(
1167 "Unknown programming model for OpenMP directive on NVPTX target.");
1168}
1169
1170void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001171 StringRef ParentName,
1172 llvm::Function *&OutlinedFn,
1173 llvm::Constant *&OutlinedFnID,
1174 bool IsOffloadEntry,
1175 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001176 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001177 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001178 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001179 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001180 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001181
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 // Emit target region as a standalone region.
1183 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1185 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001186
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001187 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001188 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001189 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001190 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001192 auto &RT =
1193 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001194 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1195 // Skip target region initialization.
1196 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 }
1198 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001199 auto &RT =
1200 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001201 RT.clearLocThreadIdInsertPt(CGF);
1202 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001204 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001205 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001206 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001207 // Reserve place for the globalized memory.
1208 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001209 if (!KernelStaticGlobalized) {
1210 KernelStaticGlobalized = new llvm::GlobalVariable(
1211 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1212 llvm::GlobalValue::InternalLinkage,
1213 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1214 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1215 llvm::GlobalValue::NotThreadLocal,
1216 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1217 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001218 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1219 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001220 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001222 // Now change the name of the worker function to correspond to this target
1223 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001224 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001225
1226 // Create the worker function
1227 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001228}
1229
1230// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001231void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001232 EntryFunctionState &EST,
1233 WorkerFunctionState &WST) {
1234 CGBuilderTy &Bld = CGF.Builder;
1235
1236 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1237 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1238 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1239 EST.ExitBB = CGF.createBasicBlock(".exit");
1240
Alexey Bataev9ff80832018-04-16 20:16:21 +00001241 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001242 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1243 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1244
1245 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001246 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001247 CGF.EmitBranch(EST.ExitBB);
1248
1249 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001250 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001251 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1252 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1253
1254 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001255 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001256 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001257 // First action in sequential region:
1258 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001259 // TODO: Optimize runtime initialization and pass in correct value.
1260 llvm::Value *Args[] = {getThreadLimit(CGF),
1261 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001262 CGF.EmitRuntimeCall(
1263 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001264
1265 // For data sharing, we need to initialize the stack.
1266 CGF.EmitRuntimeCall(
1267 createNVPTXRuntimeFunction(
1268 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1269
Alexey Bataevc99042b2018-03-15 18:10:54 +00001270 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001271}
1272
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001273void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001274 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001275 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001276 if (!CGF.HaveInsertPoint())
1277 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001278
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001279 emitGenericVarsEpilog(CGF);
1280
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001281 if (!EST.ExitBB)
1282 EST.ExitBB = CGF.createBasicBlock(".exit");
1283
1284 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1285 CGF.EmitBranch(TerminateBB);
1286
1287 CGF.EmitBlock(TerminateBB);
1288 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001289 // TODO: Optimize runtime initialization and pass in correct value.
1290 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001291 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001292 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001293 // Barrier to terminate worker threads.
1294 syncCTAThreads(CGF);
1295 // Master thread jumps to exit point.
1296 CGF.EmitBranch(EST.ExitBB);
1297
1298 CGF.EmitBlock(EST.ExitBB);
1299 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001300}
1301
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001302void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001303 StringRef ParentName,
1304 llvm::Function *&OutlinedFn,
1305 llvm::Constant *&OutlinedFnID,
1306 bool IsOffloadEntry,
1307 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001308 ExecutionRuntimeModesRAII ModeRAII(
1309 CurrentExecutionMode, RequiresFullRuntime,
1310 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1311 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001312 EntryFunctionState EST;
1313
1314 // Emit target region as a standalone region.
1315 class NVPTXPrePostActionTy : public PrePostActionTy {
1316 CGOpenMPRuntimeNVPTX &RT;
1317 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1318 const OMPExecutableDirective &D;
1319
1320 public:
1321 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1322 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1323 const OMPExecutableDirective &D)
1324 : RT(RT), EST(EST), D(D) {}
1325 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001326 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001327 // Skip target region initialization.
1328 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001329 }
1330 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001331 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001332 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001333 }
1334 } Action(*this, EST, D);
1335 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001336 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001337 // Reserve place for the globalized memory.
1338 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001339 if (!KernelStaticGlobalized) {
1340 KernelStaticGlobalized = new llvm::GlobalVariable(
1341 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1342 llvm::GlobalValue::InternalLinkage,
1343 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1344 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1345 llvm::GlobalValue::NotThreadLocal,
1346 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1347 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1349 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001350 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351}
1352
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001353void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001354 CodeGenFunction &CGF, EntryFunctionState &EST,
1355 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001356 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001357
1358 // Setup BBs in entry function.
1359 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1360 EST.ExitBB = CGF.createBasicBlock(".exit");
1361
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001362 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1363 /*RequiresOMPRuntime=*/
1364 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1365 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001366 CGF.EmitRuntimeCall(
1367 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001368
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001369 if (RequiresFullRuntime) {
1370 // For data sharing, we need to initialize the stack.
1371 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1372 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1373 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001374
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001375 CGF.EmitBranch(ExecuteBB);
1376
1377 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001378
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001379 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001380}
1381
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001382void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001383 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001384 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001385 if (!CGF.HaveInsertPoint())
1386 return;
1387
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001388 if (!EST.ExitBB)
1389 EST.ExitBB = CGF.createBasicBlock(".exit");
1390
1391 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1392 CGF.EmitBranch(OMPDeInitBB);
1393
1394 CGF.EmitBlock(OMPDeInitBB);
1395 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001396 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1397 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001398 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001399 createNVPTXRuntimeFunction(
1400 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001401 CGF.EmitBranch(EST.ExitBB);
1402
1403 CGF.EmitBlock(EST.ExitBB);
1404 EST.ExitBB = nullptr;
1405}
1406
1407// Create a unique global variable to indicate the execution mode of this target
1408// region. The execution mode is either 'generic', or 'spmd' depending on the
1409// target directive. This variable is picked up by the offload library to setup
1410// the device appropriately before kernel launch. If the execution mode is
1411// 'generic', the runtime reserves one warp for the master, otherwise, all
1412// warps participate in parallel work.
1413static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001414 bool Mode) {
1415 auto *GVMode =
1416 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1417 llvm::GlobalValue::WeakAnyLinkage,
1418 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1419 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001420 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001421}
1422
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001423void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001424 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001425
1426 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001427 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001428 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001429 emitWorkerLoop(CGF, WST);
1430 CGF.FinishFunction();
1431}
1432
1433void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1434 WorkerFunctionState &WST) {
1435 //
1436 // The workers enter this loop and wait for parallel work from the master.
1437 // When the master encounters a parallel region it sets up the work + variable
1438 // arguments, and wakes up the workers. The workers first check to see if
1439 // they are required for the parallel region, i.e., within the # of requested
1440 // parallel threads. The activated workers load the variable arguments and
1441 // execute the parallel work.
1442 //
1443
1444 CGBuilderTy &Bld = CGF.Builder;
1445
1446 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1447 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1448 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1449 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1450 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1451 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1452
1453 CGF.EmitBranch(AwaitBB);
1454
1455 // Workers wait for work from master.
1456 CGF.EmitBlock(AwaitBB);
1457 // Wait for parallel work
1458 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001459
1460 Address WorkFn =
1461 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1462 Address ExecStatus =
1463 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1464 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1465 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1466
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001467 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001468 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001469 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001470 llvm::Value *Ret = CGF.EmitRuntimeCall(
1471 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1472 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001473
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001474 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001475 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1476 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001477 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1478
1479 // Activate requested workers.
1480 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001481 llvm::Value *IsActive =
1482 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1483 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001484
1485 // Signal start of parallel region.
1486 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001487 // Skip initialization.
1488 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001489
1490 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001491 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001492 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001493 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001494
1495 llvm::Value *WorkFnMatch =
1496 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1497
1498 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1499 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1500 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1501
1502 // Execute this outlined function.
1503 CGF.EmitBlock(ExecuteFNBB);
1504
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001505 // Insert call to work function via shared wrapper. The shared
1506 // wrapper takes two arguments:
1507 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001508 // - the thread ID;
1509 emitCall(CGF, WST.Loc, W,
1510 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001511
1512 // Go to end of parallel region.
1513 CGF.EmitBranch(TerminateBB);
1514
1515 CGF.EmitBlock(CheckNextBB);
1516 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001517 // Default case: call to outlined function through pointer if the target
1518 // region makes a declare target call that may contain an orphaned parallel
1519 // directive.
1520 auto *ParallelFnTy =
1521 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1522 /*isVarArg=*/false)
1523 ->getPointerTo();
1524 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1525 // Insert call to work function via shared wrapper. The shared
1526 // wrapper takes two arguments:
1527 // - the parallelism level;
1528 // - the thread ID;
1529 emitCall(CGF, WST.Loc, WorkFnCast,
1530 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1531 // Go to end of parallel region.
1532 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001533
1534 // Signal end of parallel region.
1535 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001536 CGF.EmitRuntimeCall(
1537 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1538 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001539 CGF.EmitBranch(BarrierBB);
1540
1541 // All active and inactive workers wait at a barrier after parallel region.
1542 CGF.EmitBlock(BarrierBB);
1543 // Barrier after parallel region.
1544 syncCTAThreads(CGF);
1545 CGF.EmitBranch(AwaitBB);
1546
1547 // Exit target region.
1548 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001549 // Skip initialization.
1550 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001551}
1552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001553/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001554/// implementation. Specialized for the NVPTX device.
1555/// \param Function OpenMP runtime function.
1556/// \return Specified function.
1557llvm::Constant *
1558CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1559 llvm::Constant *RTLFn = nullptr;
1560 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1561 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001562 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1563 // RequiresOMPRuntime);
1564 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001565 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1568 break;
1569 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001570 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001571 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1572 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001573 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001574 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001575 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1576 break;
1577 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001578 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1579 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001580 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001581 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001582 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001583 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1584 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1585 break;
1586 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001587 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1588 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1589 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001590 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001591 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001593 break;
1594 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001595 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1596 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001597 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001598 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001599 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001600 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1602 break;
1603 }
1604 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001605 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1606 /// int16_t IsOMPRuntimeInitialized);
1607 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001608 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001609 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001610 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1611 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1612 break;
1613 }
1614 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1615 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001616 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001617 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1618 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1619 break;
1620 }
1621 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1622 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1623 // global_tid);
1624 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001625 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001626 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1627 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1628 break;
1629 }
1630 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1631 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1632 // global_tid);
1633 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001634 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1637 break;
1638 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001639 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1640 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1641 // int16_t lane_offset, int16_t warp_size);
1642 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001643 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001644 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1645 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1646 break;
1647 }
1648 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1649 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1650 // int16_t lane_offset, int16_t warp_size);
1651 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001652 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001653 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1654 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1655 break;
1656 }
1657 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1658 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1659 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1660 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1661 // lane_offset, int16_t Algorithm Version),
1662 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1663 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1664 CGM.Int16Ty, CGM.Int16Ty};
1665 auto *ShuffleReduceFnTy =
1666 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1667 /*isVarArg=*/false);
1668 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1669 auto *InterWarpCopyFnTy =
1670 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1671 /*isVarArg=*/false);
1672 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1673 CGM.Int32Ty,
1674 CGM.SizeTy,
1675 CGM.VoidPtrTy,
1676 ShuffleReduceFnTy->getPointerTo(),
1677 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001678 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001679 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1680 RTLFn = CGM.CreateRuntimeFunction(
1681 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1682 break;
1683 }
1684 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1685 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1686 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001687 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001688 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1689 RTLFn = CGM.CreateRuntimeFunction(
1690 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1691 break;
1692 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001693 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1694 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1695 // global_tid, kmp_critical_name *lck)
1696 llvm::Type *TypeParams[] = {
1697 getIdentTyPointerTy(), CGM.Int32Ty,
1698 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1699 auto *FnTy =
1700 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1701 RTLFn = CGM.CreateRuntimeFunction(
1702 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1703 break;
1704 }
1705 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1706 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1707 // global_tid, kmp_critical_name *lck)
1708 llvm::Type *TypeParams[] = {
1709 getIdentTyPointerTy(), CGM.Int32Ty,
1710 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1711 auto *FnTy =
1712 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1713 RTLFn = CGM.CreateRuntimeFunction(
1714 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1715 break;
1716 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001717 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1718 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001719 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001720 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1721 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1722 break;
1723 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001724 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1725 /// Build void __kmpc_data_sharing_init_stack_spmd();
1726 auto *FnTy =
1727 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001728 RTLFn =
1729 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001730 break;
1731 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001732 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1733 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001734 // int16_t UseSharedMemory);
1735 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001736 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001737 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1738 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001739 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001740 break;
1741 }
1742 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1743 // Build void __kmpc_data_sharing_pop_stack(void *a);
1744 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001745 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001746 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1747 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1748 /*Name=*/"__kmpc_data_sharing_pop_stack");
1749 break;
1750 }
1751 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1752 /// Build void __kmpc_begin_sharing_variables(void ***args,
1753 /// size_t n_args);
1754 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001755 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001756 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1758 break;
1759 }
1760 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1761 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001762 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001763 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1765 break;
1766 }
1767 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1768 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1769 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001770 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1773 break;
1774 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001775 case OMPRTL_NVPTX__kmpc_parallel_level: {
1776 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1777 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1778 auto *FnTy =
1779 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1781 break;
1782 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001783 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1784 // Build int8_t __kmpc_is_spmd_exec_mode();
1785 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1787 break;
1788 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001789 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1790 // Build void __kmpc_get_team_static_memory(const void *buf, size_t size,
1791 // int16_t is_shared, const void **res);
1792 llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.SizeTy, CGM.Int16Ty,
1793 CGM.VoidPtrPtrTy};
1794 auto *FnTy =
1795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1796 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1797 break;
1798 }
1799 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1800 // Build void __kmpc_restore_team_static_memory(int16_t is_shared);
1801 auto *FnTy =
1802 llvm::FunctionType::get(CGM.VoidTy, CGM.Int16Ty, /*isVarArg=*/false);
1803 RTLFn =
1804 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1805 break;
1806 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001807 case OMPRTL__kmpc_barrier: {
1808 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1810 auto *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1813 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1814 break;
1815 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001816 }
1817 return RTLFn;
1818}
1819
1820void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1821 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001822 uint64_t Size, int32_t,
1823 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001824 // TODO: Add support for global variables on the device after declare target
1825 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001826 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001827 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001828 llvm::Module &M = CGM.getModule();
1829 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001830
1831 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001832 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001833
1834 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001835 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001836 llvm::ConstantAsMetadata::get(
1837 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1838 // Append metadata to nvvm.annotations
1839 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1840}
1841
1842void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1843 const OMPExecutableDirective &D, StringRef ParentName,
1844 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001845 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846 if (!IsOffloadEntry) // Nothing to do.
1847 return;
1848
1849 assert(!ParentName.empty() && "Invalid target region parent name!");
1850
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001851 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001852 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001853 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001854 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001855 else
1856 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1857 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001858
1859 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001860}
1861
Alexey Bataevceeaa482018-11-21 21:04:34 +00001862namespace {
1863LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1864/// Enum for accesseing the reserved_2 field of the ident_t struct.
1865enum ModeFlagsTy : unsigned {
1866 /// Bit set to 1 when in SPMD mode.
1867 KMP_IDENT_SPMD_MODE = 0x01,
1868 /// Bit set to 1 when a simplified runtime is used.
1869 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1870 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1871};
1872
1873/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1874static const ModeFlagsTy UndefinedMode =
1875 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1876} // anonymous namespace
1877
1878unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001879 switch (getExecutionMode()) {
1880 case EM_SPMD:
1881 if (requiresFullRuntime())
1882 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1883 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1884 case EM_NonSPMD:
1885 assert(requiresFullRuntime() && "Expected full runtime.");
1886 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1887 case EM_Unknown:
1888 return UndefinedMode;
1889 }
1890 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001891}
1892
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001893CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001894 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001895 if (!CGM.getLangOpts().OpenMPIsDevice)
1896 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001897}
Carlo Bertollic6872252016-04-04 15:55:02 +00001898
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001899void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1900 OpenMPProcBindClauseKind ProcBind,
1901 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001902 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001903 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001904 return;
1905
1906 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1907}
1908
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001909void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1910 llvm::Value *NumThreads,
1911 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001912 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001913 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001914 return;
1915
1916 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1917}
1918
Carlo Bertollic6872252016-04-04 15:55:02 +00001919void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1920 const Expr *NumTeams,
1921 const Expr *ThreadLimit,
1922 SourceLocation Loc) {}
1923
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001924llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1925 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1926 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001927 // Emit target region as a standalone region.
1928 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001929 bool &IsInParallelRegion;
1930 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001931
1932 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001933 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1934 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001935 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001936 PrevIsInParallelRegion = IsInParallelRegion;
1937 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938 }
1939 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001940 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001941 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001942 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001943 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001944 bool PrevIsInTTDRegion = IsInTTDRegion;
1945 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001946 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1947 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001948 auto *OutlinedFun =
1949 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1950 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001951 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001952 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001953 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1954 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001955 llvm::Function *WrapperFun =
1956 createParallelDataSharingWrapper(OutlinedFun, D);
1957 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1958 }
1959
1960 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001961}
1962
Alexey Bataev2adecff2018-09-21 14:22:53 +00001963/// Get list of lastprivate variables from the teams distribute ... or
1964/// teams {distribute ...} directives.
1965static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001966getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001967 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1968 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1969 "expected teams directive.");
1970 const OMPExecutableDirective *Dir = &D;
1971 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1972 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001973 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001974 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1975 /*IgnoreCaptured=*/true))) {
1976 Dir = dyn_cast<OMPExecutableDirective>(S);
1977 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1978 Dir = nullptr;
1979 }
1980 }
1981 if (!Dir)
1982 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001983 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001984 for (const Expr *E : C->getVarRefs())
1985 Vars.push_back(getPrivateItem(E));
1986 }
1987}
1988
1989/// Get list of reduction variables from the teams ... directives.
1990static void
1991getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1992 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1993 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1994 "expected teams directive.");
1995 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1996 for (const Expr *E : C->privates())
1997 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001998 }
1999}
2000
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002001llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002002 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2003 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002004 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002005
Alexey Bataev2adecff2018-09-21 14:22:53 +00002006 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002007 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002008 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002009 // Globalize team reductions variable unconditionally in all modes.
2010 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002011 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002012 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2013 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002014 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002015 CGM.getContext(), llvm::None, LastPrivatesReductions,
2016 MappedDeclsFields);
2017 }
2018 } else if (!LastPrivatesReductions.empty()) {
2019 assert(!TeamAndReductions.first &&
2020 "Previous team declaration is not expected.");
2021 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2022 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002023 }
2024
Alexey Bataevc99042b2018-03-15 18:10:54 +00002025 // Emit target region as a standalone region.
2026 class NVPTXPrePostActionTy : public PrePostActionTy {
2027 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002028 const RecordDecl *GlobalizedRD;
2029 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2030 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002031
2032 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 NVPTXPrePostActionTy(
2034 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2035 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2036 &MappedDeclsFields)
2037 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2038 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002039 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002040 auto &Rt =
2041 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2042 if (GlobalizedRD) {
2043 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2044 I->getSecond().GlobalRecord = GlobalizedRD;
2045 I->getSecond().MappedParams =
2046 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2047 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2048 for (const auto &Pair : MappedDeclsFields) {
2049 assert(Pair.getFirst()->isCanonicalDecl() &&
2050 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002051 Data.insert(std::make_pair(Pair.getFirst(),
2052 MappedVarData(Pair.getSecond(),
2053 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002054 }
2055 }
2056 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002057 }
2058 void Exit(CodeGenFunction &CGF) override {
2059 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2060 .emitGenericVarsEpilog(CGF);
2061 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002062 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2063 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002064 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2065 D, ThreadIDVar, InnermostKind, CodeGen);
2066 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2067 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002068 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002069 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002070
2071 return OutlinedFun;
2072}
2073
Alexey Bataevc99042b2018-03-15 18:10:54 +00002074void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002075 SourceLocation Loc,
2076 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002077 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2078 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002079 return;
2080
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081 CGBuilderTy &Bld = CGF.Builder;
2082
2083 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2084 if (I == FunctionGlobalizedDecls.end())
2085 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002086 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002087 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002088 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002089
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002090 // Recover pointer to this function's global record. The runtime will
2091 // handle the specifics of the allocation of the memory.
2092 // Use actual memory size of the record including the padding
2093 // for alignment purposes.
2094 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002095 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002096 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002097 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002098 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002099
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002100 llvm::PointerType *GlobalRecPtrTy =
2101 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002102 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002103 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002104 if (!IsInTTDRegion &&
2105 (WithSPMDCheck ||
2106 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002107 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2108 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2109 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2111 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2112 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2113 llvm::Value *PL = CGF.EmitRuntimeCall(
2114 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2115 {RTLoc, ThreadID});
2116 IsTTD = Bld.CreateIsNull(PL);
2117 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002118 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2119 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2120 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2121 // There is no need to emit line number for unconditional branch.
2122 (void)ApplyDebugLocation::CreateEmpty(CGF);
2123 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002124 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2125 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002126 CGF.EmitBranch(ExitBB);
2127 // There is no need to emit line number for unconditional branch.
2128 (void)ApplyDebugLocation::CreateEmpty(CGF);
2129 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002130 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2131 if (const RecordDecl *SecGlobalizedVarsRecord =
2132 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2133 SecGlobalRecTy =
2134 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2135
2136 // Recover pointer to this function's global record. The runtime will
2137 // handle the specifics of the allocation of the memory.
2138 // Use actual memory size of the record including the padding
2139 // for alignment purposes.
2140 unsigned Alignment =
2141 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2142 unsigned GlobalRecordSize =
2143 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2144 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2145 Size = Bld.CreateSelect(
2146 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2147 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002148 // TODO: allow the usage of shared memory to be controlled by
2149 // the user, for now, default to global.
2150 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002151 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002152 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2153 createNVPTXRuntimeFunction(
2154 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2155 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002156 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002157 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002158 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002159 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002160 /*NumReservedValues=*/2, "_select_stack");
2161 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2162 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2163 GlobalRecCastAddr = Phi;
2164 I->getSecond().GlobalRecordAddr = Phi;
2165 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002166 } else if (IsInTTDRegion) {
2167 assert(GlobalizedRecords.back().Records.size() < 2 &&
2168 "Expected less than 2 globalized records: one for target and one "
2169 "for teams.");
2170 unsigned Offset = 0;
2171 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2172 QualType RDTy = CGM.getContext().getRecordType(RD);
2173 unsigned Alignment =
2174 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2175 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2176 Offset =
2177 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2178 }
2179 unsigned Alignment =
2180 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2181 Offset = llvm::alignTo(Offset, Alignment);
2182 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2183 ++GlobalizedRecords.back().RegionCounter;
2184 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002185 assert(KernelStaticGlobalized &&
2186 "Kernel static pointer must be initialized already.");
2187 auto *UseSharedMemory = new llvm::GlobalVariable(
2188 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2189 llvm::GlobalValue::InternalLinkage, nullptr,
2190 "_openmp_static_kernel$is_shared");
2191 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2192 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2193 /*DestWidth=*/16, /*Signed=*/0);
2194 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2195 Address(UseSharedMemory,
2196 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2197 /*Volatile=*/false, Int16Ty, Loc);
2198 auto *StaticGlobalized = new llvm::GlobalVariable(
2199 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002200 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002201 auto *RecSize = new llvm::GlobalVariable(
2202 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2203 llvm::GlobalValue::InternalLinkage, nullptr,
2204 "_openmp_static_kernel$size");
2205 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2206 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002207 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 CGM.getContext().getSizeType(), Loc);
2209 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2210 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002211 llvm::Value *GlobalRecordSizeArg[] = {StaticGlobalized, Ld,
2212 IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002213 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2214 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2215 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002216 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002217 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002218 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2219 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 }
2221 assert(KernelStaticGlobalized && "Global address must be set already.");
2222 Address FrameAddr = CGF.EmitLoadOfPointer(
2223 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2224 CGM.getContext()
2225 .getPointerType(CGM.getContext().VoidPtrTy)
2226 .castAs<PointerType>());
2227 llvm::Value *GlobalRecValue =
2228 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2229 .getPointer();
2230 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2231 I->getSecond().IsInSPMDModeFlag = nullptr;
2232 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2233 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002234 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002235 // TODO: allow the usage of shared memory to be controlled by
2236 // the user, for now, default to global.
2237 llvm::Value *GlobalRecordSizeArg[] = {
2238 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2239 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002240 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2241 createNVPTXRuntimeFunction(
2242 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2243 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002244 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002245 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002246 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2247 I->getSecond().IsInSPMDModeFlag = nullptr;
2248 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002249 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002250 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002251
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002252 // Emit the "global alloca" which is a GEP from the global declaration
2253 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002254 LValue SecBase;
2255 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2256 if (IsTTD) {
2257 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2258 llvm::PointerType *SecGlobalRecPtrTy =
2259 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2260 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2261 Bld.CreatePointerBitCastOrAddrSpaceCast(
2262 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2263 SecGlobalRecTy);
2264 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002265 for (auto &Rec : I->getSecond().LocalVarData) {
2266 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2267 llvm::Value *ParValue;
2268 if (EscapedParam) {
2269 const auto *VD = cast<VarDecl>(Rec.first);
2270 LValue ParLVal =
2271 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2272 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2273 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002274 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2275 // Emit VarAddr basing on lane-id if required.
2276 QualType VarTy;
2277 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002278 VarTy = Rec.second.FD->getType();
2279 } else {
2280 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2281 VarAddr.getAddress().getPointer(),
2282 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002283 VarTy =
2284 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002285 VarAddr = CGF.MakeAddrLValue(
2286 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2287 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002288 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002289 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002290 if (!IsInTTDRegion &&
2291 (WithSPMDCheck ||
2292 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002293 assert(I->getSecond().IsInSPMDModeFlag &&
2294 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002295 if (IsTTD) {
2296 assert(SecIt->second.IsOnePerTeam &&
2297 "Secondary glob data must be one per team.");
2298 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2299 VarAddr.setAddress(
2300 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2301 VarAddr.getPointer()),
2302 VarAddr.getAlignment()));
2303 Rec.second.PrivateAddr = VarAddr.getAddress();
2304 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 Address GlobalPtr = Rec.second.PrivateAddr;
2306 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2307 Rec.second.PrivateAddr = Address(
2308 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2309 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2310 LocalAddr.getAlignment());
2311 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002312 if (EscapedParam) {
2313 const auto *VD = cast<VarDecl>(Rec.first);
2314 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2315 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2316 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002317 if (IsTTD)
2318 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002319 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002320 }
2321 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2322 // Recover pointer to this function's global record. The runtime will
2323 // handle the specifics of the allocation of the memory.
2324 // Use actual memory size of the record including the padding
2325 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002326 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002327 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2328 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2329 Size = Bld.CreateNUWAdd(
2330 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2331 llvm::Value *AlignVal =
2332 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2333 Size = Bld.CreateUDiv(Size, AlignVal);
2334 Size = Bld.CreateNUWMul(Size, AlignVal);
2335 // TODO: allow the usage of shared memory to be controlled by
2336 // the user, for now, default to global.
2337 llvm::Value *GlobalRecordSizeArg[] = {
2338 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2339 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002340 createNVPTXRuntimeFunction(
2341 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002342 GlobalRecordSizeArg);
2343 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2344 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2345 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2346 CGM.getContext().getDeclAlign(VD),
2347 AlignmentSource::Decl);
2348 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2349 Base.getAddress());
2350 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002351 }
2352 I->getSecond().MappedParams->apply(CGF);
2353}
2354
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002355void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2356 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002357 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2358 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002359 return;
2360
Alexey Bataevc99042b2018-03-15 18:10:54 +00002361 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002362 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002363 I->getSecond().MappedParams->restore(CGF);
2364 if (!CGF.HaveInsertPoint())
2365 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002366 for (llvm::Value *Addr :
2367 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2368 CGF.EmitRuntimeCall(
2369 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2370 Addr);
2371 }
2372 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002373 if (!IsInTTDRegion &&
2374 (WithSPMDCheck ||
2375 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002376 CGBuilderTy &Bld = CGF.Builder;
2377 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2378 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2379 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2380 // There is no need to emit line number for unconditional branch.
2381 (void)ApplyDebugLocation::CreateEmpty(CGF);
2382 CGF.EmitBlock(NonSPMDBB);
2383 CGF.EmitRuntimeCall(
2384 createNVPTXRuntimeFunction(
2385 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2386 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2387 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002388 } else if (IsInTTDRegion) {
2389 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2390 "region counter must be > 0.");
2391 --GlobalizedRecords.back().RegionCounter;
2392 // Emit the restore function only in the target region.
2393 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002394 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2395 /*DestWidth=*/16, /*Signed=*/0);
2396 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2397 Address(GlobalizedRecords.back().UseSharedMemory,
2398 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2399 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataeve4090182018-11-02 14:54:07 +00002400 CGF.EmitRuntimeCall(
2401 createNVPTXRuntimeFunction(
2402 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002403 IsInSharedMemory);
Alexey Bataeve4090182018-11-02 14:54:07 +00002404 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002405 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002406 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2407 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2408 I->getSecond().GlobalRecordAddr);
2409 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002410 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002411 }
2412}
2413
Carlo Bertollic6872252016-04-04 15:55:02 +00002414void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2415 const OMPExecutableDirective &D,
2416 SourceLocation Loc,
2417 llvm::Value *OutlinedFn,
2418 ArrayRef<llvm::Value *> CapturedVars) {
2419 if (!CGF.HaveInsertPoint())
2420 return;
2421
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002422 Address ZeroAddr = CGF.CreateMemTemp(
2423 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2424 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002425 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2426 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002427 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002428 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2429 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002430 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002431}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002432
2433void CGOpenMPRuntimeNVPTX::emitParallelCall(
2434 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2435 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2436 if (!CGF.HaveInsertPoint())
2437 return;
2438
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002439 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002440 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002441 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002442 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002443}
2444
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002445void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002446 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2447 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2448 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002449
2450 // Force inline this outlined function at its call site.
2451 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2452
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002453 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2454 /*DestWidth=*/32, /*Signed=*/1),
2455 ".zero.addr");
2456 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002457 // ThreadId for serialized parallels is 0.
2458 Address ThreadIDAddr = ZeroAddr;
2459 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002460 CodeGenFunction &CGF, PrePostActionTy &Action) {
2461 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002462
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002463 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2464 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2465 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2466 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2467 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2468 };
2469 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2470 PrePostActionTy &) {
2471
2472 RegionCodeGenTy RCG(CodeGen);
2473 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2474 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2475 llvm::Value *Args[] = {RTLoc, ThreadID};
2476
2477 NVPTXActionTy Action(
2478 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2479 Args,
2480 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2481 Args);
2482 RCG.setAction(Action);
2483 RCG(CGF);
2484 };
2485
2486 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2487 PrePostActionTy &Action) {
2488 CGBuilderTy &Bld = CGF.Builder;
2489 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2490 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002491 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2492
2493 // Prepare for parallel region. Indicate the outlined function.
2494 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002495 CGF.EmitRuntimeCall(
2496 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2497 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002498
2499 // Create a private scope that will globalize the arguments
2500 // passed from the outside of the target region.
2501 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2502
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002503 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002504 if (!CapturedVars.empty()) {
2505 // Prepare for parallel region. Indicate the outlined function.
2506 Address SharedArgs =
2507 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2508 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2509
2510 llvm::Value *DataSharingArgs[] = {
2511 SharedArgsPtr,
2512 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2513 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2514 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2515 DataSharingArgs);
2516
2517 // Store variable address in a list of references to pass to workers.
2518 unsigned Idx = 0;
2519 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002520 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2521 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2522 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002523 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002524 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2525 CGF.getPointerSize());
2526 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002527 if (V->getType()->isIntegerTy())
2528 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2529 else
2530 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002531 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2532 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002533 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002534 }
2535 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002536
2537 // Activate workers. This barrier is used by the master to signal
2538 // work for the workers.
2539 syncCTAThreads(CGF);
2540
2541 // OpenMP [2.5, Parallel Construct, p.49]
2542 // There is an implied barrier at the end of a parallel region. After the
2543 // end of a parallel region, only the master thread of the team resumes
2544 // execution of the enclosing task region.
2545 //
2546 // The master waits at this barrier until all workers are done.
2547 syncCTAThreads(CGF);
2548
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002549 if (!CapturedVars.empty())
2550 CGF.EmitRuntimeCall(
2551 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2552
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002553 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002554 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002555 };
2556
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002557 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2558 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002559 if (IsInParallelRegion) {
2560 SeqGen(CGF, Action);
2561 } else if (IsInTargetMasterThreadRegion) {
2562 L0ParallelGen(CGF, Action);
2563 } else {
2564 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002565 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002566 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002567 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002568 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002569 // }
2570 CGBuilderTy &Bld = CGF.Builder;
2571 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002572 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2573 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002574 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002575 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2576 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002577 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002578 // There is no need to emit line number for unconditional branch.
2579 (void)ApplyDebugLocation::CreateEmpty(CGF);
2580 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002581 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2582 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2583 llvm::Value *PL = CGF.EmitRuntimeCall(
2584 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2585 {RTLoc, ThreadID});
2586 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002587 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002588 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002589 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002590 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002591 // There is no need to emit line number for unconditional branch.
2592 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002593 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002594 L0ParallelGen(CGF, Action);
2595 CGF.EmitBranch(ExitBB);
2596 // There is no need to emit line number for unconditional branch.
2597 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002598 // Emit the continuation block for code after the if.
2599 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2600 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002601 };
2602
Alexey Bataev9ff80832018-04-16 20:16:21 +00002603 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002604 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002605 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002606 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002607 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002608 ThenRCG(CGF);
2609 }
2610}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002611
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002612void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002613 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2614 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2615 // Just call the outlined function to execute the parallel region.
2616 // OutlinedFn(&GTid, &zero, CapturedStruct);
2617 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002618 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002619
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002620 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2621 /*DestWidth=*/32, /*Signed=*/1),
2622 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002623 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002624 // ThreadId for serialized parallels is 0.
2625 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002626 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002627 &ThreadIDAddr](CodeGenFunction &CGF,
2628 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002629 Action.Enter(CGF);
2630
2631 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2632 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2633 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2634 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2635 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2636 };
2637 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2638 PrePostActionTy &) {
2639
2640 RegionCodeGenTy RCG(CodeGen);
2641 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2642 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2643 llvm::Value *Args[] = {RTLoc, ThreadID};
2644
2645 NVPTXActionTy Action(
2646 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2647 Args,
2648 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2649 Args);
2650 RCG.setAction(Action);
2651 RCG(CGF);
2652 };
2653
2654 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002655 // In the worker need to use the real thread id.
2656 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002657 RegionCodeGenTy RCG(CodeGen);
2658 RCG(CGF);
2659 } else {
2660 // If we are not in the target region, it is definitely L2 parallelism or
2661 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2662 // need to check for orphaned directives.
2663 RegionCodeGenTy RCG(SeqGen);
2664 RCG(CGF);
2665 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002666}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002667
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002668void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2669 SourceLocation Loc,
2670 OpenMPDirectiveKind Kind, bool,
2671 bool) {
2672 // Always emit simple barriers!
2673 if (!CGF.HaveInsertPoint())
2674 return;
2675 // Build call __kmpc_cancel_barrier(loc, thread_id);
2676 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2677 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2678 getThreadID(CGF, Loc)};
2679 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2680}
2681
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002682void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2683 CodeGenFunction &CGF, StringRef CriticalName,
2684 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2685 const Expr *Hint) {
2686 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2687 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2688 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2689 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2690 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2691
2692 // Fetch team-local id of the thread.
2693 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2694
2695 // Get the width of the team.
2696 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2697
2698 // Initialize the counter variable for the loop.
2699 QualType Int32Ty =
2700 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2701 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2702 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2703 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2704 /*isInit=*/true);
2705
2706 // Block checks if loop counter exceeds upper bound.
2707 CGF.EmitBlock(LoopBB);
2708 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2709 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2710 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2711
2712 // Block tests which single thread should execute region, and which threads
2713 // should go straight to synchronisation point.
2714 CGF.EmitBlock(TestBB);
2715 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2716 llvm::Value *CmpThreadToCounter =
2717 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2718 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2719
2720 // Block emits the body of the critical region.
2721 CGF.EmitBlock(BodyBB);
2722
2723 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002724 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2725 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002726
2727 // After the body surrounded by the critical region, the single executing
2728 // thread will jump to the synchronisation point.
2729 // Block waits for all threads in current team to finish then increments the
2730 // counter variable and returns to the loop.
2731 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002732 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2733 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002734
2735 llvm::Value *IncCounterVal =
2736 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2737 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2738 CGF.EmitBranch(LoopBB);
2739
2740 // Block that is reached when all threads in the team complete the region.
2741 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2742}
2743
Alexey Bataevb2575932018-01-04 20:18:55 +00002744/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002745static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2746 QualType ValTy, QualType CastTy,
2747 SourceLocation Loc) {
2748 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2749 "Cast type must sized.");
2750 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2751 "Val type must sized.");
2752 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2753 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002754 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002755 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2756 CGF.getContext().getTypeSizeInChars(CastTy))
2757 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2758 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2759 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2760 CastTy->hasSignedIntegerRepresentation());
2761 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002762 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2763 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002764 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2765 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002766}
2767
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002768/// This function creates calls to one of two shuffle functions to copy
2769/// variables between lanes in a warp.
2770static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002771 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002772 QualType ElemType,
2773 llvm::Value *Offset,
2774 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002775 CodeGenModule &CGM = CGF.CGM;
2776 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002777 CGOpenMPRuntimeNVPTX &RT =
2778 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2779
Alexey Bataeva453f362018-03-19 17:53:56 +00002780 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2781 assert(Size.getQuantity() <= 8 &&
2782 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002783
Alexey Bataeva453f362018-03-19 17:53:56 +00002784 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002785 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2786 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2787
2788 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002789 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2790 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2791 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002792 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002793 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002794
Alexey Bataev9ff80832018-04-16 20:16:21 +00002795 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2796 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002797
Alexey Bataeva453f362018-03-19 17:53:56 +00002798 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799}
2800
Alexey Bataev12c62902018-06-22 19:10:38 +00002801static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2802 Address DestAddr, QualType ElemType,
2803 llvm::Value *Offset, SourceLocation Loc) {
2804 CGBuilderTy &Bld = CGF.Builder;
2805
2806 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2807 // Create the loop over the big sized data.
2808 // ptr = (void*)Elem;
2809 // ptrEnd = (void*) Elem + 1;
2810 // Step = 8;
2811 // while (ptr + Step < ptrEnd)
2812 // shuffle((int64_t)*ptr);
2813 // Step = 4;
2814 // while (ptr + Step < ptrEnd)
2815 // shuffle((int32_t)*ptr);
2816 // ...
2817 Address ElemPtr = DestAddr;
2818 Address Ptr = SrcAddr;
2819 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2820 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2821 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2822 if (Size < CharUnits::fromQuantity(IntSize))
2823 continue;
2824 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2825 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2826 /*Signed=*/1);
2827 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2828 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2829 ElemPtr =
2830 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2831 if (Size.getQuantity() / IntSize > 1) {
2832 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2833 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2834 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2835 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2836 CGF.EmitBlock(PreCondBB);
2837 llvm::PHINode *PhiSrc =
2838 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2839 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2840 llvm::PHINode *PhiDest =
2841 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2842 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2843 Ptr = Address(PhiSrc, Ptr.getAlignment());
2844 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2845 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2846 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2847 Ptr.getPointer(), CGF.VoidPtrTy));
2848 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2849 ThenBB, ExitBB);
2850 CGF.EmitBlock(ThenBB);
2851 llvm::Value *Res = createRuntimeShuffleFunction(
2852 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2853 IntType, Offset, Loc);
2854 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002855 Address LocalPtr =
2856 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2857 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002858 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002859 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2860 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002861 CGF.EmitBranch(PreCondBB);
2862 CGF.EmitBlock(ExitBB);
2863 } else {
2864 llvm::Value *Res = createRuntimeShuffleFunction(
2865 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2866 IntType, Offset, Loc);
2867 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2868 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2869 ElemPtr =
2870 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2871 }
2872 Size = Size % IntSize;
2873 }
2874}
2875
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002876namespace {
2877enum CopyAction : unsigned {
2878 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2879 // the warp using shuffle instructions.
2880 RemoteLaneToThread,
2881 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2882 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002883 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2884 ThreadToScratchpad,
2885 // ScratchpadToThread: Copy from a scratchpad array in global memory
2886 // containing team-reduced data to a thread's stack.
2887 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002888};
2889} // namespace
2890
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002891struct CopyOptionsTy {
2892 llvm::Value *RemoteLaneOffset;
2893 llvm::Value *ScratchpadIndex;
2894 llvm::Value *ScratchpadWidth;
2895};
2896
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002897/// Emit instructions to copy a Reduce list, which contains partially
2898/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002899static void emitReductionListCopy(
2900 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2901 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2902 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002903
Alexey Bataev9ff80832018-04-16 20:16:21 +00002904 CodeGenModule &CGM = CGF.CGM;
2905 ASTContext &C = CGM.getContext();
2906 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002907
Alexey Bataev9ff80832018-04-16 20:16:21 +00002908 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2909 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2910 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002911
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002912 // Iterates, element-by-element, through the source Reduce list and
2913 // make a copy.
2914 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002915 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002916 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917 Address SrcElementAddr = Address::invalid();
2918 Address DestElementAddr = Address::invalid();
2919 Address DestElementPtrAddr = Address::invalid();
2920 // Should we shuffle in an element from a remote lane?
2921 bool ShuffleInElement = false;
2922 // Set to true to update the pointer in the dest Reduce list to a
2923 // newly created element.
2924 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002925 // Increment the src or dest pointer to the scratchpad, for each
2926 // new element.
2927 bool IncrScratchpadSrc = false;
2928 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929
2930 switch (Action) {
2931 case RemoteLaneToThread: {
2932 // Step 1.1: Get the address for the src element in the Reduce list.
2933 Address SrcElementPtrAddr =
2934 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002935 SrcElementAddr = CGF.EmitLoadOfPointer(
2936 SrcElementPtrAddr,
2937 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002938
2939 // Step 1.2: Create a temporary to store the element in the destination
2940 // Reduce list.
2941 DestElementPtrAddr =
2942 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2943 DestElementAddr =
2944 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2945 ShuffleInElement = true;
2946 UpdateDestListPtr = true;
2947 break;
2948 }
2949 case ThreadCopy: {
2950 // Step 1.1: Get the address for the src element in the Reduce list.
2951 Address SrcElementPtrAddr =
2952 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002953 SrcElementAddr = CGF.EmitLoadOfPointer(
2954 SrcElementPtrAddr,
2955 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002956
2957 // Step 1.2: Get the address for dest element. The destination
2958 // element has already been created on the thread's stack.
2959 DestElementPtrAddr =
2960 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002961 DestElementAddr = CGF.EmitLoadOfPointer(
2962 DestElementPtrAddr,
2963 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002964 break;
2965 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002966 case ThreadToScratchpad: {
2967 // Step 1.1: Get the address for the src element in the Reduce list.
2968 Address SrcElementPtrAddr =
2969 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002970 SrcElementAddr = CGF.EmitLoadOfPointer(
2971 SrcElementPtrAddr,
2972 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002973
2974 // Step 1.2: Get the address for dest element:
2975 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002976 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002977 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002978 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002979 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002980 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002981 ScratchPadElemAbsolutePtrVal =
2982 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002983 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2984 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002985 IncrScratchpadDest = true;
2986 break;
2987 }
2988 case ScratchpadToThread: {
2989 // Step 1.1: Get the address for the src element in the scratchpad.
2990 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002991 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002992 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002993 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002994 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002995 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002996 ScratchPadElemAbsolutePtrVal =
2997 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2998 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2999 C.getTypeAlignInChars(Private->getType()));
3000 IncrScratchpadSrc = true;
3001
3002 // Step 1.2: Create a temporary to store the element in the destination
3003 // Reduce list.
3004 DestElementPtrAddr =
3005 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3006 DestElementAddr =
3007 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3008 UpdateDestListPtr = true;
3009 break;
3010 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003011 }
3012
3013 // Regardless of src and dest of copy, we emit the load of src
3014 // element as this is required in all directions
3015 SrcElementAddr = Bld.CreateElementBitCast(
3016 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003017 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3018 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003019
3020 // Now that all active lanes have read the element in the
3021 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003022 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003023 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3024 RemoteLaneOffset, Private->getExprLoc());
3025 } else {
3026 if (Private->getType()->isScalarType()) {
3027 llvm::Value *Elem =
3028 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3029 Private->getType(), Private->getExprLoc());
3030 // Store the source element value to the dest element address.
3031 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3032 Private->getType());
3033 } else {
3034 CGF.EmitAggregateCopy(
3035 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3036 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3037 Private->getType(), AggValueSlot::DoesNotOverlap);
3038 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003039 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003040
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003041 // Step 3.1: Modify reference in dest Reduce list as needed.
3042 // Modifying the reference in Reduce list to point to the newly
3043 // created element. The element is live in the current function
3044 // scope and that of functions it invokes (i.e., reduce_function).
3045 // RemoteReduceData[i] = (void*)&RemoteElem
3046 if (UpdateDestListPtr) {
3047 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3048 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3049 DestElementPtrAddr, /*Volatile=*/false,
3050 C.VoidPtrTy);
3051 }
3052
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003053 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3054 // address of the next element in scratchpad memory, unless we're currently
3055 // processing the last one. Memory alignment is also taken care of here.
3056 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3057 llvm::Value *ScratchpadBasePtr =
3058 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003059 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3060 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003061 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003062 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003063
3064 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003065 ScratchpadBasePtr = Bld.CreateNUWSub(
3066 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3067 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003068 ScratchpadBasePtr,
3069 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003070 ScratchpadBasePtr = Bld.CreateNUWAdd(
3071 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3072 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003073 ScratchpadBasePtr,
3074 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3075
3076 if (IncrScratchpadDest)
3077 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3078 else /* IncrScratchpadSrc = true */
3079 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3080 }
3081
Alexey Bataev9ff80832018-04-16 20:16:21 +00003082 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003083 }
3084}
3085
3086/// This function emits a helper that gathers Reduce lists from the first
3087/// lane of every active warp to lanes in the first warp.
3088///
3089/// void inter_warp_copy_func(void* reduce_data, num_warps)
3090/// shared smem[warp_size];
3091/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003092/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003093/// If (I am the first lane in each warp)
3094/// Copy my local D to smem[warp_id]
3095/// sync
3096/// if (I am the first warp)
3097/// Copy smem[thread_id] to my local D
3098/// sync
3099static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3100 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003101 QualType ReductionArrayTy,
3102 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003103 ASTContext &C = CGM.getContext();
3104 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003105
3106 // ReduceList: thread local Reduce list.
3107 // At the stage of the computation when this function is called, partially
3108 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003109 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3110 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003111 // NumWarps: number of warps active in the parallel region. This could
3112 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003113 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003114 C.getIntTypeForBitwidth(32, /* Signed */ true),
3115 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003116 FunctionArgList Args;
3117 Args.push_back(&ReduceListArg);
3118 Args.push_back(&NumWarpsArg);
3119
Alexey Bataev9ff80832018-04-16 20:16:21 +00003120 const CGFunctionInfo &CGFI =
3121 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003122 auto *Fn = llvm::Function::Create(
3123 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3124 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003125 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003126 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003127 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003128 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003129
Alexey Bataev9ff80832018-04-16 20:16:21 +00003130 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131
3132 // This array is used as a medium to transfer, one reduce element at a time,
3133 // the data from the first lane of every warp to lanes in the first warp
3134 // in order to perform the final step of a reduction in a parallel region
3135 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3136 // for reduced latency, as well as to have a distinct copy for concurrently
3137 // executing target regions. The array is declared with common linkage so
3138 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003139 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003140 "__openmp_nvptx_data_transfer_temporary_storage";
3141 llvm::GlobalVariable *TransferMedium =
3142 M.getGlobalVariable(TransferMediumName);
3143 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003144 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3146 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003147 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003148 llvm::Constant::getNullValue(Ty), TransferMediumName,
3149 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3150 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003151 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003152 }
3153
3154 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003155 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003157 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003159 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160
3161 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3162 Address LocalReduceList(
3163 Bld.CreatePointerBitCastOrAddrSpaceCast(
3164 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003165 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3167 CGF.getPointerAlign());
3168
3169 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003170 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171 //
3172 // Warp master copies reduce element to transfer medium in __shared__
3173 // memory.
3174 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003175 unsigned RealTySize =
3176 C.getTypeSizeInChars(Private->getType())
3177 .alignTo(C.getTypeAlignInChars(Private->getType()))
3178 .getQuantity();
3179 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3180 unsigned NumIters = RealTySize / TySize;
3181 if (NumIters == 0)
3182 continue;
3183 QualType CType = C.getIntTypeForBitwidth(
3184 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3185 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3186 CharUnits Align = CharUnits::fromQuantity(TySize);
3187 llvm::Value *Cnt = nullptr;
3188 Address CntAddr = Address::invalid();
3189 llvm::BasicBlock *PrecondBB = nullptr;
3190 llvm::BasicBlock *ExitBB = nullptr;
3191 if (NumIters > 1) {
3192 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3193 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3194 /*Volatile=*/false, C.IntTy);
3195 PrecondBB = CGF.createBasicBlock("precond");
3196 ExitBB = CGF.createBasicBlock("exit");
3197 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3198 // There is no need to emit line number for unconditional branch.
3199 (void)ApplyDebugLocation::CreateEmpty(CGF);
3200 CGF.EmitBlock(PrecondBB);
3201 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3202 llvm::Value *Cmp =
3203 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3204 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3205 CGF.EmitBlock(BodyBB);
3206 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003207 // kmpc_barrier.
3208 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3209 /*EmitChecks=*/false,
3210 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003211 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3212 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3213 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003214
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003215 // if (lane_id == 0)
3216 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3217 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3218 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003219
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003220 // Reduce element = LocalReduceList[i]
3221 Address ElemPtrPtrAddr =
3222 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3223 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3224 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3225 // elemptr = ((CopyType*)(elemptrptr)) + I
3226 Address ElemPtr = Address(ElemPtrPtr, Align);
3227 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3228 if (NumIters > 1) {
3229 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3230 ElemPtr.getAlignment());
3231 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003232
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003233 // Get pointer to location in transfer medium.
3234 // MediumPtr = &medium[warp_id]
3235 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3236 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3237 Address MediumPtr(MediumPtrVal, Align);
3238 // Casting to actual data type.
3239 // MediumPtr = (CopyType*)MediumPtrAddr;
3240 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 // elem = *elemptr
3243 //*MediumPtr = elem
3244 llvm::Value *Elem =
3245 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003246 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003247 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003248
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003249 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 CGF.EmitBlock(ElseBB);
3252 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003253
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003254 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003255
Alexey Bataevae51b962018-12-14 21:00:58 +00003256 // kmpc_barrier.
3257 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3258 /*EmitChecks=*/false,
3259 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003260
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003261 //
3262 // Warp 0 copies reduce element from transfer medium.
3263 //
3264 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3265 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3266 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267
Alexey Bataevae51b962018-12-14 21:00:58 +00003268 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3269 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3270 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3271
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003272 // Up to 32 threads in warp 0 are active.
3273 llvm::Value *IsActiveThread =
3274 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3275 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003277 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003278
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003279 // SrcMediumPtr = &medium[tid]
3280 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3281 TransferMedium,
3282 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3283 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3284 // SrcMediumVal = *SrcMediumPtr;
3285 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3288 Address TargetElemPtrPtr =
3289 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3290 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3291 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3292 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3293 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3294 if (NumIters > 1) {
3295 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3296 TargetElemPtr.getAlignment());
3297 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003298
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003299 // *TargetElemPtr = SrcMediumVal;
3300 llvm::Value *SrcMediumValue =
3301 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003302 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003303 CType);
3304 Bld.CreateBr(W0MergeBB);
3305
3306 CGF.EmitBlock(W0ElseBB);
3307 Bld.CreateBr(W0MergeBB);
3308
3309 CGF.EmitBlock(W0MergeBB);
3310
3311 // While warp 0 copies values from transfer medium, all other warps must
3312 // wait.
Alexey Bataevae51b962018-12-14 21:00:58 +00003313 // kmpc_barrier.
3314 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3315 /*EmitChecks=*/false,
3316 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003317 if (NumIters > 1) {
3318 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3319 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3320 CGF.EmitBranch(PrecondBB);
3321 (void)ApplyDebugLocation::CreateEmpty(CGF);
3322 CGF.EmitBlock(ExitBB);
3323 }
3324 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003325 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003326 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327 }
3328
3329 CGF.FinishFunction();
3330 return Fn;
3331}
3332
3333/// Emit a helper that reduces data across two OpenMP threads (lanes)
3334/// in the same warp. It uses shuffle instructions to copy over data from
3335/// a remote lane's stack. The reduction algorithm performed is specified
3336/// by the fourth parameter.
3337///
3338/// Algorithm Versions.
3339/// Full Warp Reduce (argument value 0):
3340/// This algorithm assumes that all 32 lanes are active and gathers
3341/// data from these 32 lanes, producing a single resultant value.
3342/// Contiguous Partial Warp Reduce (argument value 1):
3343/// This algorithm assumes that only a *contiguous* subset of lanes
3344/// are active. This happens for the last warp in a parallel region
3345/// when the user specified num_threads is not an integer multiple of
3346/// 32. This contiguous subset always starts with the zeroth lane.
3347/// Partial Warp Reduce (argument value 2):
3348/// This algorithm gathers data from any number of lanes at any position.
3349/// All reduced values are stored in the lowest possible lane. The set
3350/// of problems every algorithm addresses is a super set of those
3351/// addressable by algorithms with a lower version number. Overhead
3352/// increases as algorithm version increases.
3353///
3354/// Terminology
3355/// Reduce element:
3356/// Reduce element refers to the individual data field with primitive
3357/// data types to be combined and reduced across threads.
3358/// Reduce list:
3359/// Reduce list refers to a collection of local, thread-private
3360/// reduce elements.
3361/// Remote Reduce list:
3362/// Remote Reduce list refers to a collection of remote (relative to
3363/// the current thread) reduce elements.
3364///
3365/// We distinguish between three states of threads that are important to
3366/// the implementation of this function.
3367/// Alive threads:
3368/// Threads in a warp executing the SIMT instruction, as distinguished from
3369/// threads that are inactive due to divergent control flow.
3370/// Active threads:
3371/// The minimal set of threads that has to be alive upon entry to this
3372/// function. The computation is correct iff active threads are alive.
3373/// Some threads are alive but they are not active because they do not
3374/// contribute to the computation in any useful manner. Turning them off
3375/// may introduce control flow overheads without any tangible benefits.
3376/// Effective threads:
3377/// In order to comply with the argument requirements of the shuffle
3378/// function, we must keep all lanes holding data alive. But at most
3379/// half of them perform value aggregation; we refer to this half of
3380/// threads as effective. The other half is simply handing off their
3381/// data.
3382///
3383/// Procedure
3384/// Value shuffle:
3385/// In this step active threads transfer data from higher lane positions
3386/// in the warp to lower lane positions, creating Remote Reduce list.
3387/// Value aggregation:
3388/// In this step, effective threads combine their thread local Reduce list
3389/// with Remote Reduce list and store the result in the thread local
3390/// Reduce list.
3391/// Value copy:
3392/// In this step, we deal with the assumption made by algorithm 2
3393/// (i.e. contiguity assumption). When we have an odd number of lanes
3394/// active, say 2k+1, only k threads will be effective and therefore k
3395/// new values will be produced. However, the Reduce list owned by the
3396/// (2k+1)th thread is ignored in the value aggregation. Therefore
3397/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3398/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003399static llvm::Value *emitShuffleAndReduceFunction(
3400 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3401 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003402 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003403
3404 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003405 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3406 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003407 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003408 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3409 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003410 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003411 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3412 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003413 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003414 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3415 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003416 FunctionArgList Args;
3417 Args.push_back(&ReduceListArg);
3418 Args.push_back(&LaneIDArg);
3419 Args.push_back(&RemoteLaneOffsetArg);
3420 Args.push_back(&AlgoVerArg);
3421
Alexey Bataev9ff80832018-04-16 20:16:21 +00003422 const CGFunctionInfo &CGFI =
3423 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003424 auto *Fn = llvm::Function::Create(
3425 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3426 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003427 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003428 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003429 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003430 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003431
Alexey Bataev9ff80832018-04-16 20:16:21 +00003432 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003433
3434 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3435 Address LocalReduceList(
3436 Bld.CreatePointerBitCastOrAddrSpaceCast(
3437 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3438 C.VoidPtrTy, SourceLocation()),
3439 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3440 CGF.getPointerAlign());
3441
3442 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3443 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3444 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3445
3446 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3447 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3448 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3449
3450 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3451 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3452 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3453
3454 // Create a local thread-private variable to host the Reduce list
3455 // from a remote lane.
3456 Address RemoteReduceList =
3457 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3458
3459 // This loop iterates through the list of reduce elements and copies,
3460 // element by element, from a remote lane in the warp to RemoteReduceList,
3461 // hosted on the thread's stack.
3462 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3463 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003464 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3465 /*ScratchpadIndex=*/nullptr,
3466 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003467
3468 // The actions to be performed on the Remote Reduce list is dependent
3469 // on the algorithm version.
3470 //
3471 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3472 // LaneId % 2 == 0 && Offset > 0):
3473 // do the reduction value aggregation
3474 //
3475 // The thread local variable Reduce list is mutated in place to host the
3476 // reduced data, which is the aggregated value produced from local and
3477 // remote lanes.
3478 //
3479 // Note that AlgoVer is expected to be a constant integer known at compile
3480 // time.
3481 // When AlgoVer==0, the first conjunction evaluates to true, making
3482 // the entire predicate true during compile time.
3483 // When AlgoVer==1, the second conjunction has only the second part to be
3484 // evaluated during runtime. Other conjunctions evaluates to false
3485 // during compile time.
3486 // When AlgoVer==2, the third conjunction has only the second part to be
3487 // evaluated during runtime. Other conjunctions evaluates to false
3488 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003489 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003490
Alexey Bataev9ff80832018-04-16 20:16:21 +00003491 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3492 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003493 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3494
Alexey Bataev9ff80832018-04-16 20:16:21 +00003495 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3496 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3497 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003498 CondAlgo2 = Bld.CreateAnd(
3499 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3500
Alexey Bataev9ff80832018-04-16 20:16:21 +00003501 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3503
3504 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3505 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3506 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3507 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3508
3509 CGF.EmitBlock(ThenBB);
3510 // reduce_function(LocalReduceList, RemoteReduceList)
3511 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3512 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3513 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3514 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003515 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3516 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003517 Bld.CreateBr(MergeBB);
3518
3519 CGF.EmitBlock(ElseBB);
3520 Bld.CreateBr(MergeBB);
3521
3522 CGF.EmitBlock(MergeBB);
3523
3524 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3525 // Reduce list.
3526 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003527 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003528 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3529
3530 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3531 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3532 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3533 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3534
3535 CGF.EmitBlock(CpyThenBB);
3536 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3537 RemoteReduceList, LocalReduceList);
3538 Bld.CreateBr(CpyMergeBB);
3539
3540 CGF.EmitBlock(CpyElseBB);
3541 Bld.CreateBr(CpyMergeBB);
3542
3543 CGF.EmitBlock(CpyMergeBB);
3544
3545 CGF.FinishFunction();
3546 return Fn;
3547}
3548
3549///
3550/// Design of OpenMP reductions on the GPU
3551///
3552/// Consider a typical OpenMP program with one or more reduction
3553/// clauses:
3554///
3555/// float foo;
3556/// double bar;
3557/// #pragma omp target teams distribute parallel for \
3558/// reduction(+:foo) reduction(*:bar)
3559/// for (int i = 0; i < N; i++) {
3560/// foo += A[i]; bar *= B[i];
3561/// }
3562///
3563/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3564/// all teams. In our OpenMP implementation on the NVPTX device an
3565/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3566/// within a team are mapped to CUDA threads within a threadblock.
3567/// Our goal is to efficiently aggregate values across all OpenMP
3568/// threads such that:
3569///
3570/// - the compiler and runtime are logically concise, and
3571/// - the reduction is performed efficiently in a hierarchical
3572/// manner as follows: within OpenMP threads in the same warp,
3573/// across warps in a threadblock, and finally across teams on
3574/// the NVPTX device.
3575///
3576/// Introduction to Decoupling
3577///
3578/// We would like to decouple the compiler and the runtime so that the
3579/// latter is ignorant of the reduction variables (number, data types)
3580/// and the reduction operators. This allows a simpler interface
3581/// and implementation while still attaining good performance.
3582///
3583/// Pseudocode for the aforementioned OpenMP program generated by the
3584/// compiler is as follows:
3585///
3586/// 1. Create private copies of reduction variables on each OpenMP
3587/// thread: 'foo_private', 'bar_private'
3588/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3589/// to it and writes the result in 'foo_private' and 'bar_private'
3590/// respectively.
3591/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3592/// and store the result on the team master:
3593///
3594/// __kmpc_nvptx_parallel_reduce_nowait(...,
3595/// reduceData, shuffleReduceFn, interWarpCpyFn)
3596///
3597/// where:
3598/// struct ReduceData {
3599/// double *foo;
3600/// double *bar;
3601/// } reduceData
3602/// reduceData.foo = &foo_private
3603/// reduceData.bar = &bar_private
3604///
3605/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3606/// auxiliary functions generated by the compiler that operate on
3607/// variables of type 'ReduceData'. They aid the runtime perform
3608/// algorithmic steps in a data agnostic manner.
3609///
3610/// 'shuffleReduceFn' is a pointer to a function that reduces data
3611/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3612/// same warp. It takes the following arguments as input:
3613///
3614/// a. variable of type 'ReduceData' on the calling lane,
3615/// b. its lane_id,
3616/// c. an offset relative to the current lane_id to generate a
3617/// remote_lane_id. The remote lane contains the second
3618/// variable of type 'ReduceData' that is to be reduced.
3619/// d. an algorithm version parameter determining which reduction
3620/// algorithm to use.
3621///
3622/// 'shuffleReduceFn' retrieves data from the remote lane using
3623/// efficient GPU shuffle intrinsics and reduces, using the
3624/// algorithm specified by the 4th parameter, the two operands
3625/// element-wise. The result is written to the first operand.
3626///
3627/// Different reduction algorithms are implemented in different
3628/// runtime functions, all calling 'shuffleReduceFn' to perform
3629/// the essential reduction step. Therefore, based on the 4th
3630/// parameter, this function behaves slightly differently to
3631/// cooperate with the runtime to ensure correctness under
3632/// different circumstances.
3633///
3634/// 'InterWarpCpyFn' is a pointer to a function that transfers
3635/// reduced variables across warps. It tunnels, through CUDA
3636/// shared memory, the thread-private data of type 'ReduceData'
3637/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003638/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3639/// The last team writes the global reduced value to memory.
3640///
3641/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3642/// reduceData, shuffleReduceFn, interWarpCpyFn,
3643/// scratchpadCopyFn, loadAndReduceFn)
3644///
3645/// 'scratchpadCopyFn' is a helper that stores reduced
3646/// data from the team master to a scratchpad array in
3647/// global memory.
3648///
3649/// 'loadAndReduceFn' is a helper that loads data from
3650/// the scratchpad array and reduces it with the input
3651/// operand.
3652///
3653/// These compiler generated functions hide address
3654/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003655/// 5. if ret == 1:
3656/// The team master of the last team stores the reduced
3657/// result to the globals in memory.
3658/// foo += reduceData.foo; bar *= reduceData.bar
3659///
3660///
3661/// Warp Reduction Algorithms
3662///
3663/// On the warp level, we have three algorithms implemented in the
3664/// OpenMP runtime depending on the number of active lanes:
3665///
3666/// Full Warp Reduction
3667///
3668/// The reduce algorithm within a warp where all lanes are active
3669/// is implemented in the runtime as follows:
3670///
3671/// full_warp_reduce(void *reduce_data,
3672/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3673/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3674/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3675/// }
3676///
3677/// The algorithm completes in log(2, WARPSIZE) steps.
3678///
3679/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3680/// not used therefore we save instructions by not retrieving lane_id
3681/// from the corresponding special registers. The 4th parameter, which
3682/// represents the version of the algorithm being used, is set to 0 to
3683/// signify full warp reduction.
3684///
3685/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3686///
3687/// #reduce_elem refers to an element in the local lane's data structure
3688/// #remote_elem is retrieved from a remote lane
3689/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3690/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3691///
3692/// Contiguous Partial Warp Reduction
3693///
3694/// This reduce algorithm is used within a warp where only the first
3695/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3696/// number of OpenMP threads in a parallel region is not a multiple of
3697/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3698///
3699/// void
3700/// contiguous_partial_reduce(void *reduce_data,
3701/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3702/// int size, int lane_id) {
3703/// int curr_size;
3704/// int offset;
3705/// curr_size = size;
3706/// mask = curr_size/2;
3707/// while (offset>0) {
3708/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3709/// curr_size = (curr_size+1)/2;
3710/// offset = curr_size/2;
3711/// }
3712/// }
3713///
3714/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3715///
3716/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3717/// if (lane_id < offset)
3718/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3719/// else
3720/// reduce_elem = remote_elem
3721///
3722/// This algorithm assumes that the data to be reduced are located in a
3723/// contiguous subset of lanes starting from the first. When there is
3724/// an odd number of active lanes, the data in the last lane is not
3725/// aggregated with any other lane's dat but is instead copied over.
3726///
3727/// Dispersed Partial Warp Reduction
3728///
3729/// This algorithm is used within a warp when any discontiguous subset of
3730/// lanes are active. It is used to implement the reduction operation
3731/// across lanes in an OpenMP simd region or in a nested parallel region.
3732///
3733/// void
3734/// dispersed_partial_reduce(void *reduce_data,
3735/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3736/// int size, remote_id;
3737/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3738/// do {
3739/// remote_id = next_active_lane_id_right_after_me();
3740/// # the above function returns 0 of no active lane
3741/// # is present right after the current lane.
3742/// size = number_of_active_lanes_in_this_warp();
3743/// logical_lane_id /= 2;
3744/// ShuffleReduceFn(reduce_data, logical_lane_id,
3745/// remote_id-1-threadIdx.x, 2);
3746/// } while (logical_lane_id % 2 == 0 && size > 1);
3747/// }
3748///
3749/// There is no assumption made about the initial state of the reduction.
3750/// Any number of lanes (>=1) could be active at any position. The reduction
3751/// result is returned in the first active lane.
3752///
3753/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3754///
3755/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3756/// if (lane_id % 2 == 0 && offset > 0)
3757/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3758/// else
3759/// reduce_elem = remote_elem
3760///
3761///
3762/// Intra-Team Reduction
3763///
3764/// This function, as implemented in the runtime call
3765/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3766/// threads in a team. It first reduces within a warp using the
3767/// aforementioned algorithms. We then proceed to gather all such
3768/// reduced values at the first warp.
3769///
3770/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3771/// data from each of the "warp master" (zeroth lane of each warp, where
3772/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3773/// a mathematical sense) the problem of reduction across warp masters in
3774/// a block to the problem of warp reduction.
3775///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003776///
3777/// Inter-Team Reduction
3778///
3779/// Once a team has reduced its data to a single value, it is stored in
3780/// a global scratchpad array. Since each team has a distinct slot, this
3781/// can be done without locking.
3782///
3783/// The last team to write to the scratchpad array proceeds to reduce the
3784/// scratchpad array. One or more workers in the last team use the helper
3785/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3786/// the k'th worker reduces every k'th element.
3787///
3788/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3789/// reduce across workers and compute a globally reduced value.
3790///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003791void CGOpenMPRuntimeNVPTX::emitReduction(
3792 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3793 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3794 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3795 if (!CGF.HaveInsertPoint())
3796 return;
3797
3798 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003799#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003800 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003801#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003802
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003803 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003804 assert(!TeamsReduction && !ParallelReduction &&
3805 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003806 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3807 ReductionOps, Options);
3808 return;
3809 }
3810
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003811 assert((TeamsReduction || ParallelReduction) &&
3812 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003813
Alexey Bataeva1166022018-11-27 21:24:54 +00003814 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003815 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003816 // or
3817 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003818 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003819
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003820 llvm::Value *Res;
3821 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003822 ASTContext &C = CGM.getContext();
3823 // 1. Build a list of reduction variables.
3824 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3825 auto Size = RHSExprs.size();
3826 for (const Expr *E : Privates) {
3827 if (E->getType()->isVariablyModifiedType())
3828 // Reserve place for array size.
3829 ++Size;
3830 }
3831 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3832 QualType ReductionArrayTy =
3833 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3834 /*IndexTypeQuals=*/0);
3835 Address ReductionList =
3836 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3837 auto IPriv = Privates.begin();
3838 unsigned Idx = 0;
3839 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3840 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3841 CGF.getPointerSize());
3842 CGF.Builder.CreateStore(
3843 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3844 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3845 Elem);
3846 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3847 // Store array size.
3848 ++Idx;
3849 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3850 CGF.getPointerSize());
3851 llvm::Value *Size = CGF.Builder.CreateIntCast(
3852 CGF.getVLASize(
3853 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3854 .NumElts,
3855 CGF.SizeTy, /*isSigned=*/false);
3856 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3857 Elem);
3858 }
3859 }
3860
3861 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3862 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3863 ReductionList.getPointer(), CGF.VoidPtrTy);
3864 llvm::Value *ReductionFn = emitReductionFunction(
3865 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3866 Privates, LHSExprs, RHSExprs, ReductionOps);
3867 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3868 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3869 llvm::Value *InterWarpCopyFn =
3870 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3871
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003872 llvm::Value *Args[] = {ThreadId,
3873 CGF.Builder.getInt32(RHSExprs.size()),
3874 ReductionArrayTySize,
3875 RL,
3876 ShuffleAndReduceFn,
3877 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003878
3879 Res = CGF.EmitRuntimeCall(
3880 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3881 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003882 } else {
3883 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003884 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3885 std::string Name = getName({"reduction"});
3886 llvm::Value *Lock = getCriticalRegionLock(Name);
3887 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003888 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003889 createNVPTXRuntimeFunction(
3890 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003891 Args);
3892 }
3893
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003894 // 5. Build if (res == 1)
3895 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3896 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3897 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3898 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3899 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003900
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003901 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003902 // thread in each team.
3903 // __kmpc_end_reduce{_nowait}(<gtid>);
3904 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003905 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003906
3907 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003908 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003909 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3910 auto IPriv = Privates.begin();
3911 auto ILHS = LHSExprs.begin();
3912 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003913 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003914 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3915 cast<DeclRefExpr>(*IRHS));
3916 ++IPriv;
3917 ++ILHS;
3918 ++IRHS;
3919 }
3920 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003921 if (ParallelReduction) {
3922 llvm::Value *EndArgs[] = {ThreadId};
3923 RegionCodeGenTy RCG(CodeGen);
3924 NVPTXActionTy Action(
3925 nullptr, llvm::None,
3926 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3927 EndArgs);
3928 RCG.setAction(Action);
3929 RCG(CGF);
3930 } else {
3931 assert(TeamsReduction && "expected teams reduction.");
3932 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3933 std::string Name = getName({"reduction"});
3934 llvm::Value *Lock = getCriticalRegionLock(Name);
3935 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3936 RegionCodeGenTy RCG(CodeGen);
3937 NVPTXActionTy Action(
3938 nullptr, llvm::None,
3939 createNVPTXRuntimeFunction(
3940 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3941 EndArgs);
3942 RCG.setAction(Action);
3943 RCG(CGF);
3944 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003945 // There is no need to emit line number for unconditional branch.
3946 (void)ApplyDebugLocation::CreateEmpty(CGF);
3947 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003948}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003949
3950const VarDecl *
3951CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3952 const VarDecl *NativeParam) const {
3953 if (!NativeParam->getType()->isReferenceType())
3954 return NativeParam;
3955 QualType ArgType = NativeParam->getType();
3956 QualifierCollector QC;
3957 const Type *NonQualTy = QC.strip(ArgType);
3958 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3959 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3960 if (Attr->getCaptureKind() == OMPC_map) {
3961 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3962 LangAS::opencl_global);
3963 }
3964 }
3965 ArgType = CGM.getContext().getPointerType(PointeeTy);
3966 QC.addRestrict();
3967 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003968 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003969 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003970 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003971 return ImplicitParamDecl::Create(
3972 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3973 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003974 return ParmVarDecl::Create(
3975 CGM.getContext(),
3976 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003977 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003978 NativeParam->getIdentifier(), ArgType,
3979 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003980}
3981
3982Address
3983CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3984 const VarDecl *NativeParam,
3985 const VarDecl *TargetParam) const {
3986 assert(NativeParam != TargetParam &&
3987 NativeParam->getType()->isReferenceType() &&
3988 "Native arg must not be the same as target arg.");
3989 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3990 QualType NativeParamType = NativeParam->getType();
3991 QualifierCollector QC;
3992 const Type *NonQualTy = QC.strip(NativeParamType);
3993 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3994 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003995 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003996 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003997 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003998 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003999 // First cast to generic.
4000 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4001 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4002 /*AddrSpace=*/0));
4003 // Cast from generic to native address space.
4004 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4005 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4006 NativePointeeAddrSpace));
4007 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4008 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004009 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004010 return NativeParamAddr;
4011}
4012
4013void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004014 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004015 ArrayRef<llvm::Value *> Args) const {
4016 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004017 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004018 auto *FnType =
4019 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4020 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004021 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4022 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4023 break;
4024 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004025 llvm::Type *TargetType = FnType->getParamType(I);
4026 llvm::Value *NativeArg = Args[I];
4027 if (!TargetType->isPointerTy()) {
4028 TargetArgs.emplace_back(NativeArg);
4029 continue;
4030 }
4031 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004032 NativeArg,
4033 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004034 TargetArgs.emplace_back(
4035 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4036 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004037 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004038}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004039
4040/// Emit function which wraps the outline parallel region
4041/// and controls the arguments which are passed to this function.
4042/// The wrapper ensures that the outlined function is called
4043/// with the correct arguments when data is shared.
4044llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4045 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4046 ASTContext &Ctx = CGM.getContext();
4047 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4048
4049 // Create a function that takes as argument the source thread.
4050 FunctionArgList WrapperArgs;
4051 QualType Int16QTy =
4052 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4053 QualType Int32QTy =
4054 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004055 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004056 /*Id=*/nullptr, Int16QTy,
4057 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004058 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004059 /*Id=*/nullptr, Int32QTy,
4060 ImplicitParamDecl::Other);
4061 WrapperArgs.emplace_back(&ParallelLevelArg);
4062 WrapperArgs.emplace_back(&WrapperArg);
4063
Alexey Bataev9ff80832018-04-16 20:16:21 +00004064 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004065 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4066
4067 auto *Fn = llvm::Function::Create(
4068 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004069 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004070 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004071 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004072 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004073
4074 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4075 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004076 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004077
4078 const auto *RD = CS.getCapturedRecordDecl();
4079 auto CurField = RD->field_begin();
4080
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004081 Address ZeroAddr = CGF.CreateMemTemp(
4082 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4083 /*Name*/ ".zero.addr");
4084 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004085 // Get the array of arguments.
4086 SmallVector<llvm::Value *, 8> Args;
4087
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004088 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4089 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004090
4091 CGBuilderTy &Bld = CGF.Builder;
4092 auto CI = CS.capture_begin();
4093
4094 // Use global memory for data sharing.
4095 // Handle passing of global args to workers.
4096 Address GlobalArgs =
4097 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4098 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4099 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4100 CGF.EmitRuntimeCall(
4101 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4102 DataSharingArgs);
4103
4104 // Retrieve the shared variables from the list of references returned
4105 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004106 Address SharedArgListAddress = Address::invalid();
4107 if (CS.capture_size() > 0 ||
4108 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4109 SharedArgListAddress = CGF.EmitLoadOfPointer(
4110 GlobalArgs, CGF.getContext()
4111 .getPointerType(CGF.getContext().getPointerType(
4112 CGF.getContext().VoidPtrTy))
4113 .castAs<PointerType>());
4114 }
4115 unsigned Idx = 0;
4116 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4117 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4118 CGF.getPointerSize());
4119 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4120 Src, CGF.SizeTy->getPointerTo());
4121 llvm::Value *LB = CGF.EmitLoadOfScalar(
4122 TypedAddress,
4123 /*Volatile=*/false,
4124 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4125 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4126 Args.emplace_back(LB);
4127 ++Idx;
4128 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4129 CGF.getPointerSize());
4130 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4131 Src, CGF.SizeTy->getPointerTo());
4132 llvm::Value *UB = CGF.EmitLoadOfScalar(
4133 TypedAddress,
4134 /*Volatile=*/false,
4135 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4136 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4137 Args.emplace_back(UB);
4138 ++Idx;
4139 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004140 if (CS.capture_size() > 0) {
4141 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004142 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4143 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004144 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4145 CGF.getPointerSize());
4146 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004147 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4148 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4149 /*Volatile=*/false,
4150 CGFContext.getPointerType(ElemTy),
4151 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004152 if (CI->capturesVariableByCopy() &&
4153 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004154 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4155 CI->getLocation());
4156 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004157 Args.emplace_back(Arg);
4158 }
4159 }
4160
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004161 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004162 CGF.FinishFunction();
4163 return Fn;
4164}
4165
4166void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4167 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004168 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4169 return;
4170
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004171 assert(D && "Expected function or captured|block decl.");
4172 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4173 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004174 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4175 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004176 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004177 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004178 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4179 Body = FD->getBody();
4180 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4181 Body = BD->getBody();
4182 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4183 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004184 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004185 if (NeedToDelayGlobalization &&
4186 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4187 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004188 }
4189 if (!Body)
4190 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004191 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004192 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004193 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004194 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004195 TeamAndReductions.first = nullptr;
4196 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004197 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4198 VarChecker.getEscapedVariableLengthDecls();
4199 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004200 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004201 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4202 I->getSecond().MappedParams =
4203 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4204 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4205 I->getSecond().EscapedParameters.insert(
4206 VarChecker.getEscapedParameters().begin(),
4207 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004208 I->getSecond().EscapedVariableLengthDecls.append(
4209 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004210 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004211 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004212 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004213 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004214 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004215 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004216 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004217 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004218 VarChecker.Visit(Body);
4219 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004220 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004221 I->getSecond().SecondaryLocalVarData.emplace();
4222 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4223 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4224 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4225 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004226 Data.insert(
4227 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004228 }
4229 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004230 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004231 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004232 struct GlobalizationScope final : EHScopeStack::Cleanup {
4233 GlobalizationScope() = default;
4234
4235 void Emit(CodeGenFunction &CGF, Flags flags) override {
4236 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004237 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004238 }
4239 };
4240 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004241 }
4242}
4243
4244Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4245 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004246 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4247 return Address::invalid();
4248
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004249 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004250 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4251 if (I == FunctionGlobalizedDecls.end())
4252 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004253 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004254 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004255 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004256 if (VD->hasAttrs()) {
4257 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4258 E(VD->attr_end());
4259 IT != E; ++IT) {
4260 auto VDI = I->getSecond().LocalVarData.find(
4261 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4262 ->getCanonicalDecl());
4263 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004264 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004265 }
4266 }
4267 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004268}
4269
4270void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004271 FunctionGlobalizedDecls.erase(CGF.CurFn);
4272 CGOpenMPRuntime::functionFinished(CGF);
4273}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004274
4275void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4276 CodeGenFunction &CGF, const OMPLoopDirective &S,
4277 OpenMPDistScheduleClauseKind &ScheduleKind,
4278 llvm::Value *&Chunk) const {
4279 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4280 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4281 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4282 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4283 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004284 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004285 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004286 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4287 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004288}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004289
4290void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4291 CodeGenFunction &CGF, const OMPLoopDirective &S,
4292 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004293 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004294 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004295 // Chunk size is 1 in this case.
4296 llvm::APInt ChunkSize(32, 1);
4297 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4298 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4299 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004300}
Alexey Bataev60705422018-10-30 15:50:12 +00004301
4302void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4303 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4304 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4305 " Expected target-based directive.");
4306 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4307 for (const CapturedStmt::Capture &C : CS->captures()) {
4308 // Capture variables captured by reference in lambdas for target-based
4309 // directives.
4310 if (!C.capturesVariable())
4311 continue;
4312 const VarDecl *VD = C.getCapturedVar();
4313 const auto *RD = VD->getType()
4314 .getCanonicalType()
4315 .getNonReferenceType()
4316 ->getAsCXXRecordDecl();
4317 if (!RD || !RD->isLambda())
4318 continue;
4319 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4320 LValue VDLVal;
4321 if (VD->getType().getCanonicalType()->isReferenceType())
4322 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4323 else
4324 VDLVal = CGF.MakeAddrLValue(
4325 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4326 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4327 FieldDecl *ThisCapture = nullptr;
4328 RD->getCaptureFields(Captures, ThisCapture);
4329 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4330 LValue ThisLVal =
4331 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4332 llvm::Value *CXXThis = CGF.LoadCXXThis();
4333 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4334 }
4335 for (const LambdaCapture &LC : RD->captures()) {
4336 if (LC.getCaptureKind() != LCK_ByRef)
4337 continue;
4338 const VarDecl *VD = LC.getCapturedVar();
4339 if (!CS->capturesVariable(VD))
4340 continue;
4341 auto It = Captures.find(VD);
4342 assert(It != Captures.end() && "Found lambda capture without field.");
4343 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4344 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4345 if (VD->getType().getCanonicalType()->isReferenceType())
4346 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4347 VD->getType().getCanonicalType())
4348 .getAddress();
4349 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4350 }
4351 }
4352}
4353
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004354// Get current CudaArch and ignore any unknown values
4355static CudaArch getCudaArch(CodeGenModule &CGM) {
4356 if (!CGM.getTarget().hasFeature("ptx"))
4357 return CudaArch::UNKNOWN;
4358 llvm::StringMap<bool> Features;
4359 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4360 CGM.getTarget().getTargetOpts().CPU,
4361 CGM.getTarget().getTargetOpts().Features);
4362 for (const auto &Feature : Features) {
4363 if (Feature.getValue()) {
4364 CudaArch Arch = StringToCudaArch(Feature.getKey());
4365 if (Arch != CudaArch::UNKNOWN)
4366 return Arch;
4367 }
4368 }
4369 return CudaArch::UNKNOWN;
4370}
4371
4372/// Check to see if target architecture supports unified addressing which is
4373/// a restriction for OpenMP requires clause "unified_shared_memory".
4374void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4375 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4376 for (const OMPClause *Clause : D->clauselists()) {
4377 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4378 switch (getCudaArch(CGM)) {
4379 case CudaArch::SM_20:
4380 case CudaArch::SM_21:
4381 case CudaArch::SM_30:
4382 case CudaArch::SM_32:
4383 case CudaArch::SM_35:
4384 case CudaArch::SM_37:
4385 case CudaArch::SM_50:
4386 case CudaArch::SM_52:
4387 case CudaArch::SM_53:
4388 case CudaArch::SM_60:
4389 case CudaArch::SM_61:
4390 case CudaArch::SM_62:
4391 CGM.Error(Clause->getBeginLoc(),
4392 "Target architecture does not support unified addressing");
4393 return;
4394 case CudaArch::SM_70:
4395 case CudaArch::SM_72:
4396 case CudaArch::SM_75:
4397 case CudaArch::GFX600:
4398 case CudaArch::GFX601:
4399 case CudaArch::GFX700:
4400 case CudaArch::GFX701:
4401 case CudaArch::GFX702:
4402 case CudaArch::GFX703:
4403 case CudaArch::GFX704:
4404 case CudaArch::GFX801:
4405 case CudaArch::GFX802:
4406 case CudaArch::GFX803:
4407 case CudaArch::GFX810:
4408 case CudaArch::GFX900:
4409 case CudaArch::GFX902:
4410 case CudaArch::GFX904:
4411 case CudaArch::GFX906:
4412 case CudaArch::GFX909:
4413 case CudaArch::UNKNOWN:
4414 break;
4415 case CudaArch::LAST:
4416 llvm_unreachable("Unexpected Cuda arch.");
4417 }
4418 }
4419 }
4420}
4421
Alexey Bataeve4090182018-11-02 14:54:07 +00004422/// Get number of SMs and number of blocks per SM.
4423static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4424 std::pair<unsigned, unsigned> Data;
4425 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4426 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4427 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4428 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4429 if (Data.first && Data.second)
4430 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004431 switch (getCudaArch(CGM)) {
4432 case CudaArch::SM_20:
4433 case CudaArch::SM_21:
4434 case CudaArch::SM_30:
4435 case CudaArch::SM_32:
4436 case CudaArch::SM_35:
4437 case CudaArch::SM_37:
4438 case CudaArch::SM_50:
4439 case CudaArch::SM_52:
4440 case CudaArch::SM_53:
4441 return {16, 16};
4442 case CudaArch::SM_60:
4443 case CudaArch::SM_61:
4444 case CudaArch::SM_62:
4445 return {56, 32};
4446 case CudaArch::SM_70:
4447 case CudaArch::SM_72:
4448 case CudaArch::SM_75:
4449 return {84, 32};
4450 case CudaArch::GFX600:
4451 case CudaArch::GFX601:
4452 case CudaArch::GFX700:
4453 case CudaArch::GFX701:
4454 case CudaArch::GFX702:
4455 case CudaArch::GFX703:
4456 case CudaArch::GFX704:
4457 case CudaArch::GFX801:
4458 case CudaArch::GFX802:
4459 case CudaArch::GFX803:
4460 case CudaArch::GFX810:
4461 case CudaArch::GFX900:
4462 case CudaArch::GFX902:
4463 case CudaArch::GFX904:
4464 case CudaArch::GFX906:
4465 case CudaArch::GFX909:
4466 case CudaArch::UNKNOWN:
4467 break;
4468 case CudaArch::LAST:
4469 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004470 }
4471 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4472}
4473
4474void CGOpenMPRuntimeNVPTX::clear() {
4475 if (!GlobalizedRecords.empty()) {
4476 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004477 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4478 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004479 RecordDecl *StaticRD = C.buildImplicitRecord(
4480 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4481 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004482 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4483 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4484 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004485 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4486 if (Records.Records.empty())
4487 continue;
4488 unsigned Size = 0;
4489 unsigned RecAlignment = 0;
4490 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004491 QualType RDTy = C.getRecordType(RD);
4492 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004493 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004494 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004495 Size =
4496 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4497 }
4498 Size = llvm::alignTo(Size, RecAlignment);
4499 llvm::APInt ArySize(/*numBits=*/64, Size);
4500 QualType SubTy = C.getConstantArrayType(
4501 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004502 const bool UseSharedMemory = Size <= SharedMemorySize;
4503 auto *Field =
4504 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4505 SourceLocation(), SourceLocation(), nullptr, SubTy,
4506 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4507 /*BW=*/nullptr, /*Mutable=*/false,
4508 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004509 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004510 if (UseSharedMemory) {
4511 SharedStaticRD->addDecl(Field);
4512 SharedRecs.push_back(&Records);
4513 } else {
4514 StaticRD->addDecl(Field);
4515 GlobalRecs.push_back(&Records);
4516 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004517 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004518 Records.UseSharedMemory->setInitializer(
4519 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4520 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004521 // Allocate SharedMemorySize buffer for the shared memory.
4522 // FIXME: nvlink does not handle weak linkage correctly (object with the
4523 // different size are reported as erroneous).
4524 // Restore this code as sson as nvlink is fixed.
4525 if (!SharedStaticRD->field_empty()) {
4526 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4527 QualType SubTy = C.getConstantArrayType(
4528 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4529 auto *Field = FieldDecl::Create(
4530 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4531 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4532 /*BW=*/nullptr, /*Mutable=*/false,
4533 /*InitStyle=*/ICIS_NoInit);
4534 Field->setAccess(AS_public);
4535 SharedStaticRD->addDecl(Field);
4536 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004537 SharedStaticRD->completeDefinition();
4538 if (!SharedStaticRD->field_empty()) {
4539 QualType StaticTy = C.getRecordType(SharedStaticRD);
4540 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4541 auto *GV = new llvm::GlobalVariable(
4542 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004543 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004544 llvm::Constant::getNullValue(LLVMStaticTy),
4545 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4546 llvm::GlobalValue::NotThreadLocal,
4547 C.getTargetAddressSpace(LangAS::cuda_shared));
4548 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4549 GV, CGM.VoidPtrTy);
4550 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4551 Rec->Buffer->replaceAllUsesWith(Replacement);
4552 Rec->Buffer->eraseFromParent();
4553 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004554 }
4555 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004556 if (!StaticRD->field_empty()) {
4557 QualType StaticTy = C.getRecordType(StaticRD);
4558 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4559 llvm::APInt Size1(32, SMsBlockPerSM.second);
4560 QualType Arr1Ty =
4561 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4562 /*IndexTypeQuals=*/0);
4563 llvm::APInt Size2(32, SMsBlockPerSM.first);
4564 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4565 /*IndexTypeQuals=*/0);
4566 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4567 auto *GV = new llvm::GlobalVariable(
4568 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004569 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004570 llvm::Constant::getNullValue(LLVMArr2Ty),
4571 "_openmp_static_glob_rd_$_");
4572 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4573 GV, CGM.VoidPtrTy);
4574 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4575 Rec->Buffer->replaceAllUsesWith(Replacement);
4576 Rec->Buffer->eraseFromParent();
4577 }
4578 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004579 }
4580 CGOpenMPRuntime::clear();
4581}