blob: 19b3147d26b5527f5952f1294c15965cb7f52ee4 [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"
20#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000027 /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
28 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000030 /// \brief Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000032 /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
35 /// \brief Call to void __kmpc_spmd_kernel_deinit();
36 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000037 /// \brief Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000041 /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function,
42 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
44 /// \brief Call to void __kmpc_kernel_end_parallel();
45 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000052 /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element,
53 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
55 /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element,
56 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
58 /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
59 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
63 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Alexey Bataevfac26cf2018-05-02 20:03:27 +000064 /// \brief Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
65 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
66 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
67 /// lane_offset, int16_t shortCircuit),
68 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
69 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000070 /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
71 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
72 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
73 /// lane_offset, int16_t shortCircuit),
74 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
75 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
76 /// int32_t index, int32_t width),
77 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
78 /// index, int32_t width, int32_t reduce))
79 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000080 /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
82 /// \brief Call to void __kmpc_data_sharing_init_stack();
83 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
84 /// \brief Call to void* __kmpc_data_sharing_push_stack(size_t size,
85 /// int16_t UseSharedMemory);
86 OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
87 /// \brief Call to void __kmpc_data_sharing_pop_stack(void *a);
88 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
89 /// \brief Call to void __kmpc_begin_sharing_variables(void ***args,
90 /// size_t n_args);
91 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
92 /// \brief Call to void __kmpc_end_sharing_variables();
93 OMPRTL_NVPTX__kmpc_end_sharing_variables,
94 /// \brief Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
95 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000096 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
97 /// global_tid);
98 OMPRTL_NVPTX__kmpc_parallel_level,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000099};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000100
101/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
102class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000103 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000105 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 llvm::BasicBlock *ContBlock = nullptr;
109
110public:
111 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
112 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
113 bool Conditional = false)
114 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
115 ExitArgs(ExitArgs), Conditional(Conditional) {}
116 void Enter(CodeGenFunction &CGF) override {
117 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
118 if (Conditional) {
119 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
120 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
121 ContBlock = CGF.createBasicBlock("omp_if.end");
122 // Generate the branch (If-stmt)
123 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
124 CGF.EmitBlock(ThenBlock);
125 }
126 }
127 void Done(CodeGenFunction &CGF) {
128 // Emit the rest of blocks/branches
129 CGF.EmitBranch(ContBlock);
130 CGF.EmitBlock(ContBlock, true);
131 }
132 void Exit(CodeGenFunction &CGF) override {
133 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
134 }
135};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000136
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000137/// A class to track the execution mode when codegening directives within
138/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
139/// to the target region and used by containing directives such as 'parallel'
140/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000141class ExecutionModeRAII {
142private:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000143 bool SavedMode;
144 bool &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000145
146public:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000147 ExecutionModeRAII(bool &Mode, bool NewMode) : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148 SavedMode = Mode;
149 Mode = NewMode;
150 }
151 ~ExecutionModeRAII() { Mode = SavedMode; }
152};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000153
154/// GPU Configuration: This information can be derived from cuda registers,
155/// however, providing compile time constants helps generate more efficient
156/// code. For all practical purposes this is fine because the configuration
157/// is the same for all known NVPTX architectures.
158enum MachineConfiguration : unsigned {
159 WarpSize = 32,
160 /// Number of bits required to represent a lane identifier, which is
161 /// computed as log_2(WarpSize).
162 LaneIDBits = 5,
163 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000164
165 /// Global memory alignment for performance.
166 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000167};
168
169enum NamedBarrier : unsigned {
170 /// Synchronize on this barrier #ID using a named barrier primitive.
171 /// Only the subset of active threads in a parallel region arrive at the
172 /// barrier.
173 NB_Parallel = 1,
174};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000175
176/// Get the list of variables that can escape their declaration context.
177class CheckVarsEscapingDeclContext final
178 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
179 CodeGenFunction &CGF;
180 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000181 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000182 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000183 bool AllEscaped = false;
184 RecordDecl *GlobalizedRD = nullptr;
185 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
186
Alexey Bataev03f270c2018-03-30 18:31:07 +0000187 static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
188 isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000189 for (const Decl *D : VD->redecls()) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000190 if (!D->hasAttrs())
191 continue;
192 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
193 return Attr->getMapType();
194 }
195 return llvm::None;
196 }
197
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000198 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000199 // Do not globalize declare target variables.
200 if (isDeclareTargetDeclaration(VD))
201 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000202 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000203 // Variables captured by value must be globalized.
204 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000205 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000206 if (!FD->hasAttrs())
207 return;
208 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
209 if (!Attr)
210 return;
211 if (!isOpenMPPrivate(
212 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
213 Attr->getCaptureKind() == OMPC_map)
214 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000215 if (FD->getType()->isReferenceType())
216 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000217 assert(!VD->getType()->isVariablyModifiedType() &&
218 "Parameter captured by value with variably modified type");
Alexey Bataevc99042b2018-03-15 18:10:54 +0000219 EscapedParameters.insert(VD);
220 }
221 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000222 if (VD->getType()->isVariablyModifiedType())
223 EscapedVariableLengthDecls.insert(VD);
224 else
225 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000226 }
227
228 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000229 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000230 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000231 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
232 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
233 const bool SavedAllEscaped = AllEscaped;
234 AllEscaped = VD->getType()->isLValueReferenceType();
235 Visit(VarD->getInit());
236 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000237 }
238 }
239 }
240 void VisitOpenMPCapturedStmt(const CapturedStmt *S) {
241 if (!S)
242 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000243 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000244 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
245 const ValueDecl *VD = C.getCapturedVar();
246 markAsEscaped(VD);
247 if (isa<OMPCapturedExprDecl>(VD))
248 VisitValueDecl(VD);
249 }
250 }
251 }
252
253 typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
254 static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
255 return P1.first > P2.first;
256 }
257
258 void buildRecordForGlobalizedVars() {
259 assert(!GlobalizedRD &&
260 "Record for globalized variables is built already.");
261 if (EscapedDecls.empty())
262 return;
263 ASTContext &C = CGF.getContext();
264 SmallVector<VarsDataTy, 4> GlobalizedVars;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000265 for (const ValueDecl *D : EscapedDecls)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000266 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
267 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
268 stable_sort_comparator);
269 // Build struct _globalized_locals_ty {
270 // /* globalized vars */
271 // };
272 GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
273 GlobalizedRD->startDefinition();
274 for (const auto &Pair : GlobalizedVars) {
275 const ValueDecl *VD = Pair.second;
276 QualType Type = VD->getType();
277 if (Type->isLValueReferenceType())
278 Type = C.getPointerType(Type.getNonReferenceType());
279 else
280 Type = Type.getNonReferenceType();
281 SourceLocation Loc = VD->getLocation();
282 auto *Field = FieldDecl::Create(
283 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
284 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
285 /*BW=*/nullptr, /*Mutable=*/false,
286 /*InitStyle=*/ICIS_NoInit);
287 Field->setAccess(AS_public);
288 GlobalizedRD->addDecl(Field);
289 if (VD->hasAttrs()) {
290 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
291 E(VD->getAttrs().end());
292 I != E; ++I)
293 Field->addAttr(*I);
294 }
295 MappedDeclsFields.try_emplace(VD, Field);
296 }
297 GlobalizedRD->completeDefinition();
298 }
299
300public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000301 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000302 virtual ~CheckVarsEscapingDeclContext() = default;
303 void VisitDeclStmt(const DeclStmt *S) {
304 if (!S)
305 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000306 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000307 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
308 VisitValueDecl(VD);
309 }
310 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
311 if (!D)
312 return;
313 if (D->hasAssociatedStmt()) {
314 if (const auto *S =
315 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt()))
316 VisitOpenMPCapturedStmt(S);
317 }
318 }
319 void VisitCapturedStmt(const CapturedStmt *S) {
320 if (!S)
321 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000322 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000323 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
324 const ValueDecl *VD = C.getCapturedVar();
325 markAsEscaped(VD);
326 if (isa<OMPCapturedExprDecl>(VD))
327 VisitValueDecl(VD);
328 }
329 }
330 }
331 void VisitLambdaExpr(const LambdaExpr *E) {
332 if (!E)
333 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000334 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000335 if (C.capturesVariable()) {
336 if (C.getCaptureKind() == LCK_ByRef) {
337 const ValueDecl *VD = C.getCapturedVar();
338 markAsEscaped(VD);
339 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
340 VisitValueDecl(VD);
341 }
342 }
343 }
344 }
345 void VisitBlockExpr(const BlockExpr *E) {
346 if (!E)
347 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000348 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000349 if (C.isByRef()) {
350 const VarDecl *VD = C.getVariable();
351 markAsEscaped(VD);
352 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
353 VisitValueDecl(VD);
354 }
355 }
356 }
357 void VisitCallExpr(const CallExpr *E) {
358 if (!E)
359 return;
360 for (const Expr *Arg : E->arguments()) {
361 if (!Arg)
362 continue;
363 if (Arg->isLValue()) {
364 const bool SavedAllEscaped = AllEscaped;
365 AllEscaped = true;
366 Visit(Arg);
367 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000368 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000369 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000370 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000371 }
372 Visit(E->getCallee());
373 }
374 void VisitDeclRefExpr(const DeclRefExpr *E) {
375 if (!E)
376 return;
377 const ValueDecl *VD = E->getDecl();
378 if (AllEscaped)
379 markAsEscaped(VD);
380 if (isa<OMPCapturedExprDecl>(VD))
381 VisitValueDecl(VD);
382 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
383 if (VarD->isInitCapture())
384 VisitValueDecl(VD);
385 }
386 void VisitUnaryOperator(const UnaryOperator *E) {
387 if (!E)
388 return;
389 if (E->getOpcode() == UO_AddrOf) {
390 const bool SavedAllEscaped = AllEscaped;
391 AllEscaped = true;
392 Visit(E->getSubExpr());
393 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000394 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000395 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000396 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000397 }
398 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
399 if (!E)
400 return;
401 if (E->getCastKind() == CK_ArrayToPointerDecay) {
402 const bool SavedAllEscaped = AllEscaped;
403 AllEscaped = true;
404 Visit(E->getSubExpr());
405 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000406 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000407 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000408 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000409 }
410 void VisitExpr(const Expr *E) {
411 if (!E)
412 return;
413 bool SavedAllEscaped = AllEscaped;
414 if (!E->isLValue())
415 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000416 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000417 if (Child)
418 Visit(Child);
419 AllEscaped = SavedAllEscaped;
420 }
421 void VisitStmt(const Stmt *S) {
422 if (!S)
423 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000424 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000425 if (Child)
426 Visit(Child);
427 }
428
Alexey Bataevc99042b2018-03-15 18:10:54 +0000429 /// Returns the record that handles all the escaped local variables and used
430 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 const RecordDecl *getGlobalizedRecord() {
432 if (!GlobalizedRD)
433 buildRecordForGlobalizedVars();
434 return GlobalizedRD;
435 }
436
Alexey Bataevc99042b2018-03-15 18:10:54 +0000437 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000438 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
439 assert(GlobalizedRD &&
440 "Record for globalized variables must be generated already.");
441 auto I = MappedDeclsFields.find(VD);
442 if (I == MappedDeclsFields.end())
443 return nullptr;
444 return I->getSecond();
445 }
446
Alexey Bataevc99042b2018-03-15 18:10:54 +0000447 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000448 ArrayRef<const ValueDecl *> getEscapedDecls() const {
449 return EscapedDecls.getArrayRef();
450 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000451
452 /// Checks if the escaped local variable is actually a parameter passed by
453 /// value.
454 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
455 return EscapedParameters;
456 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000457
458 /// Returns the list of the escaped variables with the variably modified
459 /// types.
460 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
461 return EscapedVariableLengthDecls.getArrayRef();
462 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000464} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000465
466/// Get the GPU warp size.
467static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000468 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000469 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000470 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000471 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000472}
473
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000474/// Get the id of the current thread on the GPU.
475static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000476 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000477 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000478 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000479 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000480}
481
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000482/// Get the id of the warp in the block.
483/// We assume that the warp size is 32, which is always the case
484/// on the NVPTX device, to generate more efficient code.
485static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
486 CGBuilderTy &Bld = CGF.Builder;
487 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
488}
489
490/// Get the id of the current lane in the Warp.
491/// We assume that the warp size is 32, which is always the case
492/// on the NVPTX device, to generate more efficient code.
493static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
494 CGBuilderTy &Bld = CGF.Builder;
495 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
496 "nvptx_lane_id");
497}
498
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000499/// Get the maximum number of threads in a block of the GPU.
500static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000501 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000502 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000503 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000504 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000505}
506
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000507/// Get barrier to synchronize all threads in a block.
508static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000509 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000510 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000511}
512
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000513/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
514/// a CTA.
515static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
516 llvm::Value *NumThreads) {
517 CGBuilderTy &Bld = CGF.Builder;
518 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000519 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
520 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
521 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000522}
523
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000524/// Synchronize all GPU threads in a block.
525static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000526
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000527/// Synchronize worker threads in a parallel region.
528static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
529 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
530}
531
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000532/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000533/// For the 'generic' execution mode, the runtime encodes thread_limit in
534/// the launch parameters, always starting thread_limit+warpSize threads per
535/// CTA. The threads in the last warp are reserved for master execution.
536/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
537static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
538 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000539 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000540 return IsInSpmdExecutionMode
541 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000542 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
543 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000544}
545
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000546/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000547/// The master thread id is the first thread (lane) of the last warp in the
548/// GPU block. Warp size is assumed to be some power of 2.
549/// Thread id is 0 indexed.
550/// E.g: If NumThreads is 33, master id is 32.
551/// If NumThreads is 64, master id is 32.
552/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000553static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000554 CGBuilderTy &Bld = CGF.Builder;
555 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
556
557 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000558 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000559
Alexey Bataeve290ec02018-04-06 16:03:36 +0000560 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000561 Bld.CreateNot(Mask), "master_tid");
562}
563
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000564CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000565 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000566 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
567 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000568 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000569}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000570
571void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
572 CodeGenModule &CGM) {
573 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000574
575 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000576 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000577 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000578 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000579 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000580}
581
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000582bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000583 return IsInSPMDExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000584}
585
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000586static CGOpenMPRuntimeNVPTX::DataSharingMode
587getDataSharingMode(CodeGenModule &CGM) {
588 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
589 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000590}
591
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000592/// Check for inner (nested) SPMD construct, if any
593static bool hasNestedSPMDDirective(const OMPExecutableDirective &D) {
594 const auto *CS = D.getCapturedStmt(OMPD_target);
595 const auto *Body = CS->getCapturedStmt()->IgnoreContainers();
596 const Stmt *ChildStmt = nullptr;
597 if (const auto *C = dyn_cast<CompoundStmt>(Body))
598 if (C->size() == 1)
599 ChildStmt = C->body_front();
600 if (!ChildStmt)
601 return false;
602
603 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
604 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
605 // TODO: add further analysis for inner teams|distribute directives, if any.
606 switch (D.getDirectiveKind()) {
607 case OMPD_target:
608 return (isOpenMPParallelDirective(DKind) &&
609 !isOpenMPTeamsDirective(DKind) &&
610 !isOpenMPDistributeDirective(DKind)) ||
611 isOpenMPSimdDirective(DKind) ||
612 DKind == OMPD_teams_distribute_parallel_for;
613 case OMPD_target_teams:
614 return (isOpenMPParallelDirective(DKind) &&
615 !isOpenMPDistributeDirective(DKind)) ||
616 isOpenMPSimdDirective(DKind) ||
617 DKind == OMPD_distribute_parallel_for;
618 case OMPD_target_teams_distribute:
619 return isOpenMPParallelDirective(DKind) || isOpenMPSimdDirective(DKind);
620 case OMPD_target_simd:
621 case OMPD_target_parallel:
622 case OMPD_target_parallel_for:
623 case OMPD_target_parallel_for_simd:
624 case OMPD_target_teams_distribute_simd:
625 case OMPD_target_teams_distribute_parallel_for:
626 case OMPD_target_teams_distribute_parallel_for_simd:
627 case OMPD_parallel:
628 case OMPD_for:
629 case OMPD_parallel_for:
630 case OMPD_parallel_sections:
631 case OMPD_for_simd:
632 case OMPD_parallel_for_simd:
633 case OMPD_cancel:
634 case OMPD_cancellation_point:
635 case OMPD_ordered:
636 case OMPD_threadprivate:
637 case OMPD_task:
638 case OMPD_simd:
639 case OMPD_sections:
640 case OMPD_section:
641 case OMPD_single:
642 case OMPD_master:
643 case OMPD_critical:
644 case OMPD_taskyield:
645 case OMPD_barrier:
646 case OMPD_taskwait:
647 case OMPD_taskgroup:
648 case OMPD_atomic:
649 case OMPD_flush:
650 case OMPD_teams:
651 case OMPD_target_data:
652 case OMPD_target_exit_data:
653 case OMPD_target_enter_data:
654 case OMPD_distribute:
655 case OMPD_distribute_simd:
656 case OMPD_distribute_parallel_for:
657 case OMPD_distribute_parallel_for_simd:
658 case OMPD_teams_distribute:
659 case OMPD_teams_distribute_simd:
660 case OMPD_teams_distribute_parallel_for:
661 case OMPD_teams_distribute_parallel_for_simd:
662 case OMPD_target_update:
663 case OMPD_declare_simd:
664 case OMPD_declare_target:
665 case OMPD_end_declare_target:
666 case OMPD_declare_reduction:
667 case OMPD_taskloop:
668 case OMPD_taskloop_simd:
669 case OMPD_unknown:
670 llvm_unreachable("Unexpected directive.");
671 }
672 }
673
674 return false;
675}
676
677static bool supportsSPMDExecutionMode(const OMPExecutableDirective &D) {
678 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
679 switch (DirectiveKind) {
680 case OMPD_target:
681 case OMPD_target_teams:
682 case OMPD_target_teams_distribute:
683 return hasNestedSPMDDirective(D);
684 case OMPD_target_simd:
685 case OMPD_target_parallel:
686 case OMPD_target_parallel_for:
687 case OMPD_target_parallel_for_simd:
688 case OMPD_target_teams_distribute_simd:
689 case OMPD_target_teams_distribute_parallel_for:
690 case OMPD_target_teams_distribute_parallel_for_simd:
691 return true;
692 case OMPD_parallel:
693 case OMPD_for:
694 case OMPD_parallel_for:
695 case OMPD_parallel_sections:
696 case OMPD_for_simd:
697 case OMPD_parallel_for_simd:
698 case OMPD_cancel:
699 case OMPD_cancellation_point:
700 case OMPD_ordered:
701 case OMPD_threadprivate:
702 case OMPD_task:
703 case OMPD_simd:
704 case OMPD_sections:
705 case OMPD_section:
706 case OMPD_single:
707 case OMPD_master:
708 case OMPD_critical:
709 case OMPD_taskyield:
710 case OMPD_barrier:
711 case OMPD_taskwait:
712 case OMPD_taskgroup:
713 case OMPD_atomic:
714 case OMPD_flush:
715 case OMPD_teams:
716 case OMPD_target_data:
717 case OMPD_target_exit_data:
718 case OMPD_target_enter_data:
719 case OMPD_distribute:
720 case OMPD_distribute_simd:
721 case OMPD_distribute_parallel_for:
722 case OMPD_distribute_parallel_for_simd:
723 case OMPD_teams_distribute:
724 case OMPD_teams_distribute_simd:
725 case OMPD_teams_distribute_parallel_for:
726 case OMPD_teams_distribute_parallel_for_simd:
727 case OMPD_target_update:
728 case OMPD_declare_simd:
729 case OMPD_declare_target:
730 case OMPD_end_declare_target:
731 case OMPD_declare_reduction:
732 case OMPD_taskloop:
733 case OMPD_taskloop_simd:
734 case OMPD_unknown:
735 break;
736 }
737 llvm_unreachable(
738 "Unknown programming model for OpenMP directive on NVPTX target.");
739}
740
741void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000742 StringRef ParentName,
743 llvm::Function *&OutlinedFn,
744 llvm::Constant *&OutlinedFnID,
745 bool IsOffloadEntry,
746 const RegionCodeGenTy &CodeGen) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000747 ExecutionModeRAII ModeRAII(IsInSPMDExecutionMode, /*NewMode=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000748 EntryFunctionState EST;
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000749 WorkerFunctionState WST(CGM, D.getLocStart());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000750 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000751 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000752
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000753 // Emit target region as a standalone region.
754 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000755 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
756 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000757
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000758 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000759 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000760 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000761 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000762 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000763 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000764 .emitNonSPMDEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000765 }
766 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000767 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000768 .emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000769 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000770 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000771 CodeGen.setAction(Action);
772 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
773 IsOffloadEntry, CodeGen);
774
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000775 // Now change the name of the worker function to correspond to this target
776 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +0000777 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +0000778
779 // Create the worker function
780 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000781}
782
783// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000784void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000785 EntryFunctionState &EST,
786 WorkerFunctionState &WST) {
787 CGBuilderTy &Bld = CGF.Builder;
788
789 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
790 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
791 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
792 EST.ExitBB = CGF.createBasicBlock(".exit");
793
Alexey Bataev9ff80832018-04-16 20:16:21 +0000794 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000795 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
796 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
797
798 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +0000799 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000800 CGF.EmitBranch(EST.ExitBB);
801
802 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000803 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000804 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
805 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
806
807 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000808 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000809 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000810 // First action in sequential region:
811 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000812 // TODO: Optimize runtime initialization and pass in correct value.
813 llvm::Value *Args[] = {getThreadLimit(CGF),
814 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000815 CGF.EmitRuntimeCall(
816 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000817
818 // For data sharing, we need to initialize the stack.
819 CGF.EmitRuntimeCall(
820 createNVPTXRuntimeFunction(
821 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
822
Alexey Bataevc99042b2018-03-15 18:10:54 +0000823 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000824}
825
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000826void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000827 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000828 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000829 if (!CGF.HaveInsertPoint())
830 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000831
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000832 emitGenericVarsEpilog(CGF);
833
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000834 if (!EST.ExitBB)
835 EST.ExitBB = CGF.createBasicBlock(".exit");
836
837 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
838 CGF.EmitBranch(TerminateBB);
839
840 CGF.EmitBlock(TerminateBB);
841 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000842 // TODO: Optimize runtime initialization and pass in correct value.
843 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000844 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000845 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000846 // Barrier to terminate worker threads.
847 syncCTAThreads(CGF);
848 // Master thread jumps to exit point.
849 CGF.EmitBranch(EST.ExitBB);
850
851 CGF.EmitBlock(EST.ExitBB);
852 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000853}
854
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000855void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
856 StringRef ParentName,
857 llvm::Function *&OutlinedFn,
858 llvm::Constant *&OutlinedFnID,
859 bool IsOffloadEntry,
860 const RegionCodeGenTy &CodeGen) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000861 ExecutionModeRAII ModeRAII(IsInSPMDExecutionMode, /*NewMode=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000862 EntryFunctionState EST;
863
864 // Emit target region as a standalone region.
865 class NVPTXPrePostActionTy : public PrePostActionTy {
866 CGOpenMPRuntimeNVPTX &RT;
867 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
868 const OMPExecutableDirective &D;
869
870 public:
871 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
872 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
873 const OMPExecutableDirective &D)
874 : RT(RT), EST(EST), D(D) {}
875 void Enter(CodeGenFunction &CGF) override {
876 RT.emitSpmdEntryHeader(CGF, EST, D);
877 }
878 void Exit(CodeGenFunction &CGF) override {
879 RT.emitSpmdEntryFooter(CGF, EST);
880 }
881 } Action(*this, EST, D);
882 CodeGen.setAction(Action);
883 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
884 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000885}
886
887void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
888 CodeGenFunction &CGF, EntryFunctionState &EST,
889 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000890 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000891
892 // Setup BBs in entry function.
893 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
894 EST.ExitBB = CGF.createBasicBlock(".exit");
895
896 // Initialize the OMP state in the runtime; called by all active threads.
897 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
898 // based on code analysis of the target region.
899 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
900 /*RequiresOMPRuntime=*/Bld.getInt16(1),
901 /*RequiresDataSharing=*/Bld.getInt16(1)};
902 CGF.EmitRuntimeCall(
903 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
904 CGF.EmitBranch(ExecuteBB);
905
906 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000907
908 emitGenericVarsProlog(CGF, D.getLocStart());
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000909}
910
911void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
912 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000913 if (!CGF.HaveInsertPoint())
914 return;
915
916 emitGenericVarsEpilog(CGF);
917
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000918 if (!EST.ExitBB)
919 EST.ExitBB = CGF.createBasicBlock(".exit");
920
921 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
922 CGF.EmitBranch(OMPDeInitBB);
923
924 CGF.EmitBlock(OMPDeInitBB);
925 // DeInitialize the OMP state in the runtime; called by all active threads.
926 CGF.EmitRuntimeCall(
927 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
928 CGF.EmitBranch(EST.ExitBB);
929
930 CGF.EmitBlock(EST.ExitBB);
931 EST.ExitBB = nullptr;
932}
933
934// Create a unique global variable to indicate the execution mode of this target
935// region. The execution mode is either 'generic', or 'spmd' depending on the
936// target directive. This variable is picked up by the offload library to setup
937// the device appropriately before kernel launch. If the execution mode is
938// 'generic', the runtime reserves one warp for the master, otherwise, all
939// warps participate in parallel work.
940static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000941 bool Mode) {
942 auto *GVMode =
943 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
944 llvm::GlobalValue::WeakAnyLinkage,
945 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
946 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +0000947 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000948}
949
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000950void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000951 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000952
953 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000954 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000955 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000956 emitWorkerLoop(CGF, WST);
957 CGF.FinishFunction();
958}
959
960void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
961 WorkerFunctionState &WST) {
962 //
963 // The workers enter this loop and wait for parallel work from the master.
964 // When the master encounters a parallel region it sets up the work + variable
965 // arguments, and wakes up the workers. The workers first check to see if
966 // they are required for the parallel region, i.e., within the # of requested
967 // parallel threads. The activated workers load the variable arguments and
968 // execute the parallel work.
969 //
970
971 CGBuilderTy &Bld = CGF.Builder;
972
973 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
974 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
975 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
976 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
977 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
978 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
979
980 CGF.EmitBranch(AwaitBB);
981
982 // Workers wait for work from master.
983 CGF.EmitBlock(AwaitBB);
984 // Wait for parallel work
985 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000986
Gheorghe-Teodor Bercea36cdfad2018-03-22 17:33:27 +0000987 // For data sharing, we need to initialize the stack for workers.
988 CGF.EmitRuntimeCall(
989 createNVPTXRuntimeFunction(
990 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
991
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000992 Address WorkFn =
993 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
994 Address ExecStatus =
995 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
996 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
997 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
998
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000999 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001000 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001001 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001002 llvm::Value *Ret = CGF.EmitRuntimeCall(
1003 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1004 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001005
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001006 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001007 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1008 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001009 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1010
1011 // Activate requested workers.
1012 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001013 llvm::Value *IsActive =
1014 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1015 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001016
1017 // Signal start of parallel region.
1018 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001019
1020 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001021 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001022 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001023 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001024
1025 llvm::Value *WorkFnMatch =
1026 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1027
1028 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1029 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1030 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1031
1032 // Execute this outlined function.
1033 CGF.EmitBlock(ExecuteFNBB);
1034
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001035 // Insert call to work function via shared wrapper. The shared
1036 // wrapper takes two arguments:
1037 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001038 // - the thread ID;
1039 emitCall(CGF, WST.Loc, W,
1040 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001041
1042 // Go to end of parallel region.
1043 CGF.EmitBranch(TerminateBB);
1044
1045 CGF.EmitBlock(CheckNextBB);
1046 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001047 // Default case: call to outlined function through pointer if the target
1048 // region makes a declare target call that may contain an orphaned parallel
1049 // directive.
1050 auto *ParallelFnTy =
1051 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1052 /*isVarArg=*/false)
1053 ->getPointerTo();
1054 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1055 // Insert call to work function via shared wrapper. The shared
1056 // wrapper takes two arguments:
1057 // - the parallelism level;
1058 // - the thread ID;
1059 emitCall(CGF, WST.Loc, WorkFnCast,
1060 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1061 // Go to end of parallel region.
1062 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001063
1064 // Signal end of parallel region.
1065 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001066 CGF.EmitRuntimeCall(
1067 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1068 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001069 CGF.EmitBranch(BarrierBB);
1070
1071 // All active and inactive workers wait at a barrier after parallel region.
1072 CGF.EmitBlock(BarrierBB);
1073 // Barrier after parallel region.
1074 syncCTAThreads(CGF);
1075 CGF.EmitBranch(AwaitBB);
1076
1077 // Exit target region.
1078 CGF.EmitBlock(ExitBB);
1079}
1080
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001081/// \brief Returns specified OpenMP runtime function for the current OpenMP
1082/// implementation. Specialized for the NVPTX device.
1083/// \param Function OpenMP runtime function.
1084/// \return Specified function.
1085llvm::Constant *
1086CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1087 llvm::Constant *RTLFn = nullptr;
1088 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1089 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001090 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1091 // RequiresOMPRuntime);
1092 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001093 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001094 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1095 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1096 break;
1097 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001098 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001099 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1100 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001101 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001102 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001103 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1104 break;
1105 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001106 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1107 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001108 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001109 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001110 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001111 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1112 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1113 break;
1114 }
1115 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1116 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001117 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001118 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1120 break;
1121 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001122 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1123 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001124 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001125 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001126 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001127 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1128 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1129 break;
1130 }
1131 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001132 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1133 /// int16_t IsOMPRuntimeInitialized);
1134 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001135 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001136 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001137 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1138 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1139 break;
1140 }
1141 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1142 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001143 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001144 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1145 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1146 break;
1147 }
1148 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1149 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1150 // global_tid);
1151 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001152 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001153 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1154 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1155 break;
1156 }
1157 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1158 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1159 // global_tid);
1160 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001161 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1164 break;
1165 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001166 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1167 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1168 // int16_t lane_offset, int16_t warp_size);
1169 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001170 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001171 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1172 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1173 break;
1174 }
1175 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1176 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1177 // int16_t lane_offset, int16_t warp_size);
1178 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001179 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001180 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1181 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1182 break;
1183 }
1184 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1185 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1186 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1187 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1188 // lane_offset, int16_t Algorithm Version),
1189 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1190 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1191 CGM.Int16Ty, CGM.Int16Ty};
1192 auto *ShuffleReduceFnTy =
1193 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1194 /*isVarArg=*/false);
1195 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1196 auto *InterWarpCopyFnTy =
1197 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1198 /*isVarArg=*/false);
1199 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1200 CGM.Int32Ty,
1201 CGM.SizeTy,
1202 CGM.VoidPtrTy,
1203 ShuffleReduceFnTy->getPointerTo(),
1204 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001205 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001206 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1207 RTLFn = CGM.CreateRuntimeFunction(
1208 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1209 break;
1210 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001211 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1212 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1213 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1214 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1215 // lane_offset, int16_t Algorithm Version),
1216 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1217 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1218 CGM.Int16Ty, CGM.Int16Ty};
1219 auto *ShuffleReduceFnTy =
1220 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1221 /*isVarArg=*/false);
1222 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1223 auto *InterWarpCopyFnTy =
1224 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1225 /*isVarArg=*/false);
1226 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1227 CGM.Int32Ty,
1228 CGM.SizeTy,
1229 CGM.VoidPtrTy,
1230 ShuffleReduceFnTy->getPointerTo(),
1231 InterWarpCopyFnTy->getPointerTo()};
1232 auto *FnTy =
1233 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1234 RTLFn = CGM.CreateRuntimeFunction(
1235 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1236 break;
1237 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001238 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1239 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1240 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1241 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1242 // lane_offset, int16_t shortCircuit),
1243 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1244 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1245 // int32_t index, int32_t width),
1246 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1247 // int32_t index, int32_t width, int32_t reduce))
1248 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1249 CGM.Int16Ty, CGM.Int16Ty};
1250 auto *ShuffleReduceFnTy =
1251 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1252 /*isVarArg=*/false);
1253 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1254 auto *InterWarpCopyFnTy =
1255 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1256 /*isVarArg=*/false);
1257 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1258 CGM.Int32Ty, CGM.Int32Ty};
1259 auto *CopyToScratchpadFnTy =
1260 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1261 /*isVarArg=*/false);
1262 llvm::Type *LoadReduceTypeParams[] = {
1263 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1264 auto *LoadReduceFnTy =
1265 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1266 /*isVarArg=*/false);
1267 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1268 CGM.Int32Ty,
1269 CGM.SizeTy,
1270 CGM.VoidPtrTy,
1271 ShuffleReduceFnTy->getPointerTo(),
1272 InterWarpCopyFnTy->getPointerTo(),
1273 CopyToScratchpadFnTy->getPointerTo(),
1274 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001275 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001276 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1277 RTLFn = CGM.CreateRuntimeFunction(
1278 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1279 break;
1280 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001281 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1282 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1283 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001284 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001285 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1286 RTLFn = CGM.CreateRuntimeFunction(
1287 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1288 break;
1289 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001290 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1291 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001292 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001293 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1295 break;
1296 }
1297 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1298 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1299 // int16_t UseSharedMemory);
1300 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001301 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001302 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1303 RTLFn = CGM.CreateRuntimeFunction(
1304 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1305 break;
1306 }
1307 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1308 // Build void __kmpc_data_sharing_pop_stack(void *a);
1309 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001310 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001311 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1312 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1313 /*Name=*/"__kmpc_data_sharing_pop_stack");
1314 break;
1315 }
1316 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1317 /// Build void __kmpc_begin_sharing_variables(void ***args,
1318 /// size_t n_args);
1319 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001320 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001321 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1322 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1323 break;
1324 }
1325 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1326 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001327 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001328 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1329 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1330 break;
1331 }
1332 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1333 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1334 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001335 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001336 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1337 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1338 break;
1339 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001340 case OMPRTL_NVPTX__kmpc_parallel_level: {
1341 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1342 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1343 auto *FnTy =
1344 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1345 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1346 break;
1347 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001348 }
1349 return RTLFn;
1350}
1351
1352void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1353 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001354 uint64_t Size, int32_t,
1355 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001356 // TODO: Add support for global variables on the device after declare target
1357 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001358 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001359 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001360 llvm::Module &M = CGM.getModule();
1361 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001362
1363 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001364 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001365
1366 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001367 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001368 llvm::ConstantAsMetadata::get(
1369 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1370 // Append metadata to nvvm.annotations
1371 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1372}
1373
1374void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1375 const OMPExecutableDirective &D, StringRef ParentName,
1376 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001377 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001378 if (!IsOffloadEntry) // Nothing to do.
1379 return;
1380
1381 assert(!ParentName.empty() && "Invalid target region parent name!");
1382
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001383 bool Mode = supportsSPMDExecutionMode(D);
1384 if (Mode)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001385 emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1386 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001387 else
1388 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1389 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001390
1391 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001392}
1393
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001394CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001395 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001396 if (!CGM.getLangOpts().OpenMPIsDevice)
1397 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001398}
Carlo Bertollic6872252016-04-04 15:55:02 +00001399
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001400void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1401 OpenMPProcBindClauseKind ProcBind,
1402 SourceLocation Loc) {
1403 // Do nothing in case of Spmd mode and L0 parallel.
1404 // TODO: If in Spmd mode and L1 parallel emit the clause.
1405 if (isInSpmdExecutionMode())
1406 return;
1407
1408 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1409}
1410
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001411void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1412 llvm::Value *NumThreads,
1413 SourceLocation Loc) {
1414 // Do nothing in case of Spmd mode and L0 parallel.
1415 // TODO: If in Spmd mode and L1 parallel emit the clause.
1416 if (isInSpmdExecutionMode())
1417 return;
1418
1419 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1420}
1421
Carlo Bertollic6872252016-04-04 15:55:02 +00001422void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1423 const Expr *NumTeams,
1424 const Expr *ThreadLimit,
1425 SourceLocation Loc) {}
1426
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001427llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1428 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1429 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001430 SourceLocation Loc = D.getLocStart();
1431
1432 // Emit target region as a standalone region.
1433 class NVPTXPrePostActionTy : public PrePostActionTy {
1434 SourceLocation &Loc;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001435 bool &IsInParallelRegion;
1436 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001437
1438 public:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001439 NVPTXPrePostActionTy(SourceLocation &Loc, bool &IsInParallelRegion)
1440 : Loc(Loc), IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001441 void Enter(CodeGenFunction &CGF) override {
1442 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1443 .emitGenericVarsProlog(CGF, Loc);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001444 PrevIsInParallelRegion = IsInParallelRegion;
1445 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001446 }
1447 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001448 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001449 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1450 .emitGenericVarsEpilog(CGF);
1451 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001452 } Action(Loc, IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001453 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001454 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1455 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001456 auto *OutlinedFun =
1457 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1458 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001459 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
1460 if (!isInSpmdExecutionMode() && !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001461 llvm::Function *WrapperFun =
1462 createParallelDataSharingWrapper(OutlinedFun, D);
1463 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1464 }
1465
1466 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001467}
1468
1469llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001470 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1471 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001472 SourceLocation Loc = D.getLocStart();
Carlo Bertollic6872252016-04-04 15:55:02 +00001473
Alexey Bataevc99042b2018-03-15 18:10:54 +00001474 // Emit target region as a standalone region.
1475 class NVPTXPrePostActionTy : public PrePostActionTy {
1476 SourceLocation &Loc;
1477
1478 public:
1479 NVPTXPrePostActionTy(SourceLocation &Loc) : Loc(Loc) {}
1480 void Enter(CodeGenFunction &CGF) override {
1481 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1482 .emitGenericVarsProlog(CGF, Loc);
1483 }
1484 void Exit(CodeGenFunction &CGF) override {
1485 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1486 .emitGenericVarsEpilog(CGF);
1487 }
1488 } Action(Loc);
1489 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001490 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1491 D, ThreadIDVar, InnermostKind, CodeGen);
1492 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1493 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001494 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001495 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001496
1497 return OutlinedFun;
1498}
1499
Alexey Bataevc99042b2018-03-15 18:10:54 +00001500void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
1501 SourceLocation Loc) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001502 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1503 return;
1504
Alexey Bataevc99042b2018-03-15 18:10:54 +00001505 CGBuilderTy &Bld = CGF.Builder;
1506
1507 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1508 if (I == FunctionGlobalizedDecls.end())
1509 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001510 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1511 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001512
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001513 // Recover pointer to this function's global record. The runtime will
1514 // handle the specifics of the allocation of the memory.
1515 // Use actual memory size of the record including the padding
1516 // for alignment purposes.
1517 unsigned Alignment =
1518 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1519 unsigned GlobalRecordSize =
1520 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1521 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
1522 // TODO: allow the usage of shared memory to be controlled by
1523 // the user, for now, default to global.
1524 llvm::Value *GlobalRecordSizeArg[] = {
1525 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1526 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1527 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1528 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1529 GlobalRecordSizeArg);
1530 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1531 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1532 LValue Base =
1533 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
1534 I->getSecond().GlobalRecordAddr = GlobalRecValue;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001535
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001536 // Emit the "global alloca" which is a GEP from the global declaration
1537 // record using the pointer returned by the runtime.
1538 for (auto &Rec : I->getSecond().LocalVarData) {
1539 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1540 llvm::Value *ParValue;
1541 if (EscapedParam) {
1542 const auto *VD = cast<VarDecl>(Rec.first);
1543 LValue ParLVal =
1544 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1545 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1546 }
1547 const FieldDecl *FD = Rec.second.first;
1548 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
1549 Rec.second.second = VarAddr.getAddress();
1550 if (EscapedParam) {
1551 const auto *VD = cast<VarDecl>(Rec.first);
1552 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1553 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1554 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001555 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001556 }
1557 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1558 // Recover pointer to this function's global record. The runtime will
1559 // handle the specifics of the allocation of the memory.
1560 // Use actual memory size of the record including the padding
1561 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001562 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001563 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1564 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1565 Size = Bld.CreateNUWAdd(
1566 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1567 llvm::Value *AlignVal =
1568 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1569 Size = Bld.CreateUDiv(Size, AlignVal);
1570 Size = Bld.CreateNUWMul(Size, AlignVal);
1571 // TODO: allow the usage of shared memory to be controlled by
1572 // the user, for now, default to global.
1573 llvm::Value *GlobalRecordSizeArg[] = {
1574 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1575 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1576 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1577 GlobalRecordSizeArg);
1578 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1579 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1580 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1581 CGM.getContext().getDeclAlign(VD),
1582 AlignmentSource::Decl);
1583 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1584 Base.getAddress());
1585 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001586 }
1587 I->getSecond().MappedParams->apply(CGF);
1588}
1589
1590void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001591 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1592 return;
1593
Alexey Bataevc99042b2018-03-15 18:10:54 +00001594 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001595 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001596 I->getSecond().MappedParams->restore(CGF);
1597 if (!CGF.HaveInsertPoint())
1598 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001599 for (llvm::Value *Addr :
1600 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1601 CGF.EmitRuntimeCall(
1602 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1603 Addr);
1604 }
1605 if (I->getSecond().GlobalRecordAddr) {
1606 CGF.EmitRuntimeCall(
1607 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1608 I->getSecond().GlobalRecordAddr);
1609 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001610 }
1611}
1612
Carlo Bertollic6872252016-04-04 15:55:02 +00001613void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
1614 const OMPExecutableDirective &D,
1615 SourceLocation Loc,
1616 llvm::Value *OutlinedFn,
1617 ArrayRef<llvm::Value *> CapturedVars) {
1618 if (!CGF.HaveInsertPoint())
1619 return;
1620
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001621 Address ZeroAddr = CGF.CreateMemTemp(
1622 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
1623 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00001624 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1625 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001626 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00001627 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1628 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001629 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00001630}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001631
1632void CGOpenMPRuntimeNVPTX::emitParallelCall(
1633 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1634 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1635 if (!CGF.HaveInsertPoint())
1636 return;
1637
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001638 if (isInSpmdExecutionMode())
1639 emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
1640 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001641 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001642}
1643
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001644void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001645 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1646 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1647 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001648
1649 // Force inline this outlined function at its call site.
1650 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
1651
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001652 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
1653 /*DestWidth=*/32, /*Signed=*/1),
1654 ".zero.addr");
1655 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1656 Address ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1657 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, ThreadIDAddr](
1658 CodeGenFunction &CGF, PrePostActionTy &Action) {
1659 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001660
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001661 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1662 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1663 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1664 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1665 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
1666 };
1667 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
1668 PrePostActionTy &) {
1669
1670 RegionCodeGenTy RCG(CodeGen);
1671 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1672 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1673 llvm::Value *Args[] = {RTLoc, ThreadID};
1674
1675 NVPTXActionTy Action(
1676 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
1677 Args,
1678 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
1679 Args);
1680 RCG.setAction(Action);
1681 RCG(CGF);
1682 };
1683
1684 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
1685 PrePostActionTy &Action) {
1686 CGBuilderTy &Bld = CGF.Builder;
1687 llvm::Function *WFn = WrapperFunctionsMap[Fn];
1688 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001689 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
1690
1691 // Prepare for parallel region. Indicate the outlined function.
1692 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001693 CGF.EmitRuntimeCall(
1694 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
1695 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001696
1697 // Create a private scope that will globalize the arguments
1698 // passed from the outside of the target region.
1699 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1700
1701 // There's somehting to share.
1702 if (!CapturedVars.empty()) {
1703 // Prepare for parallel region. Indicate the outlined function.
1704 Address SharedArgs =
1705 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
1706 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
1707
1708 llvm::Value *DataSharingArgs[] = {
1709 SharedArgsPtr,
1710 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1711 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1712 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
1713 DataSharingArgs);
1714
1715 // Store variable address in a list of references to pass to workers.
1716 unsigned Idx = 0;
1717 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001718 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
1719 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
1720 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001721 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001722 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
1723 CGF.getPointerSize());
1724 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00001725 if (V->getType()->isIntegerTy())
1726 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1727 else
1728 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001729 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1730 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00001731 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001732 }
1733 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001734
1735 // Activate workers. This barrier is used by the master to signal
1736 // work for the workers.
1737 syncCTAThreads(CGF);
1738
1739 // OpenMP [2.5, Parallel Construct, p.49]
1740 // There is an implied barrier at the end of a parallel region. After the
1741 // end of a parallel region, only the master thread of the team resumes
1742 // execution of the enclosing task region.
1743 //
1744 // The master waits at this barrier until all workers are done.
1745 syncCTAThreads(CGF);
1746
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001747 if (!CapturedVars.empty())
1748 CGF.EmitRuntimeCall(
1749 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
1750
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001751 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001752 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001753 };
1754
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001755 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen, &CodeGen](
1756 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001757 RegionCodeGenTy RCG(CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001758 if (IsInParallelRegion) {
1759 SeqGen(CGF, Action);
1760 } else if (IsInTargetMasterThreadRegion) {
1761 L0ParallelGen(CGF, Action);
1762 } else {
1763 // Check for master and then parallelism:
1764 // if (is_master) {
1765 // Worker call.
1766 // } else if (__kmpc_parallel_level(loc, gtid)) {
1767 // Serialized execution.
1768 // } else {
1769 // Outlined function call.
1770 // }
1771 CGBuilderTy &Bld = CGF.Builder;
1772 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1773 if (!isInSpmdExecutionMode()) {
1774 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1775 llvm::BasicBlock *ParallelCheckBB =
1776 CGF.createBasicBlock(".parallelcheck");
1777 llvm::Value *IsMaster =
1778 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1779 Bld.CreateCondBr(IsMaster, MasterCheckBB, ParallelCheckBB);
1780 CGF.EmitBlock(MasterCheckBB);
1781 L0ParallelGen(CGF, Action);
1782 CGF.EmitBranch(ExitBB);
1783 // There is no need to emit line number for unconditional branch.
1784 (void)ApplyDebugLocation::CreateEmpty(CGF);
1785 CGF.EmitBlock(ParallelCheckBB);
1786 }
1787 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1788 llvm::Value *ThreadID = getThreadID(CGF, Loc);
1789 llvm::Value *PL = CGF.EmitRuntimeCall(
1790 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
1791 {RTLoc, ThreadID});
1792 llvm::Value *Res = Bld.CreateIsNotNull(PL);
1793 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
1794 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
1795 Bld.CreateCondBr(Res, ThenBlock, ElseBlock);
1796 // Emit the 'then' code.
1797 CGF.EmitBlock(ThenBlock);
1798 SeqGen(CGF, Action);
1799 // There is no need to emit line number for unconditional branch.
1800 (void)ApplyDebugLocation::CreateEmpty(CGF);
1801 // Emit the 'else' code.
1802 CGF.EmitBlock(ElseBlock);
1803 RCG(CGF);
1804 // There is no need to emit line number for unconditional branch.
1805 (void)ApplyDebugLocation::CreateEmpty(CGF);
1806 // Emit the continuation block for code after the if.
1807 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1808 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001809 };
1810
Alexey Bataev9ff80832018-04-16 20:16:21 +00001811 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001812 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001813 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001814 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001815 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001816 ThenRCG(CGF);
1817 }
1818}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001819
1820void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
1821 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
1822 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
1823 // Just call the outlined function to execute the parallel region.
1824 // OutlinedFn(&GTid, &zero, CapturedStruct);
1825 //
1826 // TODO: Do something with IfCond when support for the 'if' clause
1827 // is added on Spmd target directives.
1828 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00001829
1830 Address ZeroAddr = CGF.CreateMemTemp(
1831 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
1832 ".zero.addr");
1833 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001834 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertolli79712092018-02-28 20:48:35 +00001835 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001836 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00001837 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001838}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001839
Alexey Bataev504fc2d2018-05-07 17:23:05 +00001840void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
1841 CodeGenFunction &CGF, StringRef CriticalName,
1842 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1843 const Expr *Hint) {
1844 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1845 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1846 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1847 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1848 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1849
1850 // Fetch team-local id of the thread.
1851 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
1852
1853 // Get the width of the team.
1854 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
1855
1856 // Initialize the counter variable for the loop.
1857 QualType Int32Ty =
1858 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1859 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1860 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1861 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1862 /*isInit=*/true);
1863
1864 // Block checks if loop counter exceeds upper bound.
1865 CGF.EmitBlock(LoopBB);
1866 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1867 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1868 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1869
1870 // Block tests which single thread should execute region, and which threads
1871 // should go straight to synchronisation point.
1872 CGF.EmitBlock(TestBB);
1873 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1874 llvm::Value *CmpThreadToCounter =
1875 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1876 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1877
1878 // Block emits the body of the critical region.
1879 CGF.EmitBlock(BodyBB);
1880
1881 // Output the critical statement.
1882 CriticalOpGen(CGF);
1883
1884 // After the body surrounded by the critical region, the single executing
1885 // thread will jump to the synchronisation point.
1886 // Block waits for all threads in current team to finish then increments the
1887 // counter variable and returns to the loop.
1888 CGF.EmitBlock(SyncBB);
1889 getNVPTXCTABarrier(CGF);
1890
1891 llvm::Value *IncCounterVal =
1892 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1893 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1894 CGF.EmitBranch(LoopBB);
1895
1896 // Block that is reached when all threads in the team complete the region.
1897 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1898}
1899
Alexey Bataevb2575932018-01-04 20:18:55 +00001900/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00001901static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
1902 QualType ValTy, QualType CastTy,
1903 SourceLocation Loc) {
1904 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
1905 "Cast type must sized.");
1906 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
1907 "Val type must sized.");
1908 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
1909 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00001910 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00001911 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
1912 CGF.getContext().getTypeSizeInChars(CastTy))
1913 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
1914 if (CastTy->isIntegerType() && ValTy->isIntegerType())
1915 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
1916 CastTy->hasSignedIntegerRepresentation());
1917 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00001918 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1919 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00001920 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
1921 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00001922}
1923
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001924/// This function creates calls to one of two shuffle functions to copy
1925/// variables between lanes in a warp.
1926static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001927 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00001928 QualType ElemType,
1929 llvm::Value *Offset,
1930 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001931 CodeGenModule &CGM = CGF.CGM;
1932 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001933 CGOpenMPRuntimeNVPTX &RT =
1934 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
1935
Alexey Bataeva453f362018-03-19 17:53:56 +00001936 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
1937 assert(Size.getQuantity() <= 8 &&
1938 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001939
Alexey Bataeva453f362018-03-19 17:53:56 +00001940 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001941 ? OMPRTL_NVPTX__kmpc_shuffle_int32
1942 : OMPRTL_NVPTX__kmpc_shuffle_int64;
1943
1944 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00001945 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
1946 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
1947 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001948 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00001949 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001950
Alexey Bataev9ff80832018-04-16 20:16:21 +00001951 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
1952 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001953
Alexey Bataeva453f362018-03-19 17:53:56 +00001954 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001955}
1956
1957namespace {
1958enum CopyAction : unsigned {
1959 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1960 // the warp using shuffle instructions.
1961 RemoteLaneToThread,
1962 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1963 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001964 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1965 ThreadToScratchpad,
1966 // ScratchpadToThread: Copy from a scratchpad array in global memory
1967 // containing team-reduced data to a thread's stack.
1968 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001969};
1970} // namespace
1971
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001972struct CopyOptionsTy {
1973 llvm::Value *RemoteLaneOffset;
1974 llvm::Value *ScratchpadIndex;
1975 llvm::Value *ScratchpadWidth;
1976};
1977
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001978/// Emit instructions to copy a Reduce list, which contains partially
1979/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001980static void emitReductionListCopy(
1981 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1982 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1983 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001984
Alexey Bataev9ff80832018-04-16 20:16:21 +00001985 CodeGenModule &CGM = CGF.CGM;
1986 ASTContext &C = CGM.getContext();
1987 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001988
Alexey Bataev9ff80832018-04-16 20:16:21 +00001989 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1990 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1991 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001992
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001993 // Iterates, element-by-element, through the source Reduce list and
1994 // make a copy.
1995 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001996 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001997 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001998 Address SrcElementAddr = Address::invalid();
1999 Address DestElementAddr = Address::invalid();
2000 Address DestElementPtrAddr = Address::invalid();
2001 // Should we shuffle in an element from a remote lane?
2002 bool ShuffleInElement = false;
2003 // Set to true to update the pointer in the dest Reduce list to a
2004 // newly created element.
2005 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002006 // Increment the src or dest pointer to the scratchpad, for each
2007 // new element.
2008 bool IncrScratchpadSrc = false;
2009 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002010
2011 switch (Action) {
2012 case RemoteLaneToThread: {
2013 // Step 1.1: Get the address for the src element in the Reduce list.
2014 Address SrcElementPtrAddr =
2015 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002016 SrcElementAddr = CGF.EmitLoadOfPointer(
2017 SrcElementPtrAddr,
2018 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002019
2020 // Step 1.2: Create a temporary to store the element in the destination
2021 // Reduce list.
2022 DestElementPtrAddr =
2023 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2024 DestElementAddr =
2025 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2026 ShuffleInElement = true;
2027 UpdateDestListPtr = true;
2028 break;
2029 }
2030 case ThreadCopy: {
2031 // Step 1.1: Get the address for the src element in the Reduce list.
2032 Address SrcElementPtrAddr =
2033 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002034 SrcElementAddr = CGF.EmitLoadOfPointer(
2035 SrcElementPtrAddr,
2036 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002037
2038 // Step 1.2: Get the address for dest element. The destination
2039 // element has already been created on the thread's stack.
2040 DestElementPtrAddr =
2041 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002042 DestElementAddr = CGF.EmitLoadOfPointer(
2043 DestElementPtrAddr,
2044 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002045 break;
2046 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002047 case ThreadToScratchpad: {
2048 // Step 1.1: Get the address for the src element in the Reduce list.
2049 Address SrcElementPtrAddr =
2050 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002051 SrcElementAddr = CGF.EmitLoadOfPointer(
2052 SrcElementPtrAddr,
2053 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002054
2055 // Step 1.2: Get the address for dest element:
2056 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002057 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002058 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002059 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002060 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002061 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002062 ScratchPadElemAbsolutePtrVal =
2063 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002064 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2065 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002066 IncrScratchpadDest = true;
2067 break;
2068 }
2069 case ScratchpadToThread: {
2070 // Step 1.1: Get the address for the src element in the scratchpad.
2071 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002072 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002073 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002074 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002075 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002076 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002077 ScratchPadElemAbsolutePtrVal =
2078 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2079 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2080 C.getTypeAlignInChars(Private->getType()));
2081 IncrScratchpadSrc = true;
2082
2083 // Step 1.2: Create a temporary to store the element in the destination
2084 // Reduce list.
2085 DestElementPtrAddr =
2086 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2087 DestElementAddr =
2088 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2089 UpdateDestListPtr = true;
2090 break;
2091 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002092 }
2093
2094 // Regardless of src and dest of copy, we emit the load of src
2095 // element as this is required in all directions
2096 SrcElementAddr = Bld.CreateElementBitCast(
2097 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
2098 llvm::Value *Elem =
2099 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002100 Private->getType(), Private->getExprLoc());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002101
2102 // Now that all active lanes have read the element in the
2103 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002104 if (ShuffleInElement) {
2105 Elem =
2106 createRuntimeShuffleFunction(CGF, Elem, Private->getType(),
2107 RemoteLaneOffset, Private->getExprLoc());
2108 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002109
2110 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2111 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002112
2113 // Store the source element value to the dest element address.
2114 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2115 Private->getType());
2116
2117 // Step 3.1: Modify reference in dest Reduce list as needed.
2118 // Modifying the reference in Reduce list to point to the newly
2119 // created element. The element is live in the current function
2120 // scope and that of functions it invokes (i.e., reduce_function).
2121 // RemoteReduceData[i] = (void*)&RemoteElem
2122 if (UpdateDestListPtr) {
2123 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2124 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2125 DestElementPtrAddr, /*Volatile=*/false,
2126 C.VoidPtrTy);
2127 }
2128
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002129 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2130 // address of the next element in scratchpad memory, unless we're currently
2131 // processing the last one. Memory alignment is also taken care of here.
2132 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2133 llvm::Value *ScratchpadBasePtr =
2134 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002135 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2136 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002137 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002138 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002139
2140 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002141 ScratchpadBasePtr = Bld.CreateNUWSub(
2142 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2143 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002144 ScratchpadBasePtr,
2145 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002146 ScratchpadBasePtr = Bld.CreateNUWAdd(
2147 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2148 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002149 ScratchpadBasePtr,
2150 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2151
2152 if (IncrScratchpadDest)
2153 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2154 else /* IncrScratchpadSrc = true */
2155 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2156 }
2157
Alexey Bataev9ff80832018-04-16 20:16:21 +00002158 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002159 }
2160}
2161
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002162/// This function emits a helper that loads data from the scratchpad array
2163/// and (optionally) reduces it with the input operand.
2164///
2165/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2166/// reduce_data remote;
2167/// for elem in remote:
2168/// remote.elem = Scratchpad[elem_id][index]
2169/// if (should_reduce)
2170/// local = local @ remote
2171/// else
2172/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002173static llvm::Value *emitReduceScratchpadFunction(
2174 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2175 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002176 ASTContext &C = CGM.getContext();
2177 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002178
2179 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002180 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2181 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002182 // Base address of the scratchpad array, with each element storing a
2183 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002184 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2185 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002186 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002187 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2188 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002189 // Row width of an element in the scratchpad array, typically
2190 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002191 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2192 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002193 // If should_reduce == 1, then it's load AND reduce,
2194 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2195 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002196 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2197 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002198
2199 FunctionArgList Args;
2200 Args.push_back(&ReduceListArg);
2201 Args.push_back(&ScratchPadArg);
2202 Args.push_back(&IndexArg);
2203 Args.push_back(&WidthArg);
2204 Args.push_back(&ShouldReduceArg);
2205
Alexey Bataev9ff80832018-04-16 20:16:21 +00002206 const CGFunctionInfo &CGFI =
2207 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002208 auto *Fn = llvm::Function::Create(
2209 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2210 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002211 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002212 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002213 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002214 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002215
Alexey Bataev9ff80832018-04-16 20:16:21 +00002216 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002217
2218 // Get local Reduce list pointer.
2219 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2220 Address ReduceListAddr(
2221 Bld.CreatePointerBitCastOrAddrSpaceCast(
2222 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002223 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002224 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2225 CGF.getPointerAlign());
2226
2227 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2228 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002229 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002230
2231 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002232 llvm::Value *IndexVal = Bld.CreateIntCast(
2233 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2234 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002235
2236 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002237 llvm::Value *WidthVal = Bld.CreateIntCast(
2238 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2239 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002240
2241 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2242 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002243 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002244
2245 // The absolute ptr address to the base addr of the next element to copy.
2246 llvm::Value *CumulativeElemBasePtr =
2247 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2248 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2249
2250 // Create a Remote Reduce list to store the elements read from the
2251 // scratchpad array.
2252 Address RemoteReduceList =
2253 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2254
2255 // Assemble remote Reduce list from scratchpad array.
2256 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2257 SrcDataAddr, RemoteReduceList,
2258 {/*RemoteLaneOffset=*/nullptr,
2259 /*ScratchpadIndex=*/IndexVal,
2260 /*ScratchpadWidth=*/WidthVal});
2261
2262 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2263 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2264 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2265
Alexey Bataev9ff80832018-04-16 20:16:21 +00002266 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002267 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2268
2269 CGF.EmitBlock(ThenBB);
2270 // We should reduce with the local Reduce list.
2271 // reduce_function(LocalReduceList, RemoteReduceList)
2272 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2273 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2274 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2275 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002276 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2277 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002278 Bld.CreateBr(MergeBB);
2279
2280 CGF.EmitBlock(ElseBB);
2281 // No reduction; just copy:
2282 // Local Reduce list = Remote Reduce list.
2283 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2284 RemoteReduceList, ReduceListAddr);
2285 Bld.CreateBr(MergeBB);
2286
2287 CGF.EmitBlock(MergeBB);
2288
2289 CGF.FinishFunction();
2290 return Fn;
2291}
2292
2293/// This function emits a helper that stores reduced data from the team
2294/// master to a scratchpad array in global memory.
2295///
2296/// for elem in Reduce List:
2297/// scratchpad[elem_id][index] = elem
2298///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002299static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2300 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002301 QualType ReductionArrayTy,
2302 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002303
Alexey Bataev9ff80832018-04-16 20:16:21 +00002304 ASTContext &C = CGM.getContext();
2305 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002306
2307 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002308 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2309 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002310 // Base address of the scratchpad array, with each element storing a
2311 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002312 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2313 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002314 // A destination index into the scratchpad array, typically the team
2315 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002316 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2317 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002318 // Row width of an element in the scratchpad array, typically
2319 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002320 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2321 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002322
2323 FunctionArgList Args;
2324 Args.push_back(&ReduceListArg);
2325 Args.push_back(&ScratchPadArg);
2326 Args.push_back(&IndexArg);
2327 Args.push_back(&WidthArg);
2328
Alexey Bataev9ff80832018-04-16 20:16:21 +00002329 const CGFunctionInfo &CGFI =
2330 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002331 auto *Fn = llvm::Function::Create(
2332 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2333 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002334 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002335 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002336 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002337 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002338
Alexey Bataev9ff80832018-04-16 20:16:21 +00002339 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002340
2341 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2342 Address SrcDataAddr(
2343 Bld.CreatePointerBitCastOrAddrSpaceCast(
2344 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002345 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002346 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2347 CGF.getPointerAlign());
2348
2349 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2350 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002351 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002352
2353 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002354 llvm::Value *IndexVal = Bld.CreateIntCast(
2355 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2356 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002357
2358 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2359 llvm::Value *WidthVal =
2360 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2361 Int32Ty, SourceLocation()),
2362 CGF.SizeTy, /*isSigned=*/true);
2363
2364 // The absolute ptr address to the base addr of the next element to copy.
2365 llvm::Value *CumulativeElemBasePtr =
2366 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2367 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2368
2369 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2370 SrcDataAddr, DestDataAddr,
2371 {/*RemoteLaneOffset=*/nullptr,
2372 /*ScratchpadIndex=*/IndexVal,
2373 /*ScratchpadWidth=*/WidthVal});
2374
2375 CGF.FinishFunction();
2376 return Fn;
2377}
2378
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002379/// This function emits a helper that gathers Reduce lists from the first
2380/// lane of every active warp to lanes in the first warp.
2381///
2382/// void inter_warp_copy_func(void* reduce_data, num_warps)
2383/// shared smem[warp_size];
2384/// For all data entries D in reduce_data:
2385/// If (I am the first lane in each warp)
2386/// Copy my local D to smem[warp_id]
2387/// sync
2388/// if (I am the first warp)
2389/// Copy smem[thread_id] to my local D
2390/// sync
2391static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2392 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002393 QualType ReductionArrayTy,
2394 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002395 ASTContext &C = CGM.getContext();
2396 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002397
2398 // ReduceList: thread local Reduce list.
2399 // At the stage of the computation when this function is called, partially
2400 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002401 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2402 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002403 // NumWarps: number of warps active in the parallel region. This could
2404 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002405 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002406 C.getIntTypeForBitwidth(32, /* Signed */ true),
2407 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002408 FunctionArgList Args;
2409 Args.push_back(&ReduceListArg);
2410 Args.push_back(&NumWarpsArg);
2411
Alexey Bataev9ff80832018-04-16 20:16:21 +00002412 const CGFunctionInfo &CGFI =
2413 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002414 auto *Fn = llvm::Function::Create(
2415 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2416 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002417 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002418 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002419 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002420 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002421
Alexey Bataev9ff80832018-04-16 20:16:21 +00002422 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002423
2424 // This array is used as a medium to transfer, one reduce element at a time,
2425 // the data from the first lane of every warp to lanes in the first warp
2426 // in order to perform the final step of a reduction in a parallel region
2427 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2428 // for reduced latency, as well as to have a distinct copy for concurrently
2429 // executing target regions. The array is declared with common linkage so
2430 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002431 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002432 "__openmp_nvptx_data_transfer_temporary_storage";
2433 llvm::GlobalVariable *TransferMedium =
2434 M.getGlobalVariable(TransferMediumName);
2435 if (!TransferMedium) {
2436 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2437 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2438 TransferMedium = new llvm::GlobalVariable(
2439 M, Ty,
2440 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2441 llvm::Constant::getNullValue(Ty), TransferMediumName,
2442 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2443 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002444 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002445 }
2446
2447 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002448 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002449 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002450 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002451 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002452 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002453
2454 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2455 Address LocalReduceList(
2456 Bld.CreatePointerBitCastOrAddrSpaceCast(
2457 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2458 C.VoidPtrTy, SourceLocation()),
2459 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2460 CGF.getPointerAlign());
2461
2462 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002463 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002464 //
2465 // Warp master copies reduce element to transfer medium in __shared__
2466 // memory.
2467 //
2468 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2469 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2470 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2471
2472 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002473 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002474 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2475 CGF.EmitBlock(ThenBB);
2476
2477 // Reduce element = LocalReduceList[i]
2478 Address ElemPtrPtrAddr =
2479 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2480 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2481 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2482 // elemptr = (type[i]*)(elemptrptr)
2483 Address ElemPtr =
2484 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2485 ElemPtr = Bld.CreateElementBitCast(
2486 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2487 // elem = *elemptr
2488 llvm::Value *Elem = CGF.EmitLoadOfScalar(
2489 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2490
2491 // Get pointer to location in transfer medium.
2492 // MediumPtr = &medium[warp_id]
2493 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2494 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2495 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
2496 // Casting to actual data type.
2497 // MediumPtr = (type[i]*)MediumPtrAddr;
2498 MediumPtr = Bld.CreateElementBitCast(
2499 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2500
2501 //*MediumPtr = elem
2502 Bld.CreateStore(Elem, MediumPtr);
2503
2504 Bld.CreateBr(MergeBB);
2505
2506 CGF.EmitBlock(ElseBB);
2507 Bld.CreateBr(MergeBB);
2508
2509 CGF.EmitBlock(MergeBB);
2510
2511 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2512 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2513 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
2514
Alexey Bataev9ff80832018-04-16 20:16:21 +00002515 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002516 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
2517 // named_barrier_sync(ParallelBarrierID, num_active_threads)
2518 syncParallelThreads(CGF, NumActiveThreads);
2519
2520 //
2521 // Warp 0 copies reduce element from transfer medium.
2522 //
2523 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2524 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2525 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2526
2527 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002528 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002529 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2530 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2531
2532 CGF.EmitBlock(W0ThenBB);
2533
2534 // SrcMediumPtr = &medium[tid]
2535 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2536 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2537 Address SrcMediumPtr(SrcMediumPtrVal,
2538 C.getTypeAlignInChars(Private->getType()));
2539 // SrcMediumVal = *SrcMediumPtr;
2540 SrcMediumPtr = Bld.CreateElementBitCast(
2541 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
2542 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
2543 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
2544
2545 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
2546 Address TargetElemPtrPtr =
2547 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2548 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2549 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2550 Address TargetElemPtr =
2551 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
2552 TargetElemPtr = Bld.CreateElementBitCast(
2553 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
2554
2555 // *TargetElemPtr = SrcMediumVal;
2556 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2557 Private->getType());
2558 Bld.CreateBr(W0MergeBB);
2559
2560 CGF.EmitBlock(W0ElseBB);
2561 Bld.CreateBr(W0MergeBB);
2562
2563 CGF.EmitBlock(W0MergeBB);
2564
2565 // While warp 0 copies values from transfer medium, all other warps must
2566 // wait.
2567 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002568 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002569 }
2570
2571 CGF.FinishFunction();
2572 return Fn;
2573}
2574
2575/// Emit a helper that reduces data across two OpenMP threads (lanes)
2576/// in the same warp. It uses shuffle instructions to copy over data from
2577/// a remote lane's stack. The reduction algorithm performed is specified
2578/// by the fourth parameter.
2579///
2580/// Algorithm Versions.
2581/// Full Warp Reduce (argument value 0):
2582/// This algorithm assumes that all 32 lanes are active and gathers
2583/// data from these 32 lanes, producing a single resultant value.
2584/// Contiguous Partial Warp Reduce (argument value 1):
2585/// This algorithm assumes that only a *contiguous* subset of lanes
2586/// are active. This happens for the last warp in a parallel region
2587/// when the user specified num_threads is not an integer multiple of
2588/// 32. This contiguous subset always starts with the zeroth lane.
2589/// Partial Warp Reduce (argument value 2):
2590/// This algorithm gathers data from any number of lanes at any position.
2591/// All reduced values are stored in the lowest possible lane. The set
2592/// of problems every algorithm addresses is a super set of those
2593/// addressable by algorithms with a lower version number. Overhead
2594/// increases as algorithm version increases.
2595///
2596/// Terminology
2597/// Reduce element:
2598/// Reduce element refers to the individual data field with primitive
2599/// data types to be combined and reduced across threads.
2600/// Reduce list:
2601/// Reduce list refers to a collection of local, thread-private
2602/// reduce elements.
2603/// Remote Reduce list:
2604/// Remote Reduce list refers to a collection of remote (relative to
2605/// the current thread) reduce elements.
2606///
2607/// We distinguish between three states of threads that are important to
2608/// the implementation of this function.
2609/// Alive threads:
2610/// Threads in a warp executing the SIMT instruction, as distinguished from
2611/// threads that are inactive due to divergent control flow.
2612/// Active threads:
2613/// The minimal set of threads that has to be alive upon entry to this
2614/// function. The computation is correct iff active threads are alive.
2615/// Some threads are alive but they are not active because they do not
2616/// contribute to the computation in any useful manner. Turning them off
2617/// may introduce control flow overheads without any tangible benefits.
2618/// Effective threads:
2619/// In order to comply with the argument requirements of the shuffle
2620/// function, we must keep all lanes holding data alive. But at most
2621/// half of them perform value aggregation; we refer to this half of
2622/// threads as effective. The other half is simply handing off their
2623/// data.
2624///
2625/// Procedure
2626/// Value shuffle:
2627/// In this step active threads transfer data from higher lane positions
2628/// in the warp to lower lane positions, creating Remote Reduce list.
2629/// Value aggregation:
2630/// In this step, effective threads combine their thread local Reduce list
2631/// with Remote Reduce list and store the result in the thread local
2632/// Reduce list.
2633/// Value copy:
2634/// In this step, we deal with the assumption made by algorithm 2
2635/// (i.e. contiguity assumption). When we have an odd number of lanes
2636/// active, say 2k+1, only k threads will be effective and therefore k
2637/// new values will be produced. However, the Reduce list owned by the
2638/// (2k+1)th thread is ignored in the value aggregation. Therefore
2639/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2640/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002641static llvm::Value *emitShuffleAndReduceFunction(
2642 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2643 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002644 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002645
2646 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002647 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2648 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002649 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002650 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2651 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002652 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002653 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2654 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002655 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002656 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2657 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002658 FunctionArgList Args;
2659 Args.push_back(&ReduceListArg);
2660 Args.push_back(&LaneIDArg);
2661 Args.push_back(&RemoteLaneOffsetArg);
2662 Args.push_back(&AlgoVerArg);
2663
Alexey Bataev9ff80832018-04-16 20:16:21 +00002664 const CGFunctionInfo &CGFI =
2665 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002666 auto *Fn = llvm::Function::Create(
2667 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2668 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002669 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002670 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002671 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002672 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002673
Alexey Bataev9ff80832018-04-16 20:16:21 +00002674 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002675
2676 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2677 Address LocalReduceList(
2678 Bld.CreatePointerBitCastOrAddrSpaceCast(
2679 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2680 C.VoidPtrTy, SourceLocation()),
2681 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2682 CGF.getPointerAlign());
2683
2684 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2685 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2686 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2687
2688 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2689 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2690 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2691
2692 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2693 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2694 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2695
2696 // Create a local thread-private variable to host the Reduce list
2697 // from a remote lane.
2698 Address RemoteReduceList =
2699 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2700
2701 // This loop iterates through the list of reduce elements and copies,
2702 // element by element, from a remote lane in the warp to RemoteReduceList,
2703 // hosted on the thread's stack.
2704 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2705 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002706 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2707 /*ScratchpadIndex=*/nullptr,
2708 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002709
2710 // The actions to be performed on the Remote Reduce list is dependent
2711 // on the algorithm version.
2712 //
2713 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2714 // LaneId % 2 == 0 && Offset > 0):
2715 // do the reduction value aggregation
2716 //
2717 // The thread local variable Reduce list is mutated in place to host the
2718 // reduced data, which is the aggregated value produced from local and
2719 // remote lanes.
2720 //
2721 // Note that AlgoVer is expected to be a constant integer known at compile
2722 // time.
2723 // When AlgoVer==0, the first conjunction evaluates to true, making
2724 // the entire predicate true during compile time.
2725 // When AlgoVer==1, the second conjunction has only the second part to be
2726 // evaluated during runtime. Other conjunctions evaluates to false
2727 // during compile time.
2728 // When AlgoVer==2, the third conjunction has only the second part to be
2729 // evaluated during runtime. Other conjunctions evaluates to false
2730 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002731 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002732
Alexey Bataev9ff80832018-04-16 20:16:21 +00002733 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2734 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002735 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2736
Alexey Bataev9ff80832018-04-16 20:16:21 +00002737 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2738 llvm::Value *CondAlgo2 = Bld.CreateAnd(
2739 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002740 CondAlgo2 = Bld.CreateAnd(
2741 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2742
Alexey Bataev9ff80832018-04-16 20:16:21 +00002743 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002744 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2745
2746 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2747 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2748 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2749 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2750
2751 CGF.EmitBlock(ThenBB);
2752 // reduce_function(LocalReduceList, RemoteReduceList)
2753 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2754 LocalReduceList.getPointer(), CGF.VoidPtrTy);
2755 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2756 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002757 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2758 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002759 Bld.CreateBr(MergeBB);
2760
2761 CGF.EmitBlock(ElseBB);
2762 Bld.CreateBr(MergeBB);
2763
2764 CGF.EmitBlock(MergeBB);
2765
2766 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2767 // Reduce list.
2768 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00002769 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002770 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2771
2772 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2773 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2774 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2775 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2776
2777 CGF.EmitBlock(CpyThenBB);
2778 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2779 RemoteReduceList, LocalReduceList);
2780 Bld.CreateBr(CpyMergeBB);
2781
2782 CGF.EmitBlock(CpyElseBB);
2783 Bld.CreateBr(CpyMergeBB);
2784
2785 CGF.EmitBlock(CpyMergeBB);
2786
2787 CGF.FinishFunction();
2788 return Fn;
2789}
2790
2791///
2792/// Design of OpenMP reductions on the GPU
2793///
2794/// Consider a typical OpenMP program with one or more reduction
2795/// clauses:
2796///
2797/// float foo;
2798/// double bar;
2799/// #pragma omp target teams distribute parallel for \
2800/// reduction(+:foo) reduction(*:bar)
2801/// for (int i = 0; i < N; i++) {
2802/// foo += A[i]; bar *= B[i];
2803/// }
2804///
2805/// where 'foo' and 'bar' are reduced across all OpenMP threads in
2806/// all teams. In our OpenMP implementation on the NVPTX device an
2807/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2808/// within a team are mapped to CUDA threads within a threadblock.
2809/// Our goal is to efficiently aggregate values across all OpenMP
2810/// threads such that:
2811///
2812/// - the compiler and runtime are logically concise, and
2813/// - the reduction is performed efficiently in a hierarchical
2814/// manner as follows: within OpenMP threads in the same warp,
2815/// across warps in a threadblock, and finally across teams on
2816/// the NVPTX device.
2817///
2818/// Introduction to Decoupling
2819///
2820/// We would like to decouple the compiler and the runtime so that the
2821/// latter is ignorant of the reduction variables (number, data types)
2822/// and the reduction operators. This allows a simpler interface
2823/// and implementation while still attaining good performance.
2824///
2825/// Pseudocode for the aforementioned OpenMP program generated by the
2826/// compiler is as follows:
2827///
2828/// 1. Create private copies of reduction variables on each OpenMP
2829/// thread: 'foo_private', 'bar_private'
2830/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2831/// to it and writes the result in 'foo_private' and 'bar_private'
2832/// respectively.
2833/// 3. Call the OpenMP runtime on the GPU to reduce within a team
2834/// and store the result on the team master:
2835///
2836/// __kmpc_nvptx_parallel_reduce_nowait(...,
2837/// reduceData, shuffleReduceFn, interWarpCpyFn)
2838///
2839/// where:
2840/// struct ReduceData {
2841/// double *foo;
2842/// double *bar;
2843/// } reduceData
2844/// reduceData.foo = &foo_private
2845/// reduceData.bar = &bar_private
2846///
2847/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2848/// auxiliary functions generated by the compiler that operate on
2849/// variables of type 'ReduceData'. They aid the runtime perform
2850/// algorithmic steps in a data agnostic manner.
2851///
2852/// 'shuffleReduceFn' is a pointer to a function that reduces data
2853/// of type 'ReduceData' across two OpenMP threads (lanes) in the
2854/// same warp. It takes the following arguments as input:
2855///
2856/// a. variable of type 'ReduceData' on the calling lane,
2857/// b. its lane_id,
2858/// c. an offset relative to the current lane_id to generate a
2859/// remote_lane_id. The remote lane contains the second
2860/// variable of type 'ReduceData' that is to be reduced.
2861/// d. an algorithm version parameter determining which reduction
2862/// algorithm to use.
2863///
2864/// 'shuffleReduceFn' retrieves data from the remote lane using
2865/// efficient GPU shuffle intrinsics and reduces, using the
2866/// algorithm specified by the 4th parameter, the two operands
2867/// element-wise. The result is written to the first operand.
2868///
2869/// Different reduction algorithms are implemented in different
2870/// runtime functions, all calling 'shuffleReduceFn' to perform
2871/// the essential reduction step. Therefore, based on the 4th
2872/// parameter, this function behaves slightly differently to
2873/// cooperate with the runtime to ensure correctness under
2874/// different circumstances.
2875///
2876/// 'InterWarpCpyFn' is a pointer to a function that transfers
2877/// reduced variables across warps. It tunnels, through CUDA
2878/// shared memory, the thread-private data of type 'ReduceData'
2879/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002880/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
2881/// The last team writes the global reduced value to memory.
2882///
2883/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
2884/// reduceData, shuffleReduceFn, interWarpCpyFn,
2885/// scratchpadCopyFn, loadAndReduceFn)
2886///
2887/// 'scratchpadCopyFn' is a helper that stores reduced
2888/// data from the team master to a scratchpad array in
2889/// global memory.
2890///
2891/// 'loadAndReduceFn' is a helper that loads data from
2892/// the scratchpad array and reduces it with the input
2893/// operand.
2894///
2895/// These compiler generated functions hide address
2896/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002897/// 5. if ret == 1:
2898/// The team master of the last team stores the reduced
2899/// result to the globals in memory.
2900/// foo += reduceData.foo; bar *= reduceData.bar
2901///
2902///
2903/// Warp Reduction Algorithms
2904///
2905/// On the warp level, we have three algorithms implemented in the
2906/// OpenMP runtime depending on the number of active lanes:
2907///
2908/// Full Warp Reduction
2909///
2910/// The reduce algorithm within a warp where all lanes are active
2911/// is implemented in the runtime as follows:
2912///
2913/// full_warp_reduce(void *reduce_data,
2914/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2915/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
2916/// ShuffleReduceFn(reduce_data, 0, offset, 0);
2917/// }
2918///
2919/// The algorithm completes in log(2, WARPSIZE) steps.
2920///
2921/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
2922/// not used therefore we save instructions by not retrieving lane_id
2923/// from the corresponding special registers. The 4th parameter, which
2924/// represents the version of the algorithm being used, is set to 0 to
2925/// signify full warp reduction.
2926///
2927/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2928///
2929/// #reduce_elem refers to an element in the local lane's data structure
2930/// #remote_elem is retrieved from a remote lane
2931/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2932/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
2933///
2934/// Contiguous Partial Warp Reduction
2935///
2936/// This reduce algorithm is used within a warp where only the first
2937/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2938/// number of OpenMP threads in a parallel region is not a multiple of
2939/// WARPSIZE. The algorithm is implemented in the runtime as follows:
2940///
2941/// void
2942/// contiguous_partial_reduce(void *reduce_data,
2943/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2944/// int size, int lane_id) {
2945/// int curr_size;
2946/// int offset;
2947/// curr_size = size;
2948/// mask = curr_size/2;
2949/// while (offset>0) {
2950/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2951/// curr_size = (curr_size+1)/2;
2952/// offset = curr_size/2;
2953/// }
2954/// }
2955///
2956/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2957///
2958/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2959/// if (lane_id < offset)
2960/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2961/// else
2962/// reduce_elem = remote_elem
2963///
2964/// This algorithm assumes that the data to be reduced are located in a
2965/// contiguous subset of lanes starting from the first. When there is
2966/// an odd number of active lanes, the data in the last lane is not
2967/// aggregated with any other lane's dat but is instead copied over.
2968///
2969/// Dispersed Partial Warp Reduction
2970///
2971/// This algorithm is used within a warp when any discontiguous subset of
2972/// lanes are active. It is used to implement the reduction operation
2973/// across lanes in an OpenMP simd region or in a nested parallel region.
2974///
2975/// void
2976/// dispersed_partial_reduce(void *reduce_data,
2977/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2978/// int size, remote_id;
2979/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2980/// do {
2981/// remote_id = next_active_lane_id_right_after_me();
2982/// # the above function returns 0 of no active lane
2983/// # is present right after the current lane.
2984/// size = number_of_active_lanes_in_this_warp();
2985/// logical_lane_id /= 2;
2986/// ShuffleReduceFn(reduce_data, logical_lane_id,
2987/// remote_id-1-threadIdx.x, 2);
2988/// } while (logical_lane_id % 2 == 0 && size > 1);
2989/// }
2990///
2991/// There is no assumption made about the initial state of the reduction.
2992/// Any number of lanes (>=1) could be active at any position. The reduction
2993/// result is returned in the first active lane.
2994///
2995/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2996///
2997/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2998/// if (lane_id % 2 == 0 && offset > 0)
2999/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3000/// else
3001/// reduce_elem = remote_elem
3002///
3003///
3004/// Intra-Team Reduction
3005///
3006/// This function, as implemented in the runtime call
3007/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3008/// threads in a team. It first reduces within a warp using the
3009/// aforementioned algorithms. We then proceed to gather all such
3010/// reduced values at the first warp.
3011///
3012/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3013/// data from each of the "warp master" (zeroth lane of each warp, where
3014/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3015/// a mathematical sense) the problem of reduction across warp masters in
3016/// a block to the problem of warp reduction.
3017///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003018///
3019/// Inter-Team Reduction
3020///
3021/// Once a team has reduced its data to a single value, it is stored in
3022/// a global scratchpad array. Since each team has a distinct slot, this
3023/// can be done without locking.
3024///
3025/// The last team to write to the scratchpad array proceeds to reduce the
3026/// scratchpad array. One or more workers in the last team use the helper
3027/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3028/// the k'th worker reduces every k'th element.
3029///
3030/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3031/// reduce across workers and compute a globally reduced value.
3032///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003033void CGOpenMPRuntimeNVPTX::emitReduction(
3034 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3035 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3036 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3037 if (!CGF.HaveInsertPoint())
3038 return;
3039
3040 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003041 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003042 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3043 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003044 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003045
Alexey Bataev9ff80832018-04-16 20:16:21 +00003046 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003047
3048 // 1. Build a list of reduction variables.
3049 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3050 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003051 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003052 if (E->getType()->isVariablyModifiedType())
3053 // Reserve place for array size.
3054 ++Size;
3055 }
3056 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3057 QualType ReductionArrayTy =
3058 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3059 /*IndexTypeQuals=*/0);
3060 Address ReductionList =
3061 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3062 auto IPriv = Privates.begin();
3063 unsigned Idx = 0;
3064 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3065 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3066 CGF.getPointerSize());
3067 CGF.Builder.CreateStore(
3068 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3069 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3070 Elem);
3071 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3072 // Store array size.
3073 ++Idx;
3074 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3075 CGF.getPointerSize());
3076 llvm::Value *Size = CGF.Builder.CreateIntCast(
3077 CGF.getVLASize(
3078 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003079 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003080 CGF.SizeTy, /*isSigned=*/false);
3081 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3082 Elem);
3083 }
3084 }
3085
3086 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003087 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003088 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3089 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003090
3091 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3092 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003093 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3094 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3095 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003096 ReductionList.getPointer(), CGF.VoidPtrTy);
3097
Alexey Bataev9ff80832018-04-16 20:16:21 +00003098 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003099 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003100 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003101 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003102
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003103 llvm::Value *Args[] = {ThreadId,
3104 CGF.Builder.getInt32(RHSExprs.size()),
3105 ReductionArrayTySize,
3106 RL,
3107 ShuffleAndReduceFn,
3108 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003110 llvm::Value *Res = nullptr;
3111 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003112 Res = CGF.EmitRuntimeCall(
3113 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3114 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003115 else if (SimdReduction)
3116 Res = CGF.EmitRuntimeCall(
3117 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3118 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003119
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003120 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003121 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003122 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003123 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003124 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003125
3126 llvm::Value *Args[] = {ThreadId,
3127 CGF.Builder.getInt32(RHSExprs.size()),
3128 ReductionArrayTySize,
3129 RL,
3130 ShuffleAndReduceFn,
3131 InterWarpCopyFn,
3132 ScratchPadCopyFn,
3133 LoadAndReduceFn};
3134 Res = CGF.EmitRuntimeCall(
3135 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3136 Args);
3137 }
3138
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003139 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003140 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3141 llvm::SwitchInst *SwInst =
3142 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143
3144 // 6. Build case 1: where we have reduced values in the master
3145 // thread in each team.
3146 // __kmpc_end_reduce{_nowait}(<gtid>);
3147 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003148 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3150 CGF.EmitBlock(Case1BB);
3151
3152 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3153 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003154 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003155 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3156 auto IPriv = Privates.begin();
3157 auto ILHS = LHSExprs.begin();
3158 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003159 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3161 cast<DeclRefExpr>(*IRHS));
3162 ++IPriv;
3163 ++ILHS;
3164 ++IRHS;
3165 }
3166 };
3167 RegionCodeGenTy RCG(CodeGen);
3168 NVPTXActionTy Action(
3169 nullptr, llvm::None,
3170 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3171 EndArgs);
3172 RCG.setAction(Action);
3173 RCG(CGF);
3174 CGF.EmitBranch(DefaultBB);
3175 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3176}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003177
3178const VarDecl *
3179CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3180 const VarDecl *NativeParam) const {
3181 if (!NativeParam->getType()->isReferenceType())
3182 return NativeParam;
3183 QualType ArgType = NativeParam->getType();
3184 QualifierCollector QC;
3185 const Type *NonQualTy = QC.strip(ArgType);
3186 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3187 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3188 if (Attr->getCaptureKind() == OMPC_map) {
3189 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3190 LangAS::opencl_global);
3191 }
3192 }
3193 ArgType = CGM.getContext().getPointerType(PointeeTy);
3194 QC.addRestrict();
3195 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003196 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003197 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003198 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003199 return ImplicitParamDecl::Create(
3200 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3201 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003202 return ParmVarDecl::Create(
3203 CGM.getContext(),
3204 const_cast<DeclContext *>(NativeParam->getDeclContext()),
3205 NativeParam->getLocStart(), NativeParam->getLocation(),
3206 NativeParam->getIdentifier(), ArgType,
3207 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003208}
3209
3210Address
3211CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3212 const VarDecl *NativeParam,
3213 const VarDecl *TargetParam) const {
3214 assert(NativeParam != TargetParam &&
3215 NativeParam->getType()->isReferenceType() &&
3216 "Native arg must not be the same as target arg.");
3217 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3218 QualType NativeParamType = NativeParam->getType();
3219 QualifierCollector QC;
3220 const Type *NonQualTy = QC.strip(NativeParamType);
3221 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3222 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003223 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003224 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003225 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003226 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003227 // First cast to generic.
3228 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3229 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3230 /*AddrSpace=*/0));
3231 // Cast from generic to native address space.
3232 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3233 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3234 NativePointeeAddrSpace));
3235 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3236 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003237 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003238 return NativeParamAddr;
3239}
3240
3241void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003242 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003243 ArrayRef<llvm::Value *> Args) const {
3244 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003245 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003246 auto *FnType =
3247 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3248 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003249 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3250 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3251 break;
3252 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003253 llvm::Type *TargetType = FnType->getParamType(I);
3254 llvm::Value *NativeArg = Args[I];
3255 if (!TargetType->isPointerTy()) {
3256 TargetArgs.emplace_back(NativeArg);
3257 continue;
3258 }
3259 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003260 NativeArg,
3261 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003262 TargetArgs.emplace_back(
3263 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3264 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003265 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003266}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003267
3268/// Emit function which wraps the outline parallel region
3269/// and controls the arguments which are passed to this function.
3270/// The wrapper ensures that the outlined function is called
3271/// with the correct arguments when data is shared.
3272llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3273 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3274 ASTContext &Ctx = CGM.getContext();
3275 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3276
3277 // Create a function that takes as argument the source thread.
3278 FunctionArgList WrapperArgs;
3279 QualType Int16QTy =
3280 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3281 QualType Int32QTy =
3282 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3283 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3284 /*Id=*/nullptr, Int16QTy,
3285 ImplicitParamDecl::Other);
3286 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getLocStart(),
3287 /*Id=*/nullptr, Int32QTy,
3288 ImplicitParamDecl::Other);
3289 WrapperArgs.emplace_back(&ParallelLevelArg);
3290 WrapperArgs.emplace_back(&WrapperArg);
3291
Alexey Bataev9ff80832018-04-16 20:16:21 +00003292 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003293 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3294
3295 auto *Fn = llvm::Function::Create(
3296 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003297 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003298 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003299 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003300 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003301
3302 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3303 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3304 D.getLocStart(), D.getLocStart());
3305
3306 const auto *RD = CS.getCapturedRecordDecl();
3307 auto CurField = RD->field_begin();
3308
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003309 Address ZeroAddr = CGF.CreateMemTemp(
3310 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3311 /*Name*/ ".zero.addr");
3312 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003313 // Get the array of arguments.
3314 SmallVector<llvm::Value *, 8> Args;
3315
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003316 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3317 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003318
3319 CGBuilderTy &Bld = CGF.Builder;
3320 auto CI = CS.capture_begin();
3321
3322 // Use global memory for data sharing.
3323 // Handle passing of global args to workers.
3324 Address GlobalArgs =
3325 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3326 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3327 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3328 CGF.EmitRuntimeCall(
3329 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3330 DataSharingArgs);
3331
3332 // Retrieve the shared variables from the list of references returned
3333 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003334 Address SharedArgListAddress = Address::invalid();
3335 if (CS.capture_size() > 0 ||
3336 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3337 SharedArgListAddress = CGF.EmitLoadOfPointer(
3338 GlobalArgs, CGF.getContext()
3339 .getPointerType(CGF.getContext().getPointerType(
3340 CGF.getContext().VoidPtrTy))
3341 .castAs<PointerType>());
3342 }
3343 unsigned Idx = 0;
3344 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3345 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3346 CGF.getPointerSize());
3347 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3348 Src, CGF.SizeTy->getPointerTo());
3349 llvm::Value *LB = CGF.EmitLoadOfScalar(
3350 TypedAddress,
3351 /*Volatile=*/false,
3352 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3353 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3354 Args.emplace_back(LB);
3355 ++Idx;
3356 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3357 CGF.getPointerSize());
3358 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3359 Src, CGF.SizeTy->getPointerTo());
3360 llvm::Value *UB = CGF.EmitLoadOfScalar(
3361 TypedAddress,
3362 /*Volatile=*/false,
3363 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3364 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3365 Args.emplace_back(UB);
3366 ++Idx;
3367 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003368 if (CS.capture_size() > 0) {
3369 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003370 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3371 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003372 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3373 CGF.getPointerSize());
3374 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003375 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3376 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3377 /*Volatile=*/false,
3378 CGFContext.getPointerType(ElemTy),
3379 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003380 if (CI->capturesVariableByCopy() &&
3381 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003382 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3383 CI->getLocation());
3384 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003385 Args.emplace_back(Arg);
3386 }
3387 }
3388
3389 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedParallelFn, Args);
3390 CGF.FinishFunction();
3391 return Fn;
3392}
3393
3394void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3395 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003396 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3397 return;
3398
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003399 assert(D && "Expected function or captured|block decl.");
3400 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3401 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003402 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003403 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003404 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3405 Body = FD->getBody();
3406 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3407 Body = BD->getBody();
3408 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3409 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003410 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003411 }
3412 if (!Body)
3413 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003414 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003415 VarChecker.Visit(Body);
3416 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003417 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3418 VarChecker.getEscapedVariableLengthDecls();
3419 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003420 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003421 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3422 I->getSecond().MappedParams =
3423 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3424 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3425 I->getSecond().EscapedParameters.insert(
3426 VarChecker.getEscapedParameters().begin(),
3427 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003428 I->getSecond().EscapedVariableLengthDecls.append(
3429 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003430 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003431 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003432 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003433 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003434 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3435 }
3436 if (!NeedToDelayGlobalization) {
3437 emitGenericVarsProlog(CGF, D->getLocStart());
3438 struct GlobalizationScope final : EHScopeStack::Cleanup {
3439 GlobalizationScope() = default;
3440
3441 void Emit(CodeGenFunction &CGF, Flags flags) override {
3442 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3443 .emitGenericVarsEpilog(CGF);
3444 }
3445 };
3446 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003447 }
3448}
3449
3450Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3451 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003452 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3453 return Address::invalid();
3454
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003455 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003456 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3457 if (I == FunctionGlobalizedDecls.end())
3458 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003459 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003460 if (VDI != I->getSecond().LocalVarData.end())
3461 return VDI->second.second;
3462 if (VD->hasAttrs()) {
3463 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3464 E(VD->attr_end());
3465 IT != E; ++IT) {
3466 auto VDI = I->getSecond().LocalVarData.find(
3467 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3468 ->getCanonicalDecl());
3469 if (VDI != I->getSecond().LocalVarData.end())
3470 return VDI->second.second;
3471 }
3472 }
3473 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003474}
3475
3476void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003477 FunctionGlobalizedDecls.erase(CGF.CurFn);
3478 CGOpenMPRuntime::functionFinished(CGF);
3479}