blob: c5346315ac156e41bb2871ed8bd2615357a27337 [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"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000016#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000017#include "CodeGenFunction.h"
18#include "clang/AST/StmtOpenMP.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000019
20using namespace clang;
21using namespace CodeGen;
22
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000023namespace {
24enum OpenMPRTLFunctionNVPTX {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000025 /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000026 OMPRTL_NVPTX__kmpc_kernel_init,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000027 /// \brief Call to void __kmpc_kernel_deinit();
28 OMPRTL_NVPTX__kmpc_kernel_deinit,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000029 /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
30 /// short RequiresOMPRuntime, short RequiresDataSharing);
31 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
32 /// \brief Call to void __kmpc_spmd_kernel_deinit();
33 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000034 /// \brief Call to void __kmpc_kernel_prepare_parallel(void
35 /// *outlined_function);
36 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
37 /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function);
38 OMPRTL_NVPTX__kmpc_kernel_parallel,
39 /// \brief Call to void __kmpc_kernel_end_parallel();
40 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
41 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
42 /// global_tid);
43 OMPRTL_NVPTX__kmpc_serialized_parallel,
44 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
45 /// global_tid);
46 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000047 /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element,
48 /// int16_t lane_offset, int16_t warp_size);
49 OMPRTL_NVPTX__kmpc_shuffle_int32,
50 /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element,
51 /// int16_t lane_offset, int16_t warp_size);
52 OMPRTL_NVPTX__kmpc_shuffle_int64,
53 /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
54 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
55 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
56 /// lane_offset, int16_t shortCircuit),
57 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
58 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000059 /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
60 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
61 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
62 /// lane_offset, int16_t shortCircuit),
63 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
64 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
65 /// int32_t index, int32_t width),
66 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
67 /// index, int32_t width, int32_t reduce))
68 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000069 /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
70 OMPRTL_NVPTX__kmpc_end_reduce_nowait
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000071};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000072
73/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
74class NVPTXActionTy final : public PrePostActionTy {
75 llvm::Value *EnterCallee;
76 ArrayRef<llvm::Value *> EnterArgs;
77 llvm::Value *ExitCallee;
78 ArrayRef<llvm::Value *> ExitArgs;
79 bool Conditional;
80 llvm::BasicBlock *ContBlock = nullptr;
81
82public:
83 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
84 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
85 bool Conditional = false)
86 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
87 ExitArgs(ExitArgs), Conditional(Conditional) {}
88 void Enter(CodeGenFunction &CGF) override {
89 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
90 if (Conditional) {
91 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
92 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
93 ContBlock = CGF.createBasicBlock("omp_if.end");
94 // Generate the branch (If-stmt)
95 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
96 CGF.EmitBlock(ThenBlock);
97 }
98 }
99 void Done(CodeGenFunction &CGF) {
100 // Emit the rest of blocks/branches
101 CGF.EmitBranch(ContBlock);
102 CGF.EmitBlock(ContBlock, true);
103 }
104 void Exit(CodeGenFunction &CGF) override {
105 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
106 }
107};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000108
109// A class to track the execution mode when codegening directives within
110// a target region. The appropriate mode (generic/spmd) is set on entry
111// to the target region and used by containing directives such as 'parallel'
112// to emit optimized code.
113class ExecutionModeRAII {
114private:
115 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
116 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
117
118public:
119 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode,
120 CGOpenMPRuntimeNVPTX::ExecutionMode NewMode)
121 : Mode(Mode) {
122 SavedMode = Mode;
123 Mode = NewMode;
124 }
125 ~ExecutionModeRAII() { Mode = SavedMode; }
126};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000127
128/// GPU Configuration: This information can be derived from cuda registers,
129/// however, providing compile time constants helps generate more efficient
130/// code. For all practical purposes this is fine because the configuration
131/// is the same for all known NVPTX architectures.
132enum MachineConfiguration : unsigned {
133 WarpSize = 32,
134 /// Number of bits required to represent a lane identifier, which is
135 /// computed as log_2(WarpSize).
136 LaneIDBits = 5,
137 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000138
139 /// Global memory alignment for performance.
140 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000141};
142
143enum NamedBarrier : unsigned {
144 /// Synchronize on this barrier #ID using a named barrier primitive.
145 /// Only the subset of active threads in a parallel region arrive at the
146 /// barrier.
147 NB_Parallel = 1,
148};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000149} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000150
151/// Get the GPU warp size.
152static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000153 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000154 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000155 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000156 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000157}
158
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000159/// Get the id of the current thread on the GPU.
160static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000161 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000162 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000163 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000164 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000165}
166
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000167/// Get the id of the warp in the block.
168/// We assume that the warp size is 32, which is always the case
169/// on the NVPTX device, to generate more efficient code.
170static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
171 CGBuilderTy &Bld = CGF.Builder;
172 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
173}
174
175/// Get the id of the current lane in the Warp.
176/// We assume that the warp size is 32, which is always the case
177/// on the NVPTX device, to generate more efficient code.
178static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
179 CGBuilderTy &Bld = CGF.Builder;
180 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
181 "nvptx_lane_id");
182}
183
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000184/// Get the maximum number of threads in a block of the GPU.
185static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000186 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000187 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000188 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000189 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000190}
191
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000192/// Get barrier to synchronize all threads in a block.
193static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000194 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000195 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000196}
197
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000198/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
199/// a CTA.
200static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
201 llvm::Value *NumThreads) {
202 CGBuilderTy &Bld = CGF.Builder;
203 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000204 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
205 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
206 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000207}
208
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000209/// Synchronize all GPU threads in a block.
210static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000211
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000212/// Synchronize worker threads in a parallel region.
213static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
214 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
215}
216
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000217/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000218/// For the 'generic' execution mode, the runtime encodes thread_limit in
219/// the launch parameters, always starting thread_limit+warpSize threads per
220/// CTA. The threads in the last warp are reserved for master execution.
221/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
222static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
223 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000224 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000225 return IsInSpmdExecutionMode
226 ? getNVPTXNumThreads(CGF)
227 : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
228 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000229}
230
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000231/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000232/// The master thread id is the first thread (lane) of the last warp in the
233/// GPU block. Warp size is assumed to be some power of 2.
234/// Thread id is 0 indexed.
235/// E.g: If NumThreads is 33, master id is 32.
236/// If NumThreads is 64, master id is 32.
237/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000238static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000239 CGBuilderTy &Bld = CGF.Builder;
240 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
241
242 // We assume that the warp size is a power of 2.
243 llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
244
245 return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)),
246 Bld.CreateNot(Mask), "master_tid");
247}
248
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000249CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
250 CodeGenModule &CGM)
251 : WorkerFn(nullptr), CGFI(nullptr) {
252 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000253}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000254
255void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
256 CodeGenModule &CGM) {
257 // Create an worker function with no arguments.
258 CGFI = &CGM.getTypes().arrangeNullaryFunction();
259
260 WorkerFn = llvm::Function::Create(
261 CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage,
262 /* placeholder */ "_worker", &CGM.getModule());
263 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, WorkerFn, *CGFI);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000264}
265
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000266bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const {
267 return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd;
268}
269
270static CGOpenMPRuntimeNVPTX::ExecutionMode
271getExecutionModeForDirective(CodeGenModule &CGM,
272 const OMPExecutableDirective &D) {
273 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
274 switch (DirectiveKind) {
275 case OMPD_target:
Arpith Chacko Jacobcca61a32017-01-26 15:43:27 +0000276 case OMPD_target_teams:
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000277 return CGOpenMPRuntimeNVPTX::ExecutionMode::Generic;
278 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +0000279 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +0000280 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000281 return CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd;
282 default:
283 llvm_unreachable("Unsupported directive on NVPTX device.");
284 }
285 llvm_unreachable("Unsupported directive on NVPTX device.");
286}
287
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000288void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D,
289 StringRef ParentName,
290 llvm::Function *&OutlinedFn,
291 llvm::Constant *&OutlinedFnID,
292 bool IsOffloadEntry,
293 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000294 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
295 CGOpenMPRuntimeNVPTX::ExecutionMode::Generic);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000296 EntryFunctionState EST;
297 WorkerFunctionState WST(CGM);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000298 Work.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000299
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000300 // Emit target region as a standalone region.
301 class NVPTXPrePostActionTy : public PrePostActionTy {
302 CGOpenMPRuntimeNVPTX &RT;
303 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
304 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000305
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000306 public:
307 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
308 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
309 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
310 : RT(RT), EST(EST), WST(WST) {}
311 void Enter(CodeGenFunction &CGF) override {
312 RT.emitGenericEntryHeader(CGF, EST, WST);
313 }
314 void Exit(CodeGenFunction &CGF) override {
315 RT.emitGenericEntryFooter(CGF, EST);
316 }
317 } Action(*this, EST, WST);
318 CodeGen.setAction(Action);
319 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
320 IsOffloadEntry, CodeGen);
321
322 // Create the worker function
323 emitWorkerFunction(WST);
324
325 // Now change the name of the worker function to correspond to this target
326 // region's entry function.
327 WST.WorkerFn->setName(OutlinedFn->getName() + "_worker");
328}
329
330// Setup NVPTX threads for master-worker OpenMP scheme.
331void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF,
332 EntryFunctionState &EST,
333 WorkerFunctionState &WST) {
334 CGBuilderTy &Bld = CGF.Builder;
335
336 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
337 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
338 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
339 EST.ExitBB = CGF.createBasicBlock(".exit");
340
341 auto *IsWorker =
342 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
343 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
344
345 CGF.EmitBlock(WorkerBB);
Alexey Bataev3c595a62017-08-14 15:01:03 +0000346 emitCall(CGF, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000347 CGF.EmitBranch(EST.ExitBB);
348
349 CGF.EmitBlock(MasterCheckBB);
350 auto *IsMaster =
351 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
352 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
353
354 CGF.EmitBlock(MasterBB);
355 // First action in sequential region:
356 // Initialize the state of the OpenMP runtime library on the GPU.
357 llvm::Value *Args[] = {getThreadLimit(CGF)};
358 CGF.EmitRuntimeCall(
359 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
360}
361
362void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF,
363 EntryFunctionState &EST) {
364 if (!EST.ExitBB)
365 EST.ExitBB = CGF.createBasicBlock(".exit");
366
367 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
368 CGF.EmitBranch(TerminateBB);
369
370 CGF.EmitBlock(TerminateBB);
371 // Signal termination condition.
372 CGF.EmitRuntimeCall(
373 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), None);
374 // Barrier to terminate worker threads.
375 syncCTAThreads(CGF);
376 // Master thread jumps to exit point.
377 CGF.EmitBranch(EST.ExitBB);
378
379 CGF.EmitBlock(EST.ExitBB);
380 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000381}
382
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000383void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
384 StringRef ParentName,
385 llvm::Function *&OutlinedFn,
386 llvm::Constant *&OutlinedFnID,
387 bool IsOffloadEntry,
388 const RegionCodeGenTy &CodeGen) {
389 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
390 CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd);
391 EntryFunctionState EST;
392
393 // Emit target region as a standalone region.
394 class NVPTXPrePostActionTy : public PrePostActionTy {
395 CGOpenMPRuntimeNVPTX &RT;
396 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
397 const OMPExecutableDirective &D;
398
399 public:
400 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
401 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
402 const OMPExecutableDirective &D)
403 : RT(RT), EST(EST), D(D) {}
404 void Enter(CodeGenFunction &CGF) override {
405 RT.emitSpmdEntryHeader(CGF, EST, D);
406 }
407 void Exit(CodeGenFunction &CGF) override {
408 RT.emitSpmdEntryFooter(CGF, EST);
409 }
410 } Action(*this, EST, D);
411 CodeGen.setAction(Action);
412 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
413 IsOffloadEntry, CodeGen);
414 return;
415}
416
417void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
418 CodeGenFunction &CGF, EntryFunctionState &EST,
419 const OMPExecutableDirective &D) {
420 auto &Bld = CGF.Builder;
421
422 // Setup BBs in entry function.
423 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
424 EST.ExitBB = CGF.createBasicBlock(".exit");
425
426 // Initialize the OMP state in the runtime; called by all active threads.
427 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
428 // based on code analysis of the target region.
429 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
430 /*RequiresOMPRuntime=*/Bld.getInt16(1),
431 /*RequiresDataSharing=*/Bld.getInt16(1)};
432 CGF.EmitRuntimeCall(
433 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
434 CGF.EmitBranch(ExecuteBB);
435
436 CGF.EmitBlock(ExecuteBB);
437}
438
439void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
440 EntryFunctionState &EST) {
441 if (!EST.ExitBB)
442 EST.ExitBB = CGF.createBasicBlock(".exit");
443
444 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
445 CGF.EmitBranch(OMPDeInitBB);
446
447 CGF.EmitBlock(OMPDeInitBB);
448 // DeInitialize the OMP state in the runtime; called by all active threads.
449 CGF.EmitRuntimeCall(
450 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
451 CGF.EmitBranch(EST.ExitBB);
452
453 CGF.EmitBlock(EST.ExitBB);
454 EST.ExitBB = nullptr;
455}
456
457// Create a unique global variable to indicate the execution mode of this target
458// region. The execution mode is either 'generic', or 'spmd' depending on the
459// target directive. This variable is picked up by the offload library to setup
460// the device appropriately before kernel launch. If the execution mode is
461// 'generic', the runtime reserves one warp for the master, otherwise, all
462// warps participate in parallel work.
463static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
464 CGOpenMPRuntimeNVPTX::ExecutionMode Mode) {
465 (void)new llvm::GlobalVariable(
466 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
467 llvm::GlobalValue::WeakAnyLinkage,
468 llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode"));
469}
470
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000471void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
472 auto &Ctx = CGM.getContext();
473
474 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000475 CGF.disableDebugInfo();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000476 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {});
477 emitWorkerLoop(CGF, WST);
478 CGF.FinishFunction();
479}
480
481void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
482 WorkerFunctionState &WST) {
483 //
484 // The workers enter this loop and wait for parallel work from the master.
485 // When the master encounters a parallel region it sets up the work + variable
486 // arguments, and wakes up the workers. The workers first check to see if
487 // they are required for the parallel region, i.e., within the # of requested
488 // parallel threads. The activated workers load the variable arguments and
489 // execute the parallel work.
490 //
491
492 CGBuilderTy &Bld = CGF.Builder;
493
494 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
495 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
496 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
497 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
498 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
499 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
500
501 CGF.EmitBranch(AwaitBB);
502
503 // Workers wait for work from master.
504 CGF.EmitBlock(AwaitBB);
505 // Wait for parallel work
506 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000507
508 Address WorkFn =
509 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
510 Address ExecStatus =
511 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
512 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
513 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
514
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000515 llvm::Value *Args[] = {WorkFn.getPointer()};
516 llvm::Value *Ret = CGF.EmitRuntimeCall(
517 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
518 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000519
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000520 // On termination condition (workid == 0), exit loop.
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000521 llvm::Value *ShouldTerminate =
522 Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000523 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
524
525 // Activate requested workers.
526 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000527 llvm::Value *IsActive =
528 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
529 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000530
531 // Signal start of parallel region.
532 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000533
534 // Process work items: outlined parallel functions.
535 for (auto *W : Work) {
536 // Try to match this outlined function.
537 auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
538
539 llvm::Value *WorkFnMatch =
540 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
541
542 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
543 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
544 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
545
546 // Execute this outlined function.
547 CGF.EmitBlock(ExecuteFNBB);
548
549 // Insert call to work function.
550 // FIXME: Pass arguments to outlined function from master thread.
551 auto *Fn = cast<llvm::Function>(W);
552 Address ZeroAddr =
553 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, /*Name=*/".zero.addr");
554 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C=*/0));
555 llvm::Value *FnArgs[] = {ZeroAddr.getPointer(), ZeroAddr.getPointer()};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000556 emitCall(CGF, Fn, FnArgs);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000557
558 // Go to end of parallel region.
559 CGF.EmitBranch(TerminateBB);
560
561 CGF.EmitBlock(CheckNextBB);
562 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000563
564 // Signal end of parallel region.
565 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000566 CGF.EmitRuntimeCall(
567 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
568 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000569 CGF.EmitBranch(BarrierBB);
570
571 // All active and inactive workers wait at a barrier after parallel region.
572 CGF.EmitBlock(BarrierBB);
573 // Barrier after parallel region.
574 syncCTAThreads(CGF);
575 CGF.EmitBranch(AwaitBB);
576
577 // Exit target region.
578 CGF.EmitBlock(ExitBB);
579}
580
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000581/// \brief Returns specified OpenMP runtime function for the current OpenMP
582/// implementation. Specialized for the NVPTX device.
583/// \param Function OpenMP runtime function.
584/// \return Specified function.
585llvm::Constant *
586CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
587 llvm::Constant *RTLFn = nullptr;
588 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
589 case OMPRTL_NVPTX__kmpc_kernel_init: {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000590 // Build void __kmpc_kernel_init(kmp_int32 thread_limit);
591 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000592 llvm::FunctionType *FnTy =
593 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
594 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
595 break;
596 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000597 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
598 // Build void __kmpc_kernel_deinit();
599 llvm::FunctionType *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000600 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
602 break;
603 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000604 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
605 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
606 // short RequiresOMPRuntime, short RequiresDataSharing);
607 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
608 llvm::FunctionType *FnTy =
609 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
611 break;
612 }
613 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
614 // Build void __kmpc_spmd_kernel_deinit();
615 llvm::FunctionType *FnTy =
616 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
618 break;
619 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000620 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
621 /// Build void __kmpc_kernel_prepare_parallel(
622 /// void *outlined_function);
623 llvm::Type *TypeParams[] = {CGM.Int8PtrTy};
624 llvm::FunctionType *FnTy =
625 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
626 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
627 break;
628 }
629 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
630 /// Build bool __kmpc_kernel_parallel(void **outlined_function);
631 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy};
632 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
633 llvm::FunctionType *FnTy =
634 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
635 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
636 break;
637 }
638 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
639 /// Build void __kmpc_kernel_end_parallel();
640 llvm::FunctionType *FnTy =
641 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
643 break;
644 }
645 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
646 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
647 // global_tid);
648 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
649 llvm::FunctionType *FnTy =
650 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
652 break;
653 }
654 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
655 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
656 // global_tid);
657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
658 llvm::FunctionType *FnTy =
659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
661 break;
662 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000663 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
664 // Build int32_t __kmpc_shuffle_int32(int32_t element,
665 // int16_t lane_offset, int16_t warp_size);
666 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
667 llvm::FunctionType *FnTy =
668 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
669 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
670 break;
671 }
672 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
673 // Build int64_t __kmpc_shuffle_int64(int64_t element,
674 // int16_t lane_offset, int16_t warp_size);
675 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
676 llvm::FunctionType *FnTy =
677 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
678 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
679 break;
680 }
681 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
682 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
683 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
684 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
685 // lane_offset, int16_t Algorithm Version),
686 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
687 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
688 CGM.Int16Ty, CGM.Int16Ty};
689 auto *ShuffleReduceFnTy =
690 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
691 /*isVarArg=*/false);
692 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
693 auto *InterWarpCopyFnTy =
694 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
695 /*isVarArg=*/false);
696 llvm::Type *TypeParams[] = {CGM.Int32Ty,
697 CGM.Int32Ty,
698 CGM.SizeTy,
699 CGM.VoidPtrTy,
700 ShuffleReduceFnTy->getPointerTo(),
701 InterWarpCopyFnTy->getPointerTo()};
702 llvm::FunctionType *FnTy =
703 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
704 RTLFn = CGM.CreateRuntimeFunction(
705 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
706 break;
707 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000708 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
709 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
710 // int32_t num_vars, size_t reduce_size, void *reduce_data,
711 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
712 // lane_offset, int16_t shortCircuit),
713 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
714 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
715 // int32_t index, int32_t width),
716 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
717 // int32_t index, int32_t width, int32_t reduce))
718 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
719 CGM.Int16Ty, CGM.Int16Ty};
720 auto *ShuffleReduceFnTy =
721 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
722 /*isVarArg=*/false);
723 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
724 auto *InterWarpCopyFnTy =
725 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
726 /*isVarArg=*/false);
727 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
728 CGM.Int32Ty, CGM.Int32Ty};
729 auto *CopyToScratchpadFnTy =
730 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
731 /*isVarArg=*/false);
732 llvm::Type *LoadReduceTypeParams[] = {
733 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
734 auto *LoadReduceFnTy =
735 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
736 /*isVarArg=*/false);
737 llvm::Type *TypeParams[] = {CGM.Int32Ty,
738 CGM.Int32Ty,
739 CGM.SizeTy,
740 CGM.VoidPtrTy,
741 ShuffleReduceFnTy->getPointerTo(),
742 InterWarpCopyFnTy->getPointerTo(),
743 CopyToScratchpadFnTy->getPointerTo(),
744 LoadReduceFnTy->getPointerTo()};
745 llvm::FunctionType *FnTy =
746 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
747 RTLFn = CGM.CreateRuntimeFunction(
748 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
749 break;
750 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000751 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
752 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
753 llvm::Type *TypeParams[] = {CGM.Int32Ty};
754 llvm::FunctionType *FnTy =
755 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
756 RTLFn = CGM.CreateRuntimeFunction(
757 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
758 break;
759 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000760 }
761 return RTLFn;
762}
763
764void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
765 llvm::Constant *Addr,
Samuel Antaof83efdb2017-01-05 16:02:49 +0000766 uint64_t Size, int32_t) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000767 auto *F = dyn_cast<llvm::Function>(Addr);
768 // TODO: Add support for global variables on the device after declare target
769 // support.
770 if (!F)
771 return;
772 llvm::Module *M = F->getParent();
773 llvm::LLVMContext &Ctx = M->getContext();
774
775 // Get "nvvm.annotations" metadata node
776 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
777
778 llvm::Metadata *MDVals[] = {
779 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"),
780 llvm::ConstantAsMetadata::get(
781 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
782 // Append metadata to nvvm.annotations
783 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
784}
785
786void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
787 const OMPExecutableDirective &D, StringRef ParentName,
788 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000789 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000790 if (!IsOffloadEntry) // Nothing to do.
791 return;
792
793 assert(!ParentName.empty() && "Invalid target region parent name!");
794
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000795 CGOpenMPRuntimeNVPTX::ExecutionMode Mode =
796 getExecutionModeForDirective(CGM, D);
797 switch (Mode) {
798 case CGOpenMPRuntimeNVPTX::ExecutionMode::Generic:
799 emitGenericKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
800 CodeGen);
801 break;
802 case CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd:
803 emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
804 CodeGen);
805 break;
806 case CGOpenMPRuntimeNVPTX::ExecutionMode::Unknown:
807 llvm_unreachable(
808 "Unknown programming model for OpenMP directive on NVPTX target.");
809 }
810
811 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000812}
813
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000814CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000815 : CGOpenMPRuntime(CGM), CurrentExecutionMode(ExecutionMode::Unknown) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000816 if (!CGM.getLangOpts().OpenMPIsDevice)
817 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000818}
Carlo Bertollic6872252016-04-04 15:55:02 +0000819
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +0000820void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
821 OpenMPProcBindClauseKind ProcBind,
822 SourceLocation Loc) {
823 // Do nothing in case of Spmd mode and L0 parallel.
824 // TODO: If in Spmd mode and L1 parallel emit the clause.
825 if (isInSpmdExecutionMode())
826 return;
827
828 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
829}
830
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +0000831void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
832 llvm::Value *NumThreads,
833 SourceLocation Loc) {
834 // Do nothing in case of Spmd mode and L0 parallel.
835 // TODO: If in Spmd mode and L1 parallel emit the clause.
836 if (isInSpmdExecutionMode())
837 return;
838
839 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
840}
841
Carlo Bertollic6872252016-04-04 15:55:02 +0000842void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
843 const Expr *NumTeams,
844 const Expr *ThreadLimit,
845 SourceLocation Loc) {}
846
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000847llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
848 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
849 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
850 return CGOpenMPRuntime::emitParallelOutlinedFunction(D, ThreadIDVar,
851 InnermostKind, CodeGen);
852}
853
854llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +0000855 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
856 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
857
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000858 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
859 D, ThreadIDVar, InnermostKind, CodeGen);
860 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
861 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000862 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000863 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +0000864
865 return OutlinedFun;
866}
867
868void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
869 const OMPExecutableDirective &D,
870 SourceLocation Loc,
871 llvm::Value *OutlinedFn,
872 ArrayRef<llvm::Value *> CapturedVars) {
873 if (!CGF.HaveInsertPoint())
874 return;
875
876 Address ZeroAddr =
877 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
878 /*Name*/ ".zero.addr");
879 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
880 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
881 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
882 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
883 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000884 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +0000885}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000886
887void CGOpenMPRuntimeNVPTX::emitParallelCall(
888 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
889 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
890 if (!CGF.HaveInsertPoint())
891 return;
892
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000893 if (isInSpmdExecutionMode())
894 emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
895 else
896 emitGenericParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000897}
898
899void CGOpenMPRuntimeNVPTX::emitGenericParallelCall(
900 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
901 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
902 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
903
Malcolm Parsonsc6e45832017-01-13 18:55:32 +0000904 auto &&L0ParallelGen = [this, Fn](CodeGenFunction &CGF, PrePostActionTy &) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000905 CGBuilderTy &Bld = CGF.Builder;
906
907 // Prepare for parallel region. Indicate the outlined function.
908 llvm::Value *Args[] = {Bld.CreateBitOrPointerCast(Fn, CGM.Int8PtrTy)};
909 CGF.EmitRuntimeCall(
910 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
911 Args);
912
913 // Activate workers. This barrier is used by the master to signal
914 // work for the workers.
915 syncCTAThreads(CGF);
916
917 // OpenMP [2.5, Parallel Construct, p.49]
918 // There is an implied barrier at the end of a parallel region. After the
919 // end of a parallel region, only the master thread of the team resumes
920 // execution of the enclosing task region.
921 //
922 // The master waits at this barrier until all workers are done.
923 syncCTAThreads(CGF);
924
925 // Remember for post-processing in worker loop.
926 Work.push_back(Fn);
927 };
928
929 auto *RTLoc = emitUpdateLocation(CGF, Loc);
930 auto *ThreadID = getThreadID(CGF, Loc);
931 llvm::Value *Args[] = {RTLoc, ThreadID};
932
Alexey Bataev3c595a62017-08-14 15:01:03 +0000933 auto &&SeqGen = [this, Fn, &CapturedVars, &Args, Loc](CodeGenFunction &CGF,
934 PrePostActionTy &) {
935 auto &&CodeGen = [this, Fn, &CapturedVars, Loc](CodeGenFunction &CGF,
936 PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000937 Action.Enter(CGF);
938
939 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
940 OutlinedFnArgs.push_back(
941 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
942 OutlinedFnArgs.push_back(
943 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
944 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000945 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000946 };
947
948 RegionCodeGenTy RCG(CodeGen);
949 NVPTXActionTy Action(
950 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
951 Args,
952 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
953 Args);
954 RCG.setAction(Action);
955 RCG(CGF);
956 };
957
958 if (IfCond)
959 emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen);
960 else {
961 CodeGenFunction::RunCleanupsScope Scope(CGF);
962 RegionCodeGenTy ThenRCG(L0ParallelGen);
963 ThenRCG(CGF);
964 }
965}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000966
967void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
968 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
969 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
970 // Just call the outlined function to execute the parallel region.
971 // OutlinedFn(&GTid, &zero, CapturedStruct);
972 //
973 // TODO: Do something with IfCond when support for the 'if' clause
974 // is added on Spmd target directives.
975 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
976 OutlinedFnArgs.push_back(
977 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
978 OutlinedFnArgs.push_back(
979 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
980 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000981 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000982}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000983
984/// This function creates calls to one of two shuffle functions to copy
985/// variables between lanes in a warp.
986static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
987 QualType ElemTy,
988 llvm::Value *Elem,
989 llvm::Value *Offset) {
990 auto &CGM = CGF.CGM;
991 auto &C = CGM.getContext();
992 auto &Bld = CGF.Builder;
993 CGOpenMPRuntimeNVPTX &RT =
994 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
995
996 unsigned Size = CGM.getContext().getTypeSizeInChars(ElemTy).getQuantity();
997 assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction.");
998
999 OpenMPRTLFunctionNVPTX ShuffleFn = Size <= 4
1000 ? OMPRTL_NVPTX__kmpc_shuffle_int32
1001 : OMPRTL_NVPTX__kmpc_shuffle_int64;
1002
1003 // Cast all types to 32- or 64-bit values before calling shuffle routines.
1004 auto CastTy = Size <= 4 ? CGM.Int32Ty : CGM.Int64Ty;
1005 auto *ElemCast = Bld.CreateSExtOrBitCast(Elem, CastTy);
1006 auto *WarpSize = CGF.EmitScalarConversion(
1007 getNVPTXWarpSize(CGF), C.getIntTypeForBitwidth(32, /* Signed */ true),
1008 C.getIntTypeForBitwidth(16, /* Signed */ true), SourceLocation());
1009
1010 auto *ShuffledVal =
1011 CGF.EmitRuntimeCall(RT.createNVPTXRuntimeFunction(ShuffleFn),
1012 {ElemCast, Offset, WarpSize});
1013
1014 return Bld.CreateTruncOrBitCast(ShuffledVal, CGF.ConvertTypeForMem(ElemTy));
1015}
1016
1017namespace {
1018enum CopyAction : unsigned {
1019 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1020 // the warp using shuffle instructions.
1021 RemoteLaneToThread,
1022 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1023 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001024 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1025 ThreadToScratchpad,
1026 // ScratchpadToThread: Copy from a scratchpad array in global memory
1027 // containing team-reduced data to a thread's stack.
1028 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001029};
1030} // namespace
1031
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001032struct CopyOptionsTy {
1033 llvm::Value *RemoteLaneOffset;
1034 llvm::Value *ScratchpadIndex;
1035 llvm::Value *ScratchpadWidth;
1036};
1037
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001038/// Emit instructions to copy a Reduce list, which contains partially
1039/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001040static void emitReductionListCopy(
1041 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1042 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1043 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001044
1045 auto &CGM = CGF.CGM;
1046 auto &C = CGM.getContext();
1047 auto &Bld = CGF.Builder;
1048
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001049 auto *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1050 auto *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1051 auto *ScratchpadWidth = CopyOptions.ScratchpadWidth;
1052
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001053 // Iterates, element-by-element, through the source Reduce list and
1054 // make a copy.
1055 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001056 unsigned Size = Privates.size();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001057 for (auto &Private : Privates) {
1058 Address SrcElementAddr = Address::invalid();
1059 Address DestElementAddr = Address::invalid();
1060 Address DestElementPtrAddr = Address::invalid();
1061 // Should we shuffle in an element from a remote lane?
1062 bool ShuffleInElement = false;
1063 // Set to true to update the pointer in the dest Reduce list to a
1064 // newly created element.
1065 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001066 // Increment the src or dest pointer to the scratchpad, for each
1067 // new element.
1068 bool IncrScratchpadSrc = false;
1069 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001070
1071 switch (Action) {
1072 case RemoteLaneToThread: {
1073 // Step 1.1: Get the address for the src element in the Reduce list.
1074 Address SrcElementPtrAddr =
1075 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
1076 llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar(
1077 SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1078 SrcElementAddr =
1079 Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType()));
1080
1081 // Step 1.2: Create a temporary to store the element in the destination
1082 // Reduce list.
1083 DestElementPtrAddr =
1084 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1085 DestElementAddr =
1086 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1087 ShuffleInElement = true;
1088 UpdateDestListPtr = true;
1089 break;
1090 }
1091 case ThreadCopy: {
1092 // Step 1.1: Get the address for the src element in the Reduce list.
1093 Address SrcElementPtrAddr =
1094 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
1095 llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar(
1096 SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1097 SrcElementAddr =
1098 Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType()));
1099
1100 // Step 1.2: Get the address for dest element. The destination
1101 // element has already been created on the thread's stack.
1102 DestElementPtrAddr =
1103 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1104 llvm::Value *DestElementPtr =
1105 CGF.EmitLoadOfScalar(DestElementPtrAddr, /*Volatile=*/false,
1106 C.VoidPtrTy, SourceLocation());
1107 Address DestElemAddr =
1108 Address(DestElementPtr, C.getTypeAlignInChars(Private->getType()));
1109 DestElementAddr = Bld.CreateElementBitCast(
1110 DestElemAddr, CGF.ConvertTypeForMem(Private->getType()));
1111 break;
1112 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001113 case ThreadToScratchpad: {
1114 // Step 1.1: Get the address for the src element in the Reduce list.
1115 Address SrcElementPtrAddr =
1116 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
1117 llvm::Value *SrcElementPtrPtr = CGF.EmitLoadOfScalar(
1118 SrcElementPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1119 SrcElementAddr =
1120 Address(SrcElementPtrPtr, C.getTypeAlignInChars(Private->getType()));
1121
1122 // Step 1.2: Get the address for dest element:
1123 // address = base + index * ElementSizeInChars.
1124 unsigned ElementSizeInChars =
1125 C.getTypeSizeInChars(Private->getType()).getQuantity();
1126 auto *CurrentOffset =
1127 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1128 ScratchpadIndex);
1129 auto *ScratchPadElemAbsolutePtrVal =
1130 Bld.CreateAdd(DestBase.getPointer(), CurrentOffset);
1131 ScratchPadElemAbsolutePtrVal =
1132 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1133 Address ScratchpadPtr =
1134 Address(ScratchPadElemAbsolutePtrVal,
1135 C.getTypeAlignInChars(Private->getType()));
1136 DestElementAddr = Bld.CreateElementBitCast(
1137 ScratchpadPtr, CGF.ConvertTypeForMem(Private->getType()));
1138 IncrScratchpadDest = true;
1139 break;
1140 }
1141 case ScratchpadToThread: {
1142 // Step 1.1: Get the address for the src element in the scratchpad.
1143 // address = base + index * ElementSizeInChars.
1144 unsigned ElementSizeInChars =
1145 C.getTypeSizeInChars(Private->getType()).getQuantity();
1146 auto *CurrentOffset =
1147 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1148 ScratchpadIndex);
1149 auto *ScratchPadElemAbsolutePtrVal =
1150 Bld.CreateAdd(SrcBase.getPointer(), CurrentOffset);
1151 ScratchPadElemAbsolutePtrVal =
1152 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1153 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1154 C.getTypeAlignInChars(Private->getType()));
1155 IncrScratchpadSrc = true;
1156
1157 // Step 1.2: Create a temporary to store the element in the destination
1158 // Reduce list.
1159 DestElementPtrAddr =
1160 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1161 DestElementAddr =
1162 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1163 UpdateDestListPtr = true;
1164 break;
1165 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001166 }
1167
1168 // Regardless of src and dest of copy, we emit the load of src
1169 // element as this is required in all directions
1170 SrcElementAddr = Bld.CreateElementBitCast(
1171 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
1172 llvm::Value *Elem =
1173 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
1174 Private->getType(), SourceLocation());
1175
1176 // Now that all active lanes have read the element in the
1177 // Reduce list, shuffle over the value from the remote lane.
1178 if (ShuffleInElement) {
1179 Elem = createRuntimeShuffleFunction(CGF, Private->getType(), Elem,
1180 RemoteLaneOffset);
1181 }
1182
1183 // Store the source element value to the dest element address.
1184 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
1185 Private->getType());
1186
1187 // Step 3.1: Modify reference in dest Reduce list as needed.
1188 // Modifying the reference in Reduce list to point to the newly
1189 // created element. The element is live in the current function
1190 // scope and that of functions it invokes (i.e., reduce_function).
1191 // RemoteReduceData[i] = (void*)&RemoteElem
1192 if (UpdateDestListPtr) {
1193 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
1194 DestElementAddr.getPointer(), CGF.VoidPtrTy),
1195 DestElementPtrAddr, /*Volatile=*/false,
1196 C.VoidPtrTy);
1197 }
1198
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001199 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
1200 // address of the next element in scratchpad memory, unless we're currently
1201 // processing the last one. Memory alignment is also taken care of here.
1202 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
1203 llvm::Value *ScratchpadBasePtr =
1204 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
1205 unsigned ElementSizeInChars =
1206 C.getTypeSizeInChars(Private->getType()).getQuantity();
1207 ScratchpadBasePtr = Bld.CreateAdd(
1208 ScratchpadBasePtr,
1209 Bld.CreateMul(ScratchpadWidth, llvm::ConstantInt::get(
1210 CGM.SizeTy, ElementSizeInChars)));
1211
1212 // Take care of global memory alignment for performance
1213 ScratchpadBasePtr = Bld.CreateSub(ScratchpadBasePtr,
1214 llvm::ConstantInt::get(CGM.SizeTy, 1));
1215 ScratchpadBasePtr = Bld.CreateSDiv(
1216 ScratchpadBasePtr,
1217 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1218 ScratchpadBasePtr = Bld.CreateAdd(ScratchpadBasePtr,
1219 llvm::ConstantInt::get(CGM.SizeTy, 1));
1220 ScratchpadBasePtr = Bld.CreateMul(
1221 ScratchpadBasePtr,
1222 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1223
1224 if (IncrScratchpadDest)
1225 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1226 else /* IncrScratchpadSrc = true */
1227 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1228 }
1229
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001230 Idx++;
1231 }
1232}
1233
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001234/// This function emits a helper that loads data from the scratchpad array
1235/// and (optionally) reduces it with the input operand.
1236///
1237/// load_and_reduce(local, scratchpad, index, width, should_reduce)
1238/// reduce_data remote;
1239/// for elem in remote:
1240/// remote.elem = Scratchpad[elem_id][index]
1241/// if (should_reduce)
1242/// local = local @ remote
1243/// else
1244/// local = remote
Benjamin Kramer674d5792017-05-26 20:08:24 +00001245static llvm::Value *
1246emitReduceScratchpadFunction(CodeGenModule &CGM,
1247 ArrayRef<const Expr *> Privates,
1248 QualType ReductionArrayTy, llvm::Value *ReduceFn) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001249 auto &C = CGM.getContext();
1250 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1251
1252 // Destination of the copy.
Alexey Bataev56223232017-06-09 13:40:18 +00001253 ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001254 // Base address of the scratchpad array, with each element storing a
1255 // Reduce list per team.
Alexey Bataev56223232017-06-09 13:40:18 +00001256 ImplicitParamDecl ScratchPadArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001257 // A source index into the scratchpad array.
Alexey Bataev56223232017-06-09 13:40:18 +00001258 ImplicitParamDecl IndexArg(C, Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001259 // Row width of an element in the scratchpad array, typically
1260 // the number of teams.
Alexey Bataev56223232017-06-09 13:40:18 +00001261 ImplicitParamDecl WidthArg(C, Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001262 // If should_reduce == 1, then it's load AND reduce,
1263 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
1264 // The latter case is used for initialization.
Alexey Bataev56223232017-06-09 13:40:18 +00001265 ImplicitParamDecl ShouldReduceArg(C, Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001266
1267 FunctionArgList Args;
1268 Args.push_back(&ReduceListArg);
1269 Args.push_back(&ScratchPadArg);
1270 Args.push_back(&IndexArg);
1271 Args.push_back(&WidthArg);
1272 Args.push_back(&ShouldReduceArg);
1273
1274 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1275 auto *Fn = llvm::Function::Create(
1276 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1277 "_omp_reduction_load_and_reduce", &CGM.getModule());
1278 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1279 CodeGenFunction CGF(CGM);
1280 // We don't need debug information in this function as nothing here refers to
1281 // user code.
1282 CGF.disableDebugInfo();
1283 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1284
1285 auto &Bld = CGF.Builder;
1286
1287 // Get local Reduce list pointer.
1288 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1289 Address ReduceListAddr(
1290 Bld.CreatePointerBitCastOrAddrSpaceCast(
1291 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1292 C.VoidPtrTy, SourceLocation()),
1293 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1294 CGF.getPointerAlign());
1295
1296 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1297 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
1298 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1299
1300 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
1301 llvm::Value *IndexVal =
1302 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false,
1303 Int32Ty, SourceLocation()),
1304 CGM.SizeTy, /*isSigned=*/true);
1305
1306 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
1307 llvm::Value *WidthVal =
1308 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
1309 Int32Ty, SourceLocation()),
1310 CGM.SizeTy, /*isSigned=*/true);
1311
1312 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
1313 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
1314 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, SourceLocation());
1315
1316 // The absolute ptr address to the base addr of the next element to copy.
1317 llvm::Value *CumulativeElemBasePtr =
1318 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1319 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1320
1321 // Create a Remote Reduce list to store the elements read from the
1322 // scratchpad array.
1323 Address RemoteReduceList =
1324 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
1325
1326 // Assemble remote Reduce list from scratchpad array.
1327 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
1328 SrcDataAddr, RemoteReduceList,
1329 {/*RemoteLaneOffset=*/nullptr,
1330 /*ScratchpadIndex=*/IndexVal,
1331 /*ScratchpadWidth=*/WidthVal});
1332
1333 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1334 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1335 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1336
1337 auto CondReduce = Bld.CreateICmpEQ(ShouldReduceVal, Bld.getInt32(1));
1338 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1339
1340 CGF.EmitBlock(ThenBB);
1341 // We should reduce with the local Reduce list.
1342 // reduce_function(LocalReduceList, RemoteReduceList)
1343 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1344 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
1345 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1346 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
1347 CGF.EmitCallOrInvoke(ReduceFn, {LocalDataPtr, RemoteDataPtr});
1348 Bld.CreateBr(MergeBB);
1349
1350 CGF.EmitBlock(ElseBB);
1351 // No reduction; just copy:
1352 // Local Reduce list = Remote Reduce list.
1353 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1354 RemoteReduceList, ReduceListAddr);
1355 Bld.CreateBr(MergeBB);
1356
1357 CGF.EmitBlock(MergeBB);
1358
1359 CGF.FinishFunction();
1360 return Fn;
1361}
1362
1363/// This function emits a helper that stores reduced data from the team
1364/// master to a scratchpad array in global memory.
1365///
1366/// for elem in Reduce List:
1367/// scratchpad[elem_id][index] = elem
1368///
Benjamin Kramer674d5792017-05-26 20:08:24 +00001369static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
1370 ArrayRef<const Expr *> Privates,
1371 QualType ReductionArrayTy) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001372
1373 auto &C = CGM.getContext();
1374 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1375
1376 // Source of the copy.
Alexey Bataev56223232017-06-09 13:40:18 +00001377 ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001378 // Base address of the scratchpad array, with each element storing a
1379 // Reduce list per team.
Alexey Bataev56223232017-06-09 13:40:18 +00001380 ImplicitParamDecl ScratchPadArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001381 // A destination index into the scratchpad array, typically the team
1382 // identifier.
Alexey Bataev56223232017-06-09 13:40:18 +00001383 ImplicitParamDecl IndexArg(C, Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001384 // Row width of an element in the scratchpad array, typically
1385 // the number of teams.
Alexey Bataev56223232017-06-09 13:40:18 +00001386 ImplicitParamDecl WidthArg(C, Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001387
1388 FunctionArgList Args;
1389 Args.push_back(&ReduceListArg);
1390 Args.push_back(&ScratchPadArg);
1391 Args.push_back(&IndexArg);
1392 Args.push_back(&WidthArg);
1393
1394 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1395 auto *Fn = llvm::Function::Create(
1396 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1397 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
1398 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1399 CodeGenFunction CGF(CGM);
1400 // We don't need debug information in this function as nothing here refers to
1401 // user code.
1402 CGF.disableDebugInfo();
1403 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1404
1405 auto &Bld = CGF.Builder;
1406
1407 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1408 Address SrcDataAddr(
1409 Bld.CreatePointerBitCastOrAddrSpaceCast(
1410 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1411 C.VoidPtrTy, SourceLocation()),
1412 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1413 CGF.getPointerAlign());
1414
1415 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1416 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
1417 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1418
1419 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
1420 llvm::Value *IndexVal =
1421 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false,
1422 Int32Ty, SourceLocation()),
1423 CGF.SizeTy, /*isSigned=*/true);
1424
1425 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
1426 llvm::Value *WidthVal =
1427 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
1428 Int32Ty, SourceLocation()),
1429 CGF.SizeTy, /*isSigned=*/true);
1430
1431 // The absolute ptr address to the base addr of the next element to copy.
1432 llvm::Value *CumulativeElemBasePtr =
1433 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1434 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1435
1436 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
1437 SrcDataAddr, DestDataAddr,
1438 {/*RemoteLaneOffset=*/nullptr,
1439 /*ScratchpadIndex=*/IndexVal,
1440 /*ScratchpadWidth=*/WidthVal});
1441
1442 CGF.FinishFunction();
1443 return Fn;
1444}
1445
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001446/// This function emits a helper that gathers Reduce lists from the first
1447/// lane of every active warp to lanes in the first warp.
1448///
1449/// void inter_warp_copy_func(void* reduce_data, num_warps)
1450/// shared smem[warp_size];
1451/// For all data entries D in reduce_data:
1452/// If (I am the first lane in each warp)
1453/// Copy my local D to smem[warp_id]
1454/// sync
1455/// if (I am the first warp)
1456/// Copy smem[thread_id] to my local D
1457/// sync
1458static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
1459 ArrayRef<const Expr *> Privates,
1460 QualType ReductionArrayTy) {
1461 auto &C = CGM.getContext();
1462 auto &M = CGM.getModule();
1463
1464 // ReduceList: thread local Reduce list.
1465 // At the stage of the computation when this function is called, partially
1466 // aggregated values reside in the first lane of every active warp.
Alexey Bataev56223232017-06-09 13:40:18 +00001467 ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001468 // NumWarps: number of warps active in the parallel region. This could
1469 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev56223232017-06-09 13:40:18 +00001470 ImplicitParamDecl NumWarpsArg(C,
1471 C.getIntTypeForBitwidth(32, /* Signed */ true),
1472 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001473 FunctionArgList Args;
1474 Args.push_back(&ReduceListArg);
1475 Args.push_back(&NumWarpsArg);
1476
1477 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1478 auto *Fn = llvm::Function::Create(
1479 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1480 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
1481 CGM.SetInternalFunctionAttributes(/*DC=*/nullptr, Fn, CGFI);
1482 CodeGenFunction CGF(CGM);
1483 // We don't need debug information in this function as nothing here refers to
1484 // user code.
1485 CGF.disableDebugInfo();
1486 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1487
1488 auto &Bld = CGF.Builder;
1489
1490 // This array is used as a medium to transfer, one reduce element at a time,
1491 // the data from the first lane of every warp to lanes in the first warp
1492 // in order to perform the final step of a reduction in a parallel region
1493 // (reduction across warps). The array is placed in NVPTX __shared__ memory
1494 // for reduced latency, as well as to have a distinct copy for concurrently
1495 // executing target regions. The array is declared with common linkage so
1496 // as to be shared across compilation units.
1497 const char *TransferMediumName =
1498 "__openmp_nvptx_data_transfer_temporary_storage";
1499 llvm::GlobalVariable *TransferMedium =
1500 M.getGlobalVariable(TransferMediumName);
1501 if (!TransferMedium) {
1502 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
1503 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
1504 TransferMedium = new llvm::GlobalVariable(
1505 M, Ty,
1506 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
1507 llvm::Constant::getNullValue(Ty), TransferMediumName,
1508 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
1509 SharedAddressSpace);
1510 }
1511
1512 // Get the CUDA thread id of the current OpenMP thread on the GPU.
1513 auto *ThreadID = getNVPTXThreadID(CGF);
1514 // nvptx_lane_id = nvptx_id % warpsize
1515 auto *LaneID = getNVPTXLaneID(CGF);
1516 // nvptx_warp_id = nvptx_id / warpsize
1517 auto *WarpID = getNVPTXWarpID(CGF);
1518
1519 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1520 Address LocalReduceList(
1521 Bld.CreatePointerBitCastOrAddrSpaceCast(
1522 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1523 C.VoidPtrTy, SourceLocation()),
1524 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1525 CGF.getPointerAlign());
1526
1527 unsigned Idx = 0;
1528 for (auto &Private : Privates) {
1529 //
1530 // Warp master copies reduce element to transfer medium in __shared__
1531 // memory.
1532 //
1533 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1534 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1535 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1536
1537 // if (lane_id == 0)
1538 auto IsWarpMaster =
1539 Bld.CreateICmpEQ(LaneID, Bld.getInt32(0), "warp_master");
1540 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
1541 CGF.EmitBlock(ThenBB);
1542
1543 // Reduce element = LocalReduceList[i]
1544 Address ElemPtrPtrAddr =
1545 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1546 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
1547 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1548 // elemptr = (type[i]*)(elemptrptr)
1549 Address ElemPtr =
1550 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
1551 ElemPtr = Bld.CreateElementBitCast(
1552 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1553 // elem = *elemptr
1554 llvm::Value *Elem = CGF.EmitLoadOfScalar(
1555 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1556
1557 // Get pointer to location in transfer medium.
1558 // MediumPtr = &medium[warp_id]
1559 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
1560 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
1561 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
1562 // Casting to actual data type.
1563 // MediumPtr = (type[i]*)MediumPtrAddr;
1564 MediumPtr = Bld.CreateElementBitCast(
1565 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1566
1567 //*MediumPtr = elem
1568 Bld.CreateStore(Elem, MediumPtr);
1569
1570 Bld.CreateBr(MergeBB);
1571
1572 CGF.EmitBlock(ElseBB);
1573 Bld.CreateBr(MergeBB);
1574
1575 CGF.EmitBlock(MergeBB);
1576
1577 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
1578 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
1579 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
1580
1581 auto *NumActiveThreads = Bld.CreateNSWMul(
1582 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
1583 // named_barrier_sync(ParallelBarrierID, num_active_threads)
1584 syncParallelThreads(CGF, NumActiveThreads);
1585
1586 //
1587 // Warp 0 copies reduce element from transfer medium.
1588 //
1589 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
1590 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
1591 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
1592
1593 // Up to 32 threads in warp 0 are active.
1594 auto IsActiveThread =
1595 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
1596 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
1597
1598 CGF.EmitBlock(W0ThenBB);
1599
1600 // SrcMediumPtr = &medium[tid]
1601 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
1602 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
1603 Address SrcMediumPtr(SrcMediumPtrVal,
1604 C.getTypeAlignInChars(Private->getType()));
1605 // SrcMediumVal = *SrcMediumPtr;
1606 SrcMediumPtr = Bld.CreateElementBitCast(
1607 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1608 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
1609 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1610
1611 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
1612 Address TargetElemPtrPtr =
1613 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1614 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
1615 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1616 Address TargetElemPtr =
1617 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
1618 TargetElemPtr = Bld.CreateElementBitCast(
1619 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1620
1621 // *TargetElemPtr = SrcMediumVal;
1622 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
1623 Private->getType());
1624 Bld.CreateBr(W0MergeBB);
1625
1626 CGF.EmitBlock(W0ElseBB);
1627 Bld.CreateBr(W0MergeBB);
1628
1629 CGF.EmitBlock(W0MergeBB);
1630
1631 // While warp 0 copies values from transfer medium, all other warps must
1632 // wait.
1633 syncParallelThreads(CGF, NumActiveThreads);
1634 Idx++;
1635 }
1636
1637 CGF.FinishFunction();
1638 return Fn;
1639}
1640
1641/// Emit a helper that reduces data across two OpenMP threads (lanes)
1642/// in the same warp. It uses shuffle instructions to copy over data from
1643/// a remote lane's stack. The reduction algorithm performed is specified
1644/// by the fourth parameter.
1645///
1646/// Algorithm Versions.
1647/// Full Warp Reduce (argument value 0):
1648/// This algorithm assumes that all 32 lanes are active and gathers
1649/// data from these 32 lanes, producing a single resultant value.
1650/// Contiguous Partial Warp Reduce (argument value 1):
1651/// This algorithm assumes that only a *contiguous* subset of lanes
1652/// are active. This happens for the last warp in a parallel region
1653/// when the user specified num_threads is not an integer multiple of
1654/// 32. This contiguous subset always starts with the zeroth lane.
1655/// Partial Warp Reduce (argument value 2):
1656/// This algorithm gathers data from any number of lanes at any position.
1657/// All reduced values are stored in the lowest possible lane. The set
1658/// of problems every algorithm addresses is a super set of those
1659/// addressable by algorithms with a lower version number. Overhead
1660/// increases as algorithm version increases.
1661///
1662/// Terminology
1663/// Reduce element:
1664/// Reduce element refers to the individual data field with primitive
1665/// data types to be combined and reduced across threads.
1666/// Reduce list:
1667/// Reduce list refers to a collection of local, thread-private
1668/// reduce elements.
1669/// Remote Reduce list:
1670/// Remote Reduce list refers to a collection of remote (relative to
1671/// the current thread) reduce elements.
1672///
1673/// We distinguish between three states of threads that are important to
1674/// the implementation of this function.
1675/// Alive threads:
1676/// Threads in a warp executing the SIMT instruction, as distinguished from
1677/// threads that are inactive due to divergent control flow.
1678/// Active threads:
1679/// The minimal set of threads that has to be alive upon entry to this
1680/// function. The computation is correct iff active threads are alive.
1681/// Some threads are alive but they are not active because they do not
1682/// contribute to the computation in any useful manner. Turning them off
1683/// may introduce control flow overheads without any tangible benefits.
1684/// Effective threads:
1685/// In order to comply with the argument requirements of the shuffle
1686/// function, we must keep all lanes holding data alive. But at most
1687/// half of them perform value aggregation; we refer to this half of
1688/// threads as effective. The other half is simply handing off their
1689/// data.
1690///
1691/// Procedure
1692/// Value shuffle:
1693/// In this step active threads transfer data from higher lane positions
1694/// in the warp to lower lane positions, creating Remote Reduce list.
1695/// Value aggregation:
1696/// In this step, effective threads combine their thread local Reduce list
1697/// with Remote Reduce list and store the result in the thread local
1698/// Reduce list.
1699/// Value copy:
1700/// In this step, we deal with the assumption made by algorithm 2
1701/// (i.e. contiguity assumption). When we have an odd number of lanes
1702/// active, say 2k+1, only k threads will be effective and therefore k
1703/// new values will be produced. However, the Reduce list owned by the
1704/// (2k+1)th thread is ignored in the value aggregation. Therefore
1705/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
1706/// that the contiguity assumption still holds.
1707static llvm::Value *
1708emitShuffleAndReduceFunction(CodeGenModule &CGM,
1709 ArrayRef<const Expr *> Privates,
1710 QualType ReductionArrayTy, llvm::Value *ReduceFn) {
1711 auto &C = CGM.getContext();
1712
1713 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev56223232017-06-09 13:40:18 +00001714 ImplicitParamDecl ReduceListArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001715 // Current lane id; could be logical.
Alexey Bataev56223232017-06-09 13:40:18 +00001716 ImplicitParamDecl LaneIDArg(C, C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001717 // Offset of the remote source lane relative to the current lane.
Alexey Bataev56223232017-06-09 13:40:18 +00001718 ImplicitParamDecl RemoteLaneOffsetArg(C, C.ShortTy,
1719 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001720 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev56223232017-06-09 13:40:18 +00001721 ImplicitParamDecl AlgoVerArg(C, C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001722 FunctionArgList Args;
1723 Args.push_back(&ReduceListArg);
1724 Args.push_back(&LaneIDArg);
1725 Args.push_back(&RemoteLaneOffsetArg);
1726 Args.push_back(&AlgoVerArg);
1727
1728 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1729 auto *Fn = llvm::Function::Create(
1730 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1731 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
1732 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
1733 CodeGenFunction CGF(CGM);
1734 // We don't need debug information in this function as nothing here refers to
1735 // user code.
1736 CGF.disableDebugInfo();
1737 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1738
1739 auto &Bld = CGF.Builder;
1740
1741 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1742 Address LocalReduceList(
1743 Bld.CreatePointerBitCastOrAddrSpaceCast(
1744 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1745 C.VoidPtrTy, SourceLocation()),
1746 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1747 CGF.getPointerAlign());
1748
1749 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
1750 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
1751 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1752
1753 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
1754 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
1755 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1756
1757 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
1758 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
1759 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1760
1761 // Create a local thread-private variable to host the Reduce list
1762 // from a remote lane.
1763 Address RemoteReduceList =
1764 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
1765
1766 // This loop iterates through the list of reduce elements and copies,
1767 // element by element, from a remote lane in the warp to RemoteReduceList,
1768 // hosted on the thread's stack.
1769 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
1770 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001771 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
1772 /*ScratchpadIndex=*/nullptr,
1773 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001774
1775 // The actions to be performed on the Remote Reduce list is dependent
1776 // on the algorithm version.
1777 //
1778 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
1779 // LaneId % 2 == 0 && Offset > 0):
1780 // do the reduction value aggregation
1781 //
1782 // The thread local variable Reduce list is mutated in place to host the
1783 // reduced data, which is the aggregated value produced from local and
1784 // remote lanes.
1785 //
1786 // Note that AlgoVer is expected to be a constant integer known at compile
1787 // time.
1788 // When AlgoVer==0, the first conjunction evaluates to true, making
1789 // the entire predicate true during compile time.
1790 // When AlgoVer==1, the second conjunction has only the second part to be
1791 // evaluated during runtime. Other conjunctions evaluates to false
1792 // during compile time.
1793 // When AlgoVer==2, the third conjunction has only the second part to be
1794 // evaluated during runtime. Other conjunctions evaluates to false
1795 // during compile time.
1796 auto CondAlgo0 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(0));
1797
1798 auto Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1799 auto CondAlgo1 = Bld.CreateAnd(
1800 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
1801
1802 auto Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
1803 auto CondAlgo2 = Bld.CreateAnd(
1804 Algo2,
1805 Bld.CreateICmpEQ(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1)),
1806 Bld.getInt16(0)));
1807 CondAlgo2 = Bld.CreateAnd(
1808 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
1809
1810 auto CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
1811 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
1812
1813 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1814 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1815 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1816 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1817
1818 CGF.EmitBlock(ThenBB);
1819 // reduce_function(LocalReduceList, RemoteReduceList)
1820 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1821 LocalReduceList.getPointer(), CGF.VoidPtrTy);
1822 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1823 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
1824 CGF.EmitCallOrInvoke(ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
1825 Bld.CreateBr(MergeBB);
1826
1827 CGF.EmitBlock(ElseBB);
1828 Bld.CreateBr(MergeBB);
1829
1830 CGF.EmitBlock(MergeBB);
1831
1832 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
1833 // Reduce list.
1834 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1835 auto CondCopy = Bld.CreateAnd(
1836 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
1837
1838 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
1839 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
1840 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
1841 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
1842
1843 CGF.EmitBlock(CpyThenBB);
1844 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1845 RemoteReduceList, LocalReduceList);
1846 Bld.CreateBr(CpyMergeBB);
1847
1848 CGF.EmitBlock(CpyElseBB);
1849 Bld.CreateBr(CpyMergeBB);
1850
1851 CGF.EmitBlock(CpyMergeBB);
1852
1853 CGF.FinishFunction();
1854 return Fn;
1855}
1856
1857///
1858/// Design of OpenMP reductions on the GPU
1859///
1860/// Consider a typical OpenMP program with one or more reduction
1861/// clauses:
1862///
1863/// float foo;
1864/// double bar;
1865/// #pragma omp target teams distribute parallel for \
1866/// reduction(+:foo) reduction(*:bar)
1867/// for (int i = 0; i < N; i++) {
1868/// foo += A[i]; bar *= B[i];
1869/// }
1870///
1871/// where 'foo' and 'bar' are reduced across all OpenMP threads in
1872/// all teams. In our OpenMP implementation on the NVPTX device an
1873/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1874/// within a team are mapped to CUDA threads within a threadblock.
1875/// Our goal is to efficiently aggregate values across all OpenMP
1876/// threads such that:
1877///
1878/// - the compiler and runtime are logically concise, and
1879/// - the reduction is performed efficiently in a hierarchical
1880/// manner as follows: within OpenMP threads in the same warp,
1881/// across warps in a threadblock, and finally across teams on
1882/// the NVPTX device.
1883///
1884/// Introduction to Decoupling
1885///
1886/// We would like to decouple the compiler and the runtime so that the
1887/// latter is ignorant of the reduction variables (number, data types)
1888/// and the reduction operators. This allows a simpler interface
1889/// and implementation while still attaining good performance.
1890///
1891/// Pseudocode for the aforementioned OpenMP program generated by the
1892/// compiler is as follows:
1893///
1894/// 1. Create private copies of reduction variables on each OpenMP
1895/// thread: 'foo_private', 'bar_private'
1896/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1897/// to it and writes the result in 'foo_private' and 'bar_private'
1898/// respectively.
1899/// 3. Call the OpenMP runtime on the GPU to reduce within a team
1900/// and store the result on the team master:
1901///
1902/// __kmpc_nvptx_parallel_reduce_nowait(...,
1903/// reduceData, shuffleReduceFn, interWarpCpyFn)
1904///
1905/// where:
1906/// struct ReduceData {
1907/// double *foo;
1908/// double *bar;
1909/// } reduceData
1910/// reduceData.foo = &foo_private
1911/// reduceData.bar = &bar_private
1912///
1913/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1914/// auxiliary functions generated by the compiler that operate on
1915/// variables of type 'ReduceData'. They aid the runtime perform
1916/// algorithmic steps in a data agnostic manner.
1917///
1918/// 'shuffleReduceFn' is a pointer to a function that reduces data
1919/// of type 'ReduceData' across two OpenMP threads (lanes) in the
1920/// same warp. It takes the following arguments as input:
1921///
1922/// a. variable of type 'ReduceData' on the calling lane,
1923/// b. its lane_id,
1924/// c. an offset relative to the current lane_id to generate a
1925/// remote_lane_id. The remote lane contains the second
1926/// variable of type 'ReduceData' that is to be reduced.
1927/// d. an algorithm version parameter determining which reduction
1928/// algorithm to use.
1929///
1930/// 'shuffleReduceFn' retrieves data from the remote lane using
1931/// efficient GPU shuffle intrinsics and reduces, using the
1932/// algorithm specified by the 4th parameter, the two operands
1933/// element-wise. The result is written to the first operand.
1934///
1935/// Different reduction algorithms are implemented in different
1936/// runtime functions, all calling 'shuffleReduceFn' to perform
1937/// the essential reduction step. Therefore, based on the 4th
1938/// parameter, this function behaves slightly differently to
1939/// cooperate with the runtime to ensure correctness under
1940/// different circumstances.
1941///
1942/// 'InterWarpCpyFn' is a pointer to a function that transfers
1943/// reduced variables across warps. It tunnels, through CUDA
1944/// shared memory, the thread-private data of type 'ReduceData'
1945/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001946/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1947/// The last team writes the global reduced value to memory.
1948///
1949/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1950/// reduceData, shuffleReduceFn, interWarpCpyFn,
1951/// scratchpadCopyFn, loadAndReduceFn)
1952///
1953/// 'scratchpadCopyFn' is a helper that stores reduced
1954/// data from the team master to a scratchpad array in
1955/// global memory.
1956///
1957/// 'loadAndReduceFn' is a helper that loads data from
1958/// the scratchpad array and reduces it with the input
1959/// operand.
1960///
1961/// These compiler generated functions hide address
1962/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001963/// 5. if ret == 1:
1964/// The team master of the last team stores the reduced
1965/// result to the globals in memory.
1966/// foo += reduceData.foo; bar *= reduceData.bar
1967///
1968///
1969/// Warp Reduction Algorithms
1970///
1971/// On the warp level, we have three algorithms implemented in the
1972/// OpenMP runtime depending on the number of active lanes:
1973///
1974/// Full Warp Reduction
1975///
1976/// The reduce algorithm within a warp where all lanes are active
1977/// is implemented in the runtime as follows:
1978///
1979/// full_warp_reduce(void *reduce_data,
1980/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1981/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1982/// ShuffleReduceFn(reduce_data, 0, offset, 0);
1983/// }
1984///
1985/// The algorithm completes in log(2, WARPSIZE) steps.
1986///
1987/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
1988/// not used therefore we save instructions by not retrieving lane_id
1989/// from the corresponding special registers. The 4th parameter, which
1990/// represents the version of the algorithm being used, is set to 0 to
1991/// signify full warp reduction.
1992///
1993/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1994///
1995/// #reduce_elem refers to an element in the local lane's data structure
1996/// #remote_elem is retrieved from a remote lane
1997/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1998/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
1999///
2000/// Contiguous Partial Warp Reduction
2001///
2002/// This reduce algorithm is used within a warp where only the first
2003/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2004/// number of OpenMP threads in a parallel region is not a multiple of
2005/// WARPSIZE. The algorithm is implemented in the runtime as follows:
2006///
2007/// void
2008/// contiguous_partial_reduce(void *reduce_data,
2009/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2010/// int size, int lane_id) {
2011/// int curr_size;
2012/// int offset;
2013/// curr_size = size;
2014/// mask = curr_size/2;
2015/// while (offset>0) {
2016/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2017/// curr_size = (curr_size+1)/2;
2018/// offset = curr_size/2;
2019/// }
2020/// }
2021///
2022/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2023///
2024/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2025/// if (lane_id < offset)
2026/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2027/// else
2028/// reduce_elem = remote_elem
2029///
2030/// This algorithm assumes that the data to be reduced are located in a
2031/// contiguous subset of lanes starting from the first. When there is
2032/// an odd number of active lanes, the data in the last lane is not
2033/// aggregated with any other lane's dat but is instead copied over.
2034///
2035/// Dispersed Partial Warp Reduction
2036///
2037/// This algorithm is used within a warp when any discontiguous subset of
2038/// lanes are active. It is used to implement the reduction operation
2039/// across lanes in an OpenMP simd region or in a nested parallel region.
2040///
2041/// void
2042/// dispersed_partial_reduce(void *reduce_data,
2043/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2044/// int size, remote_id;
2045/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2046/// do {
2047/// remote_id = next_active_lane_id_right_after_me();
2048/// # the above function returns 0 of no active lane
2049/// # is present right after the current lane.
2050/// size = number_of_active_lanes_in_this_warp();
2051/// logical_lane_id /= 2;
2052/// ShuffleReduceFn(reduce_data, logical_lane_id,
2053/// remote_id-1-threadIdx.x, 2);
2054/// } while (logical_lane_id % 2 == 0 && size > 1);
2055/// }
2056///
2057/// There is no assumption made about the initial state of the reduction.
2058/// Any number of lanes (>=1) could be active at any position. The reduction
2059/// result is returned in the first active lane.
2060///
2061/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2062///
2063/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2064/// if (lane_id % 2 == 0 && offset > 0)
2065/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2066/// else
2067/// reduce_elem = remote_elem
2068///
2069///
2070/// Intra-Team Reduction
2071///
2072/// This function, as implemented in the runtime call
2073/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
2074/// threads in a team. It first reduces within a warp using the
2075/// aforementioned algorithms. We then proceed to gather all such
2076/// reduced values at the first warp.
2077///
2078/// The runtime makes use of the function 'InterWarpCpyFn', which copies
2079/// data from each of the "warp master" (zeroth lane of each warp, where
2080/// warp-reduced data is held) to the zeroth warp. This step reduces (in
2081/// a mathematical sense) the problem of reduction across warp masters in
2082/// a block to the problem of warp reduction.
2083///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002084///
2085/// Inter-Team Reduction
2086///
2087/// Once a team has reduced its data to a single value, it is stored in
2088/// a global scratchpad array. Since each team has a distinct slot, this
2089/// can be done without locking.
2090///
2091/// The last team to write to the scratchpad array proceeds to reduce the
2092/// scratchpad array. One or more workers in the last team use the helper
2093/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2094/// the k'th worker reduces every k'th element.
2095///
2096/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
2097/// reduce across workers and compute a globally reduced value.
2098///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002099void CGOpenMPRuntimeNVPTX::emitReduction(
2100 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
2101 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
2102 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
2103 if (!CGF.HaveInsertPoint())
2104 return;
2105
2106 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002107 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
2108 // FIXME: Add support for simd reduction.
2109 assert((TeamsReduction || ParallelReduction) &&
2110 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002111
2112 auto &C = CGM.getContext();
2113
2114 // 1. Build a list of reduction variables.
2115 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2116 auto Size = RHSExprs.size();
2117 for (auto *E : Privates) {
2118 if (E->getType()->isVariablyModifiedType())
2119 // Reserve place for array size.
2120 ++Size;
2121 }
2122 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
2123 QualType ReductionArrayTy =
2124 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2125 /*IndexTypeQuals=*/0);
2126 Address ReductionList =
2127 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2128 auto IPriv = Privates.begin();
2129 unsigned Idx = 0;
2130 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
2131 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2132 CGF.getPointerSize());
2133 CGF.Builder.CreateStore(
2134 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2135 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2136 Elem);
2137 if ((*IPriv)->getType()->isVariablyModifiedType()) {
2138 // Store array size.
2139 ++Idx;
2140 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2141 CGF.getPointerSize());
2142 llvm::Value *Size = CGF.Builder.CreateIntCast(
2143 CGF.getVLASize(
2144 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2145 .first,
2146 CGF.SizeTy, /*isSigned=*/false);
2147 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2148 Elem);
2149 }
2150 }
2151
2152 // 2. Emit reduce_func().
2153 auto *ReductionFn = emitReductionFunction(
2154 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
2155 LHSExprs, RHSExprs, ReductionOps);
2156
2157 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
2158 // RedList, shuffle_reduce_func, interwarp_copy_func);
2159 auto *ThreadId = getThreadID(CGF, Loc);
2160 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
2161 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2162 ReductionList.getPointer(), CGF.VoidPtrTy);
2163
2164 auto *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
2165 CGM, Privates, ReductionArrayTy, ReductionFn);
2166 auto *InterWarpCopyFn =
2167 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy);
2168
2169 llvm::Value *Res = nullptr;
2170 if (ParallelReduction) {
2171 llvm::Value *Args[] = {ThreadId,
2172 CGF.Builder.getInt32(RHSExprs.size()),
2173 ReductionArrayTySize,
2174 RL,
2175 ShuffleAndReduceFn,
2176 InterWarpCopyFn};
2177
2178 Res = CGF.EmitRuntimeCall(
2179 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
2180 Args);
2181 }
2182
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002183 if (TeamsReduction) {
2184 auto *ScratchPadCopyFn =
2185 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy);
2186 auto *LoadAndReduceFn = emitReduceScratchpadFunction(
2187 CGM, Privates, ReductionArrayTy, ReductionFn);
2188
2189 llvm::Value *Args[] = {ThreadId,
2190 CGF.Builder.getInt32(RHSExprs.size()),
2191 ReductionArrayTySize,
2192 RL,
2193 ShuffleAndReduceFn,
2194 InterWarpCopyFn,
2195 ScratchPadCopyFn,
2196 LoadAndReduceFn};
2197 Res = CGF.EmitRuntimeCall(
2198 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
2199 Args);
2200 }
2201
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002202 // 5. Build switch(res)
2203 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2204 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
2205
2206 // 6. Build case 1: where we have reduced values in the master
2207 // thread in each team.
2208 // __kmpc_end_reduce{_nowait}(<gtid>);
2209 // break;
2210 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2211 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2212 CGF.EmitBlock(Case1BB);
2213
2214 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
2215 llvm::Value *EndArgs[] = {ThreadId};
2216 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps,
2217 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
2218 auto IPriv = Privates.begin();
2219 auto ILHS = LHSExprs.begin();
2220 auto IRHS = RHSExprs.begin();
2221 for (auto *E : ReductionOps) {
2222 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
2223 cast<DeclRefExpr>(*IRHS));
2224 ++IPriv;
2225 ++ILHS;
2226 ++IRHS;
2227 }
2228 };
2229 RegionCodeGenTy RCG(CodeGen);
2230 NVPTXActionTy Action(
2231 nullptr, llvm::None,
2232 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
2233 EndArgs);
2234 RCG.setAction(Action);
2235 RCG(CGF);
2236 CGF.EmitBranch(DefaultBB);
2237 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2238}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002239
2240const VarDecl *
2241CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
2242 const VarDecl *NativeParam) const {
2243 if (!NativeParam->getType()->isReferenceType())
2244 return NativeParam;
2245 QualType ArgType = NativeParam->getType();
2246 QualifierCollector QC;
2247 const Type *NonQualTy = QC.strip(ArgType);
2248 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2249 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
2250 if (Attr->getCaptureKind() == OMPC_map) {
2251 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
2252 LangAS::opencl_global);
2253 }
2254 }
2255 ArgType = CGM.getContext().getPointerType(PointeeTy);
2256 QC.addRestrict();
2257 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00002258 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002259 ArgType = QC.apply(CGM.getContext(), ArgType);
2260 return ImplicitParamDecl::Create(
2261 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
2262 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
2263}
2264
2265Address
2266CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
2267 const VarDecl *NativeParam,
2268 const VarDecl *TargetParam) const {
2269 assert(NativeParam != TargetParam &&
2270 NativeParam->getType()->isReferenceType() &&
2271 "Native arg must not be the same as target arg.");
2272 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
2273 QualType NativeParamType = NativeParam->getType();
2274 QualifierCollector QC;
2275 const Type *NonQualTy = QC.strip(NativeParamType);
2276 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2277 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00002278 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002279 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002280 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002281 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002282 // First cast to generic.
2283 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2284 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2285 /*AddrSpace=*/0));
2286 // Cast from generic to native address space.
2287 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2288 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2289 NativePointeeAddrSpace));
2290 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
2291 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002292 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002293 return NativeParamAddr;
2294}
2295
2296void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00002297 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002298 ArrayRef<llvm::Value *> Args) const {
2299 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002300 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002301 auto *FnType =
2302 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
2303 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002304 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
2305 TargetArgs.append(std::next(Args.begin(), I), Args.end());
2306 break;
2307 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002308 llvm::Type *TargetType = FnType->getParamType(I);
2309 llvm::Value *NativeArg = Args[I];
2310 if (!TargetType->isPointerTy()) {
2311 TargetArgs.emplace_back(NativeArg);
2312 continue;
2313 }
2314 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2315 NativeArg, NativeArg->getType()->getPointerElementType()->getPointerTo(
2316 /*AddrSpace=*/0));
2317 TargetArgs.emplace_back(
2318 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
2319 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002320 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002321}