blob: c0bf6e13b2af52df9811da3c963f76626067e1a2 [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 {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000025 /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
26 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000027 OMPRTL_NVPTX__kmpc_kernel_init,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// \brief Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000029 OMPRTL_NVPTX__kmpc_kernel_deinit,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000030 /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000031 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000032 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
33 /// \brief Call to void __kmpc_spmd_kernel_deinit();
34 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000035 /// \brief Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000036 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000037 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000038 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000039 /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function,
40 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_parallel,
42 /// \brief Call to void __kmpc_kernel_end_parallel();
43 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
44 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
45 /// global_tid);
46 OMPRTL_NVPTX__kmpc_serialized_parallel,
47 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000050 /// \brief Call to int32_t __kmpc_shuffle_int32(int32_t element,
51 /// int16_t lane_offset, int16_t warp_size);
52 OMPRTL_NVPTX__kmpc_shuffle_int32,
53 /// \brief Call to int64_t __kmpc_shuffle_int64(int64_t element,
54 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int64,
56 /// \brief Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
57 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
58 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
59 /// lane_offset, int16_t shortCircuit),
60 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
61 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000062 /// \brief Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
63 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
64 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
65 /// lane_offset, int16_t shortCircuit),
66 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
67 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
68 /// int32_t index, int32_t width),
69 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
70 /// index, int32_t width, int32_t reduce))
71 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000072 /// \brief Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
73 OMPRTL_NVPTX__kmpc_end_reduce_nowait
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000074};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000075
76/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
77class NVPTXActionTy final : public PrePostActionTy {
78 llvm::Value *EnterCallee;
79 ArrayRef<llvm::Value *> EnterArgs;
80 llvm::Value *ExitCallee;
81 ArrayRef<llvm::Value *> ExitArgs;
82 bool Conditional;
83 llvm::BasicBlock *ContBlock = nullptr;
84
85public:
86 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
87 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
88 bool Conditional = false)
89 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
90 ExitArgs(ExitArgs), Conditional(Conditional) {}
91 void Enter(CodeGenFunction &CGF) override {
92 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
93 if (Conditional) {
94 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
95 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
96 ContBlock = CGF.createBasicBlock("omp_if.end");
97 // Generate the branch (If-stmt)
98 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
99 CGF.EmitBlock(ThenBlock);
100 }
101 }
102 void Done(CodeGenFunction &CGF) {
103 // Emit the rest of blocks/branches
104 CGF.EmitBranch(ContBlock);
105 CGF.EmitBlock(ContBlock, true);
106 }
107 void Exit(CodeGenFunction &CGF) override {
108 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
109 }
110};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000111
112// A class to track the execution mode when codegening directives within
113// a target region. The appropriate mode (generic/spmd) is set on entry
114// to the target region and used by containing directives such as 'parallel'
115// to emit optimized code.
116class ExecutionModeRAII {
117private:
118 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
119 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
120
121public:
122 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode,
123 CGOpenMPRuntimeNVPTX::ExecutionMode NewMode)
124 : Mode(Mode) {
125 SavedMode = Mode;
126 Mode = NewMode;
127 }
128 ~ExecutionModeRAII() { Mode = SavedMode; }
129};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000130
131/// GPU Configuration: This information can be derived from cuda registers,
132/// however, providing compile time constants helps generate more efficient
133/// code. For all practical purposes this is fine because the configuration
134/// is the same for all known NVPTX architectures.
135enum MachineConfiguration : unsigned {
136 WarpSize = 32,
137 /// Number of bits required to represent a lane identifier, which is
138 /// computed as log_2(WarpSize).
139 LaneIDBits = 5,
140 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000141
142 /// Global memory alignment for performance.
143 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000144};
145
146enum NamedBarrier : unsigned {
147 /// Synchronize on this barrier #ID using a named barrier primitive.
148 /// Only the subset of active threads in a parallel region arrive at the
149 /// barrier.
150 NB_Parallel = 1,
151};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000152} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000153
154/// Get the GPU warp size.
155static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000156 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000157 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000158 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000159 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000160}
161
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000162/// Get the id of the current thread on the GPU.
163static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000164 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000165 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000166 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000167 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000168}
169
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000170/// Get the id of the warp in the block.
171/// We assume that the warp size is 32, which is always the case
172/// on the NVPTX device, to generate more efficient code.
173static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
174 CGBuilderTy &Bld = CGF.Builder;
175 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
176}
177
178/// Get the id of the current lane in the Warp.
179/// We assume that the warp size is 32, which is always the case
180/// on the NVPTX device, to generate more efficient code.
181static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
182 CGBuilderTy &Bld = CGF.Builder;
183 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
184 "nvptx_lane_id");
185}
186
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000187/// Get the maximum number of threads in a block of the GPU.
188static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000189 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000190 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000191 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000192 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000193}
194
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000195/// Get barrier to synchronize all threads in a block.
196static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000197 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000198 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000199}
200
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000201/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
202/// a CTA.
203static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
204 llvm::Value *NumThreads) {
205 CGBuilderTy &Bld = CGF.Builder;
206 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000207 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
208 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
209 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000210}
211
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000212/// Synchronize all GPU threads in a block.
213static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000214
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000215/// Synchronize worker threads in a parallel region.
216static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
217 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
218}
219
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000220/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000221/// For the 'generic' execution mode, the runtime encodes thread_limit in
222/// the launch parameters, always starting thread_limit+warpSize threads per
223/// CTA. The threads in the last warp are reserved for master execution.
224/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
225static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
226 bool IsInSpmdExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000227 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000228 return IsInSpmdExecutionMode
229 ? getNVPTXNumThreads(CGF)
230 : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
231 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000232}
233
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000234/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000235/// The master thread id is the first thread (lane) of the last warp in the
236/// GPU block. Warp size is assumed to be some power of 2.
237/// Thread id is 0 indexed.
238/// E.g: If NumThreads is 33, master id is 32.
239/// If NumThreads is 64, master id is 32.
240/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000241static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000242 CGBuilderTy &Bld = CGF.Builder;
243 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
244
245 // We assume that the warp size is a power of 2.
246 llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
247
248 return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)),
249 Bld.CreateNot(Mask), "master_tid");
250}
251
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000252CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000253 CodeGenModule &CGM, SourceLocation Loc)
254 : WorkerFn(nullptr), CGFI(nullptr), Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000255 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000256}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000257
258void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
259 CodeGenModule &CGM) {
260 // Create an worker function with no arguments.
261 CGFI = &CGM.getTypes().arrangeNullaryFunction();
262
263 WorkerFn = llvm::Function::Create(
264 CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000265 /*placeholder=*/"_worker", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +0000266 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, *CGFI);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000267}
268
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000269bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const {
270 return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd;
271}
272
273static CGOpenMPRuntimeNVPTX::ExecutionMode
Carlo Bertolli79712092018-02-28 20:48:35 +0000274getExecutionMode(CodeGenModule &CGM) {
275 return CGM.getLangOpts().OpenMPCUDAMode
276 ? CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd
277 : CGOpenMPRuntimeNVPTX::ExecutionMode::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000278}
279
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000280void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D,
281 StringRef ParentName,
282 llvm::Function *&OutlinedFn,
283 llvm::Constant *&OutlinedFnID,
284 bool IsOffloadEntry,
285 const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000286 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
287 CGOpenMPRuntimeNVPTX::ExecutionMode::Generic);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000288 EntryFunctionState EST;
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000289 WorkerFunctionState WST(CGM, D.getLocStart());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000290 Work.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000291
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000292 // Emit target region as a standalone region.
293 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000294 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
295 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000296
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000297 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000298 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000299 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000300 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000301 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000302 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
303 .emitGenericEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000304 }
305 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000306 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
307 .emitGenericEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000308 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000309 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000310 CodeGen.setAction(Action);
311 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
312 IsOffloadEntry, CodeGen);
313
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000314 // Now change the name of the worker function to correspond to this target
315 // region's entry function.
316 WST.WorkerFn->setName(OutlinedFn->getName() + "_worker");
Alexey Bataevaee93892018-01-08 20:09:47 +0000317
318 // Create the worker function
319 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000320}
321
322// Setup NVPTX threads for master-worker OpenMP scheme.
323void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF,
324 EntryFunctionState &EST,
325 WorkerFunctionState &WST) {
326 CGBuilderTy &Bld = CGF.Builder;
327
328 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
329 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
330 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
331 EST.ExitBB = CGF.createBasicBlock(".exit");
332
333 auto *IsWorker =
334 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
335 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
336
337 CGF.EmitBlock(WorkerBB);
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000338 emitOutlinedFunctionCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000339 CGF.EmitBranch(EST.ExitBB);
340
341 CGF.EmitBlock(MasterCheckBB);
342 auto *IsMaster =
343 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
344 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
345
346 CGF.EmitBlock(MasterBB);
347 // First action in sequential region:
348 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000349 // TODO: Optimize runtime initialization and pass in correct value.
350 llvm::Value *Args[] = {getThreadLimit(CGF),
351 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000352 CGF.EmitRuntimeCall(
353 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
354}
355
356void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF,
357 EntryFunctionState &EST) {
358 if (!EST.ExitBB)
359 EST.ExitBB = CGF.createBasicBlock(".exit");
360
361 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
362 CGF.EmitBranch(TerminateBB);
363
364 CGF.EmitBlock(TerminateBB);
365 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000366 // TODO: Optimize runtime initialization and pass in correct value.
367 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000368 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000369 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000370 // Barrier to terminate worker threads.
371 syncCTAThreads(CGF);
372 // Master thread jumps to exit point.
373 CGF.EmitBranch(EST.ExitBB);
374
375 CGF.EmitBlock(EST.ExitBB);
376 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000377}
378
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000379void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D,
380 StringRef ParentName,
381 llvm::Function *&OutlinedFn,
382 llvm::Constant *&OutlinedFnID,
383 bool IsOffloadEntry,
384 const RegionCodeGenTy &CodeGen) {
385 ExecutionModeRAII ModeRAII(CurrentExecutionMode,
386 CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd);
387 EntryFunctionState EST;
388
389 // Emit target region as a standalone region.
390 class NVPTXPrePostActionTy : public PrePostActionTy {
391 CGOpenMPRuntimeNVPTX &RT;
392 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
393 const OMPExecutableDirective &D;
394
395 public:
396 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
397 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
398 const OMPExecutableDirective &D)
399 : RT(RT), EST(EST), D(D) {}
400 void Enter(CodeGenFunction &CGF) override {
401 RT.emitSpmdEntryHeader(CGF, EST, D);
402 }
403 void Exit(CodeGenFunction &CGF) override {
404 RT.emitSpmdEntryFooter(CGF, EST);
405 }
406 } Action(*this, EST, D);
407 CodeGen.setAction(Action);
408 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
409 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000410}
411
412void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader(
413 CodeGenFunction &CGF, EntryFunctionState &EST,
414 const OMPExecutableDirective &D) {
415 auto &Bld = CGF.Builder;
416
417 // Setup BBs in entry function.
418 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
419 EST.ExitBB = CGF.createBasicBlock(".exit");
420
421 // Initialize the OMP state in the runtime; called by all active threads.
422 // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters
423 // based on code analysis of the target region.
424 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true),
425 /*RequiresOMPRuntime=*/Bld.getInt16(1),
426 /*RequiresDataSharing=*/Bld.getInt16(1)};
427 CGF.EmitRuntimeCall(
428 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
429 CGF.EmitBranch(ExecuteBB);
430
431 CGF.EmitBlock(ExecuteBB);
432}
433
434void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF,
435 EntryFunctionState &EST) {
436 if (!EST.ExitBB)
437 EST.ExitBB = CGF.createBasicBlock(".exit");
438
439 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
440 CGF.EmitBranch(OMPDeInitBB);
441
442 CGF.EmitBlock(OMPDeInitBB);
443 // DeInitialize the OMP state in the runtime; called by all active threads.
444 CGF.EmitRuntimeCall(
445 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
446 CGF.EmitBranch(EST.ExitBB);
447
448 CGF.EmitBlock(EST.ExitBB);
449 EST.ExitBB = nullptr;
450}
451
452// Create a unique global variable to indicate the execution mode of this target
453// region. The execution mode is either 'generic', or 'spmd' depending on the
454// target directive. This variable is picked up by the offload library to setup
455// the device appropriately before kernel launch. If the execution mode is
456// 'generic', the runtime reserves one warp for the master, otherwise, all
457// warps participate in parallel work.
458static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
459 CGOpenMPRuntimeNVPTX::ExecutionMode Mode) {
460 (void)new llvm::GlobalVariable(
461 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
462 llvm::GlobalValue::WeakAnyLinkage,
463 llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode"));
464}
465
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000466void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000467 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000468
469 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000470 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {},
471 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000472 emitWorkerLoop(CGF, WST);
473 CGF.FinishFunction();
474}
475
476void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
477 WorkerFunctionState &WST) {
478 //
479 // The workers enter this loop and wait for parallel work from the master.
480 // When the master encounters a parallel region it sets up the work + variable
481 // arguments, and wakes up the workers. The workers first check to see if
482 // they are required for the parallel region, i.e., within the # of requested
483 // parallel threads. The activated workers load the variable arguments and
484 // execute the parallel work.
485 //
486
487 CGBuilderTy &Bld = CGF.Builder;
488
489 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
490 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
491 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
492 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
493 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
494 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
495
496 CGF.EmitBranch(AwaitBB);
497
498 // Workers wait for work from master.
499 CGF.EmitBlock(AwaitBB);
500 // Wait for parallel work
501 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000502
503 Address WorkFn =
504 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
505 Address ExecStatus =
506 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
507 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
508 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
509
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000510 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000511 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000512 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000513 llvm::Value *Ret = CGF.EmitRuntimeCall(
514 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
515 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000516
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000517 // On termination condition (workid == 0), exit loop.
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000518 llvm::Value *ShouldTerminate =
519 Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000520 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
521
522 // Activate requested workers.
523 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000524 llvm::Value *IsActive =
525 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
526 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000527
528 // Signal start of parallel region.
529 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000530
531 // Process work items: outlined parallel functions.
532 for (auto *W : Work) {
533 // Try to match this outlined function.
534 auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
535
536 llvm::Value *WorkFnMatch =
537 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
538
539 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
540 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
541 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
542
543 // Execute this outlined function.
544 CGF.EmitBlock(ExecuteFNBB);
545
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000546 // Insert call to work function.
547 // FIXME: Pass arguments to outlined function from master thread.
548 auto *Fn = cast<llvm::Function>(W);
549 Address ZeroAddr =
550 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, /*Name=*/".zero.addr");
551 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C=*/0));
552 llvm::Value *FnArgs[] = {ZeroAddr.getPointer(), ZeroAddr.getPointer()};
553 emitCall(CGF, WST.Loc, Fn, FnArgs);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000554
555 // Go to end of parallel region.
556 CGF.EmitBranch(TerminateBB);
557
558 CGF.EmitBlock(CheckNextBB);
559 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000560
561 // Signal end of parallel region.
562 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000563 CGF.EmitRuntimeCall(
564 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
565 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000566 CGF.EmitBranch(BarrierBB);
567
568 // All active and inactive workers wait at a barrier after parallel region.
569 CGF.EmitBlock(BarrierBB);
570 // Barrier after parallel region.
571 syncCTAThreads(CGF);
572 CGF.EmitBranch(AwaitBB);
573
574 // Exit target region.
575 CGF.EmitBlock(ExitBB);
576}
577
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000578/// \brief Returns specified OpenMP runtime function for the current OpenMP
579/// implementation. Specialized for the NVPTX device.
580/// \param Function OpenMP runtime function.
581/// \return Specified function.
582llvm::Constant *
583CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
584 llvm::Constant *RTLFn = nullptr;
585 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
586 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000587 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
588 // RequiresOMPRuntime);
589 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000590 llvm::FunctionType *FnTy =
591 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
593 break;
594 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000595 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000596 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
597 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000598 llvm::FunctionType *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000599 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
601 break;
602 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000603 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
604 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +0000605 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000606 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
607 llvm::FunctionType *FnTy =
608 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
609 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
610 break;
611 }
612 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
613 // Build void __kmpc_spmd_kernel_deinit();
614 llvm::FunctionType *FnTy =
615 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
616 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
617 break;
618 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000619 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
620 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000621 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +0000622 llvm::Type *TypeParams[] = {CGM.Int8PtrTy,
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +0000623 CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000624 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: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000630 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
631 /// int16_t IsOMPRuntimeInitialized);
632 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000633 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
634 llvm::FunctionType *FnTy =
635 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
637 break;
638 }
639 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
640 /// Build void __kmpc_kernel_end_parallel();
641 llvm::FunctionType *FnTy =
642 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
643 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
644 break;
645 }
646 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
647 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
648 // global_tid);
649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
650 llvm::FunctionType *FnTy =
651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
652 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
653 break;
654 }
655 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
656 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
657 // global_tid);
658 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
659 llvm::FunctionType *FnTy =
660 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
661 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
662 break;
663 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000664 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
665 // Build int32_t __kmpc_shuffle_int32(int32_t element,
666 // int16_t lane_offset, int16_t warp_size);
667 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
668 llvm::FunctionType *FnTy =
669 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
670 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
671 break;
672 }
673 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
674 // Build int64_t __kmpc_shuffle_int64(int64_t element,
675 // int16_t lane_offset, int16_t warp_size);
676 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
677 llvm::FunctionType *FnTy =
678 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
679 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
680 break;
681 }
682 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
683 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
684 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
685 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
686 // lane_offset, int16_t Algorithm Version),
687 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
688 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
689 CGM.Int16Ty, CGM.Int16Ty};
690 auto *ShuffleReduceFnTy =
691 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
692 /*isVarArg=*/false);
693 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
694 auto *InterWarpCopyFnTy =
695 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
696 /*isVarArg=*/false);
697 llvm::Type *TypeParams[] = {CGM.Int32Ty,
698 CGM.Int32Ty,
699 CGM.SizeTy,
700 CGM.VoidPtrTy,
701 ShuffleReduceFnTy->getPointerTo(),
702 InterWarpCopyFnTy->getPointerTo()};
703 llvm::FunctionType *FnTy =
704 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
705 RTLFn = CGM.CreateRuntimeFunction(
706 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
707 break;
708 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000709 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
710 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
711 // int32_t num_vars, size_t reduce_size, void *reduce_data,
712 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
713 // lane_offset, int16_t shortCircuit),
714 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
715 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
716 // int32_t index, int32_t width),
717 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
718 // int32_t index, int32_t width, int32_t reduce))
719 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
720 CGM.Int16Ty, CGM.Int16Ty};
721 auto *ShuffleReduceFnTy =
722 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
723 /*isVarArg=*/false);
724 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
725 auto *InterWarpCopyFnTy =
726 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
727 /*isVarArg=*/false);
728 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
729 CGM.Int32Ty, CGM.Int32Ty};
730 auto *CopyToScratchpadFnTy =
731 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
732 /*isVarArg=*/false);
733 llvm::Type *LoadReduceTypeParams[] = {
734 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
735 auto *LoadReduceFnTy =
736 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
737 /*isVarArg=*/false);
738 llvm::Type *TypeParams[] = {CGM.Int32Ty,
739 CGM.Int32Ty,
740 CGM.SizeTy,
741 CGM.VoidPtrTy,
742 ShuffleReduceFnTy->getPointerTo(),
743 InterWarpCopyFnTy->getPointerTo(),
744 CopyToScratchpadFnTy->getPointerTo(),
745 LoadReduceFnTy->getPointerTo()};
746 llvm::FunctionType *FnTy =
747 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
748 RTLFn = CGM.CreateRuntimeFunction(
749 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
750 break;
751 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000752 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
753 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
754 llvm::Type *TypeParams[] = {CGM.Int32Ty};
755 llvm::FunctionType *FnTy =
756 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
757 RTLFn = CGM.CreateRuntimeFunction(
758 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
759 break;
760 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000761 }
762 return RTLFn;
763}
764
765void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
766 llvm::Constant *Addr,
Samuel Antaof83efdb2017-01-05 16:02:49 +0000767 uint64_t Size, int32_t) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000768 auto *F = dyn_cast<llvm::Function>(Addr);
769 // TODO: Add support for global variables on the device after declare target
770 // support.
771 if (!F)
772 return;
773 llvm::Module *M = F->getParent();
774 llvm::LLVMContext &Ctx = M->getContext();
775
776 // Get "nvvm.annotations" metadata node
777 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
778
779 llvm::Metadata *MDVals[] = {
780 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"),
781 llvm::ConstantAsMetadata::get(
782 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
783 // Append metadata to nvvm.annotations
784 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
785}
786
787void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
788 const OMPExecutableDirective &D, StringRef ParentName,
789 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000790 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000791 if (!IsOffloadEntry) // Nothing to do.
792 return;
793
794 assert(!ParentName.empty() && "Invalid target region parent name!");
795
Carlo Bertolli79712092018-02-28 20:48:35 +0000796 CGOpenMPRuntimeNVPTX::ExecutionMode Mode = getExecutionMode(CGM);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000797 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) {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000850 return CGOpenMPRuntime::emitParallelOutlinedFunction(D, ThreadIDVar,
851 InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000852}
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
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000904 auto &&L0ParallelGen = [this, Fn](CodeGenFunction &CGF, PrePostActionTy &) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000905 CGBuilderTy &Bld = CGF.Builder;
906
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000907 // TODO: Optimize runtime initialization.
908 llvm::Value *Args[] = {Bld.CreateBitOrPointerCast(Fn, CGM.Int8PtrTy),
909 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
910 CGF.EmitRuntimeCall(
911 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
912 Args);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000913
914 // Activate workers. This barrier is used by the master to signal
915 // work for the workers.
916 syncCTAThreads(CGF);
917
918 // OpenMP [2.5, Parallel Construct, p.49]
919 // There is an implied barrier at the end of a parallel region. After the
920 // end of a parallel region, only the master thread of the team resumes
921 // execution of the enclosing task region.
922 //
923 // The master waits at this barrier until all workers are done.
924 syncCTAThreads(CGF);
925
926 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +0000927 Work.emplace_back(Fn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000928 };
929
930 auto *RTLoc = emitUpdateLocation(CGF, Loc);
931 auto *ThreadID = getThreadID(CGF, Loc);
932 llvm::Value *Args[] = {RTLoc, ThreadID};
933
Alexey Bataev3c595a62017-08-14 15:01:03 +0000934 auto &&SeqGen = [this, Fn, &CapturedVars, &Args, Loc](CodeGenFunction &CGF,
935 PrePostActionTy &) {
936 auto &&CodeGen = [this, Fn, &CapturedVars, Loc](CodeGenFunction &CGF,
937 PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000938 Action.Enter(CGF);
939
940 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
941 OutlinedFnArgs.push_back(
942 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
943 OutlinedFnArgs.push_back(
944 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo()));
945 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000946 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000947 };
948
949 RegionCodeGenTy RCG(CodeGen);
950 NVPTXActionTy Action(
951 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
952 Args,
953 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
954 Args);
955 RCG.setAction(Action);
956 RCG(CGF);
957 };
958
959 if (IfCond)
960 emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen);
961 else {
962 CodeGenFunction::RunCleanupsScope Scope(CGF);
963 RegionCodeGenTy ThenRCG(L0ParallelGen);
964 ThenRCG(CGF);
965 }
966}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000967
968void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall(
969 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
970 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
971 // Just call the outlined function to execute the parallel region.
972 // OutlinedFn(&GTid, &zero, CapturedStruct);
973 //
974 // TODO: Do something with IfCond when support for the 'if' clause
975 // is added on Spmd target directives.
976 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +0000977
978 Address ZeroAddr = CGF.CreateMemTemp(
979 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
980 ".zero.addr");
981 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
982 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
983 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000984 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +0000985 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000986}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000987
Alexey Bataevb2575932018-01-04 20:18:55 +0000988/// Cast value to the specified type.
989static llvm::Value *
990castValueToType(CodeGenFunction &CGF, llvm::Value *Val, llvm::Type *CastTy,
991 llvm::Optional<bool> IsSigned = llvm::None) {
992 if (Val->getType() == CastTy)
993 return Val;
994 if (Val->getType()->getPrimitiveSizeInBits() > 0 &&
995 CastTy->getPrimitiveSizeInBits() > 0 &&
996 Val->getType()->getPrimitiveSizeInBits() ==
997 CastTy->getPrimitiveSizeInBits())
998 return CGF.Builder.CreateBitCast(Val, CastTy);
999 if (IsSigned.hasValue() && CastTy->isIntegerTy() &&
1000 Val->getType()->isIntegerTy())
1001 return CGF.Builder.CreateIntCast(Val, CastTy, *IsSigned);
1002 Address CastItem = CGF.CreateTempAlloca(
1003 CastTy,
1004 CharUnits::fromQuantity(
1005 CGF.CGM.getDataLayout().getPrefTypeAlignment(Val->getType())));
1006 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1007 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
1008 CGF.Builder.CreateStore(Val, ValCastItem);
1009 return CGF.Builder.CreateLoad(CastItem);
1010}
1011
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001012/// This function creates calls to one of two shuffle functions to copy
1013/// variables between lanes in a warp.
1014static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001015 llvm::Value *Elem,
1016 llvm::Value *Offset) {
1017 auto &CGM = CGF.CGM;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001018 auto &Bld = CGF.Builder;
1019 CGOpenMPRuntimeNVPTX &RT =
1020 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
1021
Alexey Bataevb2575932018-01-04 20:18:55 +00001022 unsigned Size = CGM.getDataLayout().getTypeStoreSize(Elem->getType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001023 assert(Size <= 8 && "Unsupported bitwidth in shuffle instruction.");
1024
1025 OpenMPRTLFunctionNVPTX ShuffleFn = Size <= 4
1026 ? OMPRTL_NVPTX__kmpc_shuffle_int32
1027 : OMPRTL_NVPTX__kmpc_shuffle_int64;
1028
1029 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataevb2575932018-01-04 20:18:55 +00001030 llvm::Type *CastTy = Size <= 4 ? CGM.Int32Ty : CGM.Int64Ty;
1031 llvm::Value *ElemCast = castValueToType(CGF, Elem, CastTy, /*isSigned=*/true);
1032 auto *WarpSize =
1033 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001034
1035 auto *ShuffledVal =
1036 CGF.EmitRuntimeCall(RT.createNVPTXRuntimeFunction(ShuffleFn),
1037 {ElemCast, Offset, WarpSize});
1038
Alexey Bataevb2575932018-01-04 20:18:55 +00001039 return castValueToType(CGF, ShuffledVal, Elem->getType(), /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001040}
1041
1042namespace {
1043enum CopyAction : unsigned {
1044 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1045 // the warp using shuffle instructions.
1046 RemoteLaneToThread,
1047 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1048 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001049 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1050 ThreadToScratchpad,
1051 // ScratchpadToThread: Copy from a scratchpad array in global memory
1052 // containing team-reduced data to a thread's stack.
1053 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001054};
1055} // namespace
1056
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001057struct CopyOptionsTy {
1058 llvm::Value *RemoteLaneOffset;
1059 llvm::Value *ScratchpadIndex;
1060 llvm::Value *ScratchpadWidth;
1061};
1062
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001063/// Emit instructions to copy a Reduce list, which contains partially
1064/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001065static void emitReductionListCopy(
1066 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1067 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1068 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001069
1070 auto &CGM = CGF.CGM;
1071 auto &C = CGM.getContext();
1072 auto &Bld = CGF.Builder;
1073
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001074 auto *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1075 auto *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1076 auto *ScratchpadWidth = CopyOptions.ScratchpadWidth;
1077
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001078 // Iterates, element-by-element, through the source Reduce list and
1079 // make a copy.
1080 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001081 unsigned Size = Privates.size();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001082 for (auto &Private : Privates) {
1083 Address SrcElementAddr = Address::invalid();
1084 Address DestElementAddr = Address::invalid();
1085 Address DestElementPtrAddr = Address::invalid();
1086 // Should we shuffle in an element from a remote lane?
1087 bool ShuffleInElement = false;
1088 // Set to true to update the pointer in the dest Reduce list to a
1089 // newly created element.
1090 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001091 // Increment the src or dest pointer to the scratchpad, for each
1092 // new element.
1093 bool IncrScratchpadSrc = false;
1094 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001095
1096 switch (Action) {
1097 case RemoteLaneToThread: {
1098 // Step 1.1: Get the address for the src element in the Reduce list.
1099 Address SrcElementPtrAddr =
1100 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001101 SrcElementAddr = CGF.EmitLoadOfPointer(
1102 SrcElementPtrAddr,
1103 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001104
1105 // Step 1.2: Create a temporary to store the element in the destination
1106 // Reduce list.
1107 DestElementPtrAddr =
1108 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1109 DestElementAddr =
1110 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1111 ShuffleInElement = true;
1112 UpdateDestListPtr = true;
1113 break;
1114 }
1115 case ThreadCopy: {
1116 // Step 1.1: Get the address for the src element in the Reduce list.
1117 Address SrcElementPtrAddr =
1118 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001119 SrcElementAddr = CGF.EmitLoadOfPointer(
1120 SrcElementPtrAddr,
1121 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001122
1123 // Step 1.2: Get the address for dest element. The destination
1124 // element has already been created on the thread's stack.
1125 DestElementPtrAddr =
1126 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001127 DestElementAddr = CGF.EmitLoadOfPointer(
1128 DestElementPtrAddr,
1129 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001130 break;
1131 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001132 case ThreadToScratchpad: {
1133 // Step 1.1: Get the address for the src element in the Reduce list.
1134 Address SrcElementPtrAddr =
1135 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00001136 SrcElementAddr = CGF.EmitLoadOfPointer(
1137 SrcElementPtrAddr,
1138 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001139
1140 // Step 1.2: Get the address for dest element:
1141 // address = base + index * ElementSizeInChars.
1142 unsigned ElementSizeInChars =
1143 C.getTypeSizeInChars(Private->getType()).getQuantity();
1144 auto *CurrentOffset =
1145 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1146 ScratchpadIndex);
1147 auto *ScratchPadElemAbsolutePtrVal =
1148 Bld.CreateAdd(DestBase.getPointer(), CurrentOffset);
1149 ScratchPadElemAbsolutePtrVal =
1150 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00001151 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1152 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001153 IncrScratchpadDest = true;
1154 break;
1155 }
1156 case ScratchpadToThread: {
1157 // Step 1.1: Get the address for the src element in the scratchpad.
1158 // address = base + index * ElementSizeInChars.
1159 unsigned ElementSizeInChars =
1160 C.getTypeSizeInChars(Private->getType()).getQuantity();
1161 auto *CurrentOffset =
1162 Bld.CreateMul(llvm::ConstantInt::get(CGM.SizeTy, ElementSizeInChars),
1163 ScratchpadIndex);
1164 auto *ScratchPadElemAbsolutePtrVal =
1165 Bld.CreateAdd(SrcBase.getPointer(), CurrentOffset);
1166 ScratchPadElemAbsolutePtrVal =
1167 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1168 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1169 C.getTypeAlignInChars(Private->getType()));
1170 IncrScratchpadSrc = true;
1171
1172 // Step 1.2: Create a temporary to store the element in the destination
1173 // Reduce list.
1174 DestElementPtrAddr =
1175 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
1176 DestElementAddr =
1177 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1178 UpdateDestListPtr = true;
1179 break;
1180 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001181 }
1182
1183 // Regardless of src and dest of copy, we emit the load of src
1184 // element as this is required in all directions
1185 SrcElementAddr = Bld.CreateElementBitCast(
1186 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
1187 llvm::Value *Elem =
1188 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001189 Private->getType(), Private->getExprLoc());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001190
1191 // Now that all active lanes have read the element in the
1192 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataevb2575932018-01-04 20:18:55 +00001193 if (ShuffleInElement)
1194 Elem = createRuntimeShuffleFunction(CGF, Elem, RemoteLaneOffset);
1195
1196 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
1197 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001198
1199 // Store the source element value to the dest element address.
1200 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
1201 Private->getType());
1202
1203 // Step 3.1: Modify reference in dest Reduce list as needed.
1204 // Modifying the reference in Reduce list to point to the newly
1205 // created element. The element is live in the current function
1206 // scope and that of functions it invokes (i.e., reduce_function).
1207 // RemoteReduceData[i] = (void*)&RemoteElem
1208 if (UpdateDestListPtr) {
1209 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
1210 DestElementAddr.getPointer(), CGF.VoidPtrTy),
1211 DestElementPtrAddr, /*Volatile=*/false,
1212 C.VoidPtrTy);
1213 }
1214
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001215 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
1216 // address of the next element in scratchpad memory, unless we're currently
1217 // processing the last one. Memory alignment is also taken care of here.
1218 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
1219 llvm::Value *ScratchpadBasePtr =
1220 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
1221 unsigned ElementSizeInChars =
1222 C.getTypeSizeInChars(Private->getType()).getQuantity();
1223 ScratchpadBasePtr = Bld.CreateAdd(
1224 ScratchpadBasePtr,
1225 Bld.CreateMul(ScratchpadWidth, llvm::ConstantInt::get(
1226 CGM.SizeTy, ElementSizeInChars)));
1227
1228 // Take care of global memory alignment for performance
1229 ScratchpadBasePtr = Bld.CreateSub(ScratchpadBasePtr,
1230 llvm::ConstantInt::get(CGM.SizeTy, 1));
1231 ScratchpadBasePtr = Bld.CreateSDiv(
1232 ScratchpadBasePtr,
1233 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1234 ScratchpadBasePtr = Bld.CreateAdd(ScratchpadBasePtr,
1235 llvm::ConstantInt::get(CGM.SizeTy, 1));
1236 ScratchpadBasePtr = Bld.CreateMul(
1237 ScratchpadBasePtr,
1238 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
1239
1240 if (IncrScratchpadDest)
1241 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1242 else /* IncrScratchpadSrc = true */
1243 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
1244 }
1245
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001246 Idx++;
1247 }
1248}
1249
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001250/// This function emits a helper that loads data from the scratchpad array
1251/// and (optionally) reduces it with the input operand.
1252///
1253/// load_and_reduce(local, scratchpad, index, width, should_reduce)
1254/// reduce_data remote;
1255/// for elem in remote:
1256/// remote.elem = Scratchpad[elem_id][index]
1257/// if (should_reduce)
1258/// local = local @ remote
1259/// else
1260/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001261static llvm::Value *emitReduceScratchpadFunction(
1262 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
1263 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001264 auto &C = CGM.getContext();
1265 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1266
1267 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001268 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1269 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001270 // Base address of the scratchpad array, with each element storing a
1271 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001272 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1273 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001274 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001275 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1276 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001277 // Row width of an element in the scratchpad array, typically
1278 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001279 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1280 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001281 // If should_reduce == 1, then it's load AND reduce,
1282 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
1283 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001284 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1285 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001286
1287 FunctionArgList Args;
1288 Args.push_back(&ReduceListArg);
1289 Args.push_back(&ScratchPadArg);
1290 Args.push_back(&IndexArg);
1291 Args.push_back(&WidthArg);
1292 Args.push_back(&ShouldReduceArg);
1293
1294 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1295 auto *Fn = llvm::Function::Create(
1296 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1297 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001298 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001299 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001300 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001301
1302 auto &Bld = CGF.Builder;
1303
1304 // Get local Reduce list pointer.
1305 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1306 Address ReduceListAddr(
1307 Bld.CreatePointerBitCastOrAddrSpaceCast(
1308 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001309 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001310 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1311 CGF.getPointerAlign());
1312
1313 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1314 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001315 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001316
1317 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001318 llvm::Value *IndexVal = Bld.CreateIntCast(
1319 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
1320 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001321
1322 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001323 llvm::Value *WidthVal = Bld.CreateIntCast(
1324 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
1325 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001326
1327 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
1328 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001329 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001330
1331 // The absolute ptr address to the base addr of the next element to copy.
1332 llvm::Value *CumulativeElemBasePtr =
1333 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1334 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1335
1336 // Create a Remote Reduce list to store the elements read from the
1337 // scratchpad array.
1338 Address RemoteReduceList =
1339 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
1340
1341 // Assemble remote Reduce list from scratchpad array.
1342 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
1343 SrcDataAddr, RemoteReduceList,
1344 {/*RemoteLaneOffset=*/nullptr,
1345 /*ScratchpadIndex=*/IndexVal,
1346 /*ScratchpadWidth=*/WidthVal});
1347
1348 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1349 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1350 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1351
1352 auto CondReduce = Bld.CreateICmpEQ(ShouldReduceVal, Bld.getInt32(1));
1353 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1354
1355 CGF.EmitBlock(ThenBB);
1356 // We should reduce with the local Reduce list.
1357 // reduce_function(LocalReduceList, RemoteReduceList)
1358 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1359 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
1360 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1361 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001362 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
1363 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001364 Bld.CreateBr(MergeBB);
1365
1366 CGF.EmitBlock(ElseBB);
1367 // No reduction; just copy:
1368 // Local Reduce list = Remote Reduce list.
1369 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1370 RemoteReduceList, ReduceListAddr);
1371 Bld.CreateBr(MergeBB);
1372
1373 CGF.EmitBlock(MergeBB);
1374
1375 CGF.FinishFunction();
1376 return Fn;
1377}
1378
1379/// This function emits a helper that stores reduced data from the team
1380/// master to a scratchpad array in global memory.
1381///
1382/// for elem in Reduce List:
1383/// scratchpad[elem_id][index] = elem
1384///
Benjamin Kramer674d5792017-05-26 20:08:24 +00001385static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
1386 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001387 QualType ReductionArrayTy,
1388 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001389
1390 auto &C = CGM.getContext();
1391 auto Int32Ty = C.getIntTypeForBitwidth(32, /* Signed */ true);
1392
1393 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001394 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1395 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001396 // Base address of the scratchpad array, with each element storing a
1397 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001398 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1399 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001400 // A destination index into the scratchpad array, typically the team
1401 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001402 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1403 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001404 // Row width of an element in the scratchpad array, typically
1405 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001406 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
1407 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001408
1409 FunctionArgList Args;
1410 Args.push_back(&ReduceListArg);
1411 Args.push_back(&ScratchPadArg);
1412 Args.push_back(&IndexArg);
1413 Args.push_back(&WidthArg);
1414
1415 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1416 auto *Fn = llvm::Function::Create(
1417 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1418 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001419 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001420 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001421 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001422
1423 auto &Bld = CGF.Builder;
1424
1425 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1426 Address SrcDataAddr(
1427 Bld.CreatePointerBitCastOrAddrSpaceCast(
1428 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001429 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001430 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1431 CGF.getPointerAlign());
1432
1433 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
1434 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001435 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001436
1437 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00001438 llvm::Value *IndexVal = Bld.CreateIntCast(
1439 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
1440 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001441
1442 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
1443 llvm::Value *WidthVal =
1444 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
1445 Int32Ty, SourceLocation()),
1446 CGF.SizeTy, /*isSigned=*/true);
1447
1448 // The absolute ptr address to the base addr of the next element to copy.
1449 llvm::Value *CumulativeElemBasePtr =
1450 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
1451 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
1452
1453 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
1454 SrcDataAddr, DestDataAddr,
1455 {/*RemoteLaneOffset=*/nullptr,
1456 /*ScratchpadIndex=*/IndexVal,
1457 /*ScratchpadWidth=*/WidthVal});
1458
1459 CGF.FinishFunction();
1460 return Fn;
1461}
1462
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001463/// This function emits a helper that gathers Reduce lists from the first
1464/// lane of every active warp to lanes in the first warp.
1465///
1466/// void inter_warp_copy_func(void* reduce_data, num_warps)
1467/// shared smem[warp_size];
1468/// For all data entries D in reduce_data:
1469/// If (I am the first lane in each warp)
1470/// Copy my local D to smem[warp_id]
1471/// sync
1472/// if (I am the first warp)
1473/// Copy smem[thread_id] to my local D
1474/// sync
1475static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
1476 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001477 QualType ReductionArrayTy,
1478 SourceLocation Loc) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001479 auto &C = CGM.getContext();
1480 auto &M = CGM.getModule();
1481
1482 // ReduceList: thread local Reduce list.
1483 // At the stage of the computation when this function is called, partially
1484 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001485 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1486 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001487 // NumWarps: number of warps active in the parallel region. This could
1488 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001489 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00001490 C.getIntTypeForBitwidth(32, /* Signed */ true),
1491 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001492 FunctionArgList Args;
1493 Args.push_back(&ReduceListArg);
1494 Args.push_back(&NumWarpsArg);
1495
1496 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1497 auto *Fn = llvm::Function::Create(
1498 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1499 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001500 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001501 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001502 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001503
1504 auto &Bld = CGF.Builder;
1505
1506 // This array is used as a medium to transfer, one reduce element at a time,
1507 // the data from the first lane of every warp to lanes in the first warp
1508 // in order to perform the final step of a reduction in a parallel region
1509 // (reduction across warps). The array is placed in NVPTX __shared__ memory
1510 // for reduced latency, as well as to have a distinct copy for concurrently
1511 // executing target regions. The array is declared with common linkage so
1512 // as to be shared across compilation units.
1513 const char *TransferMediumName =
1514 "__openmp_nvptx_data_transfer_temporary_storage";
1515 llvm::GlobalVariable *TransferMedium =
1516 M.getGlobalVariable(TransferMediumName);
1517 if (!TransferMedium) {
1518 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
1519 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
1520 TransferMedium = new llvm::GlobalVariable(
1521 M, Ty,
1522 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
1523 llvm::Constant::getNullValue(Ty), TransferMediumName,
1524 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
1525 SharedAddressSpace);
1526 }
1527
1528 // Get the CUDA thread id of the current OpenMP thread on the GPU.
1529 auto *ThreadID = getNVPTXThreadID(CGF);
1530 // nvptx_lane_id = nvptx_id % warpsize
1531 auto *LaneID = getNVPTXLaneID(CGF);
1532 // nvptx_warp_id = nvptx_id / warpsize
1533 auto *WarpID = getNVPTXWarpID(CGF);
1534
1535 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1536 Address LocalReduceList(
1537 Bld.CreatePointerBitCastOrAddrSpaceCast(
1538 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1539 C.VoidPtrTy, SourceLocation()),
1540 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1541 CGF.getPointerAlign());
1542
1543 unsigned Idx = 0;
1544 for (auto &Private : Privates) {
1545 //
1546 // Warp master copies reduce element to transfer medium in __shared__
1547 // memory.
1548 //
1549 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1550 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1551 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1552
1553 // if (lane_id == 0)
1554 auto IsWarpMaster =
1555 Bld.CreateICmpEQ(LaneID, Bld.getInt32(0), "warp_master");
1556 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
1557 CGF.EmitBlock(ThenBB);
1558
1559 // Reduce element = LocalReduceList[i]
1560 Address ElemPtrPtrAddr =
1561 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1562 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
1563 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1564 // elemptr = (type[i]*)(elemptrptr)
1565 Address ElemPtr =
1566 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
1567 ElemPtr = Bld.CreateElementBitCast(
1568 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1569 // elem = *elemptr
1570 llvm::Value *Elem = CGF.EmitLoadOfScalar(
1571 ElemPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1572
1573 // Get pointer to location in transfer medium.
1574 // MediumPtr = &medium[warp_id]
1575 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
1576 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
1577 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
1578 // Casting to actual data type.
1579 // MediumPtr = (type[i]*)MediumPtrAddr;
1580 MediumPtr = Bld.CreateElementBitCast(
1581 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1582
1583 //*MediumPtr = elem
1584 Bld.CreateStore(Elem, MediumPtr);
1585
1586 Bld.CreateBr(MergeBB);
1587
1588 CGF.EmitBlock(ElseBB);
1589 Bld.CreateBr(MergeBB);
1590
1591 CGF.EmitBlock(MergeBB);
1592
1593 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
1594 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
1595 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
1596
1597 auto *NumActiveThreads = Bld.CreateNSWMul(
1598 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
1599 // named_barrier_sync(ParallelBarrierID, num_active_threads)
1600 syncParallelThreads(CGF, NumActiveThreads);
1601
1602 //
1603 // Warp 0 copies reduce element from transfer medium.
1604 //
1605 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
1606 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
1607 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
1608
1609 // Up to 32 threads in warp 0 are active.
1610 auto IsActiveThread =
1611 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
1612 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
1613
1614 CGF.EmitBlock(W0ThenBB);
1615
1616 // SrcMediumPtr = &medium[tid]
1617 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
1618 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
1619 Address SrcMediumPtr(SrcMediumPtrVal,
1620 C.getTypeAlignInChars(Private->getType()));
1621 // SrcMediumVal = *SrcMediumPtr;
1622 SrcMediumPtr = Bld.CreateElementBitCast(
1623 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
1624 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
1625 SrcMediumPtr, /*Volatile=*/false, Private->getType(), SourceLocation());
1626
1627 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
1628 Address TargetElemPtrPtr =
1629 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
1630 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
1631 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
1632 Address TargetElemPtr =
1633 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
1634 TargetElemPtr = Bld.CreateElementBitCast(
1635 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
1636
1637 // *TargetElemPtr = SrcMediumVal;
1638 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
1639 Private->getType());
1640 Bld.CreateBr(W0MergeBB);
1641
1642 CGF.EmitBlock(W0ElseBB);
1643 Bld.CreateBr(W0MergeBB);
1644
1645 CGF.EmitBlock(W0MergeBB);
1646
1647 // While warp 0 copies values from transfer medium, all other warps must
1648 // wait.
1649 syncParallelThreads(CGF, NumActiveThreads);
1650 Idx++;
1651 }
1652
1653 CGF.FinishFunction();
1654 return Fn;
1655}
1656
1657/// Emit a helper that reduces data across two OpenMP threads (lanes)
1658/// in the same warp. It uses shuffle instructions to copy over data from
1659/// a remote lane's stack. The reduction algorithm performed is specified
1660/// by the fourth parameter.
1661///
1662/// Algorithm Versions.
1663/// Full Warp Reduce (argument value 0):
1664/// This algorithm assumes that all 32 lanes are active and gathers
1665/// data from these 32 lanes, producing a single resultant value.
1666/// Contiguous Partial Warp Reduce (argument value 1):
1667/// This algorithm assumes that only a *contiguous* subset of lanes
1668/// are active. This happens for the last warp in a parallel region
1669/// when the user specified num_threads is not an integer multiple of
1670/// 32. This contiguous subset always starts with the zeroth lane.
1671/// Partial Warp Reduce (argument value 2):
1672/// This algorithm gathers data from any number of lanes at any position.
1673/// All reduced values are stored in the lowest possible lane. The set
1674/// of problems every algorithm addresses is a super set of those
1675/// addressable by algorithms with a lower version number. Overhead
1676/// increases as algorithm version increases.
1677///
1678/// Terminology
1679/// Reduce element:
1680/// Reduce element refers to the individual data field with primitive
1681/// data types to be combined and reduced across threads.
1682/// Reduce list:
1683/// Reduce list refers to a collection of local, thread-private
1684/// reduce elements.
1685/// Remote Reduce list:
1686/// Remote Reduce list refers to a collection of remote (relative to
1687/// the current thread) reduce elements.
1688///
1689/// We distinguish between three states of threads that are important to
1690/// the implementation of this function.
1691/// Alive threads:
1692/// Threads in a warp executing the SIMT instruction, as distinguished from
1693/// threads that are inactive due to divergent control flow.
1694/// Active threads:
1695/// The minimal set of threads that has to be alive upon entry to this
1696/// function. The computation is correct iff active threads are alive.
1697/// Some threads are alive but they are not active because they do not
1698/// contribute to the computation in any useful manner. Turning them off
1699/// may introduce control flow overheads without any tangible benefits.
1700/// Effective threads:
1701/// In order to comply with the argument requirements of the shuffle
1702/// function, we must keep all lanes holding data alive. But at most
1703/// half of them perform value aggregation; we refer to this half of
1704/// threads as effective. The other half is simply handing off their
1705/// data.
1706///
1707/// Procedure
1708/// Value shuffle:
1709/// In this step active threads transfer data from higher lane positions
1710/// in the warp to lower lane positions, creating Remote Reduce list.
1711/// Value aggregation:
1712/// In this step, effective threads combine their thread local Reduce list
1713/// with Remote Reduce list and store the result in the thread local
1714/// Reduce list.
1715/// Value copy:
1716/// In this step, we deal with the assumption made by algorithm 2
1717/// (i.e. contiguity assumption). When we have an odd number of lanes
1718/// active, say 2k+1, only k threads will be effective and therefore k
1719/// new values will be produced. However, the Reduce list owned by the
1720/// (2k+1)th thread is ignored in the value aggregation. Therefore
1721/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
1722/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001723static llvm::Value *emitShuffleAndReduceFunction(
1724 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
1725 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001726 auto &C = CGM.getContext();
1727
1728 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001729 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1730 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001731 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001732 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
1733 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001734 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001735 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1736 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001737 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001738 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
1739 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001740 FunctionArgList Args;
1741 Args.push_back(&ReduceListArg);
1742 Args.push_back(&LaneIDArg);
1743 Args.push_back(&RemoteLaneOffsetArg);
1744 Args.push_back(&AlgoVerArg);
1745
1746 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1747 auto *Fn = llvm::Function::Create(
1748 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1749 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001750 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001751 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001752 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001753
1754 auto &Bld = CGF.Builder;
1755
1756 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
1757 Address LocalReduceList(
1758 Bld.CreatePointerBitCastOrAddrSpaceCast(
1759 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
1760 C.VoidPtrTy, SourceLocation()),
1761 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
1762 CGF.getPointerAlign());
1763
1764 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
1765 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
1766 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1767
1768 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
1769 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
1770 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1771
1772 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
1773 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
1774 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
1775
1776 // Create a local thread-private variable to host the Reduce list
1777 // from a remote lane.
1778 Address RemoteReduceList =
1779 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
1780
1781 // This loop iterates through the list of reduce elements and copies,
1782 // element by element, from a remote lane in the warp to RemoteReduceList,
1783 // hosted on the thread's stack.
1784 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
1785 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001786 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
1787 /*ScratchpadIndex=*/nullptr,
1788 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001789
1790 // The actions to be performed on the Remote Reduce list is dependent
1791 // on the algorithm version.
1792 //
1793 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
1794 // LaneId % 2 == 0 && Offset > 0):
1795 // do the reduction value aggregation
1796 //
1797 // The thread local variable Reduce list is mutated in place to host the
1798 // reduced data, which is the aggregated value produced from local and
1799 // remote lanes.
1800 //
1801 // Note that AlgoVer is expected to be a constant integer known at compile
1802 // time.
1803 // When AlgoVer==0, the first conjunction evaluates to true, making
1804 // the entire predicate true during compile time.
1805 // When AlgoVer==1, the second conjunction has only the second part to be
1806 // evaluated during runtime. Other conjunctions evaluates to false
1807 // during compile time.
1808 // When AlgoVer==2, the third conjunction has only the second part to be
1809 // evaluated during runtime. Other conjunctions evaluates to false
1810 // during compile time.
1811 auto CondAlgo0 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(0));
1812
1813 auto Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1814 auto CondAlgo1 = Bld.CreateAnd(
1815 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
1816
1817 auto Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
1818 auto CondAlgo2 = Bld.CreateAnd(
1819 Algo2,
1820 Bld.CreateICmpEQ(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1)),
1821 Bld.getInt16(0)));
1822 CondAlgo2 = Bld.CreateAnd(
1823 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
1824
1825 auto CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
1826 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
1827
1828 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
1829 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
1830 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
1831 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
1832
1833 CGF.EmitBlock(ThenBB);
1834 // reduce_function(LocalReduceList, RemoteReduceList)
1835 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1836 LocalReduceList.getPointer(), CGF.VoidPtrTy);
1837 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1838 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001839 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
1840 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001841 Bld.CreateBr(MergeBB);
1842
1843 CGF.EmitBlock(ElseBB);
1844 Bld.CreateBr(MergeBB);
1845
1846 CGF.EmitBlock(MergeBB);
1847
1848 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
1849 // Reduce list.
1850 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
1851 auto CondCopy = Bld.CreateAnd(
1852 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
1853
1854 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
1855 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
1856 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
1857 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
1858
1859 CGF.EmitBlock(CpyThenBB);
1860 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
1861 RemoteReduceList, LocalReduceList);
1862 Bld.CreateBr(CpyMergeBB);
1863
1864 CGF.EmitBlock(CpyElseBB);
1865 Bld.CreateBr(CpyMergeBB);
1866
1867 CGF.EmitBlock(CpyMergeBB);
1868
1869 CGF.FinishFunction();
1870 return Fn;
1871}
1872
1873///
1874/// Design of OpenMP reductions on the GPU
1875///
1876/// Consider a typical OpenMP program with one or more reduction
1877/// clauses:
1878///
1879/// float foo;
1880/// double bar;
1881/// #pragma omp target teams distribute parallel for \
1882/// reduction(+:foo) reduction(*:bar)
1883/// for (int i = 0; i < N; i++) {
1884/// foo += A[i]; bar *= B[i];
1885/// }
1886///
1887/// where 'foo' and 'bar' are reduced across all OpenMP threads in
1888/// all teams. In our OpenMP implementation on the NVPTX device an
1889/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1890/// within a team are mapped to CUDA threads within a threadblock.
1891/// Our goal is to efficiently aggregate values across all OpenMP
1892/// threads such that:
1893///
1894/// - the compiler and runtime are logically concise, and
1895/// - the reduction is performed efficiently in a hierarchical
1896/// manner as follows: within OpenMP threads in the same warp,
1897/// across warps in a threadblock, and finally across teams on
1898/// the NVPTX device.
1899///
1900/// Introduction to Decoupling
1901///
1902/// We would like to decouple the compiler and the runtime so that the
1903/// latter is ignorant of the reduction variables (number, data types)
1904/// and the reduction operators. This allows a simpler interface
1905/// and implementation while still attaining good performance.
1906///
1907/// Pseudocode for the aforementioned OpenMP program generated by the
1908/// compiler is as follows:
1909///
1910/// 1. Create private copies of reduction variables on each OpenMP
1911/// thread: 'foo_private', 'bar_private'
1912/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1913/// to it and writes the result in 'foo_private' and 'bar_private'
1914/// respectively.
1915/// 3. Call the OpenMP runtime on the GPU to reduce within a team
1916/// and store the result on the team master:
1917///
1918/// __kmpc_nvptx_parallel_reduce_nowait(...,
1919/// reduceData, shuffleReduceFn, interWarpCpyFn)
1920///
1921/// where:
1922/// struct ReduceData {
1923/// double *foo;
1924/// double *bar;
1925/// } reduceData
1926/// reduceData.foo = &foo_private
1927/// reduceData.bar = &bar_private
1928///
1929/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1930/// auxiliary functions generated by the compiler that operate on
1931/// variables of type 'ReduceData'. They aid the runtime perform
1932/// algorithmic steps in a data agnostic manner.
1933///
1934/// 'shuffleReduceFn' is a pointer to a function that reduces data
1935/// of type 'ReduceData' across two OpenMP threads (lanes) in the
1936/// same warp. It takes the following arguments as input:
1937///
1938/// a. variable of type 'ReduceData' on the calling lane,
1939/// b. its lane_id,
1940/// c. an offset relative to the current lane_id to generate a
1941/// remote_lane_id. The remote lane contains the second
1942/// variable of type 'ReduceData' that is to be reduced.
1943/// d. an algorithm version parameter determining which reduction
1944/// algorithm to use.
1945///
1946/// 'shuffleReduceFn' retrieves data from the remote lane using
1947/// efficient GPU shuffle intrinsics and reduces, using the
1948/// algorithm specified by the 4th parameter, the two operands
1949/// element-wise. The result is written to the first operand.
1950///
1951/// Different reduction algorithms are implemented in different
1952/// runtime functions, all calling 'shuffleReduceFn' to perform
1953/// the essential reduction step. Therefore, based on the 4th
1954/// parameter, this function behaves slightly differently to
1955/// cooperate with the runtime to ensure correctness under
1956/// different circumstances.
1957///
1958/// 'InterWarpCpyFn' is a pointer to a function that transfers
1959/// reduced variables across warps. It tunnels, through CUDA
1960/// shared memory, the thread-private data of type 'ReduceData'
1961/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001962/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1963/// The last team writes the global reduced value to memory.
1964///
1965/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1966/// reduceData, shuffleReduceFn, interWarpCpyFn,
1967/// scratchpadCopyFn, loadAndReduceFn)
1968///
1969/// 'scratchpadCopyFn' is a helper that stores reduced
1970/// data from the team master to a scratchpad array in
1971/// global memory.
1972///
1973/// 'loadAndReduceFn' is a helper that loads data from
1974/// the scratchpad array and reduces it with the input
1975/// operand.
1976///
1977/// These compiler generated functions hide address
1978/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001979/// 5. if ret == 1:
1980/// The team master of the last team stores the reduced
1981/// result to the globals in memory.
1982/// foo += reduceData.foo; bar *= reduceData.bar
1983///
1984///
1985/// Warp Reduction Algorithms
1986///
1987/// On the warp level, we have three algorithms implemented in the
1988/// OpenMP runtime depending on the number of active lanes:
1989///
1990/// Full Warp Reduction
1991///
1992/// The reduce algorithm within a warp where all lanes are active
1993/// is implemented in the runtime as follows:
1994///
1995/// full_warp_reduce(void *reduce_data,
1996/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1997/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1998/// ShuffleReduceFn(reduce_data, 0, offset, 0);
1999/// }
2000///
2001/// The algorithm completes in log(2, WARPSIZE) steps.
2002///
2003/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
2004/// not used therefore we save instructions by not retrieving lane_id
2005/// from the corresponding special registers. The 4th parameter, which
2006/// represents the version of the algorithm being used, is set to 0 to
2007/// signify full warp reduction.
2008///
2009/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2010///
2011/// #reduce_elem refers to an element in the local lane's data structure
2012/// #remote_elem is retrieved from a remote lane
2013/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2014/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
2015///
2016/// Contiguous Partial Warp Reduction
2017///
2018/// This reduce algorithm is used within a warp where only the first
2019/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
2020/// number of OpenMP threads in a parallel region is not a multiple of
2021/// WARPSIZE. The algorithm is implemented in the runtime as follows:
2022///
2023/// void
2024/// contiguous_partial_reduce(void *reduce_data,
2025/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
2026/// int size, int lane_id) {
2027/// int curr_size;
2028/// int offset;
2029/// curr_size = size;
2030/// mask = curr_size/2;
2031/// while (offset>0) {
2032/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
2033/// curr_size = (curr_size+1)/2;
2034/// offset = curr_size/2;
2035/// }
2036/// }
2037///
2038/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2039///
2040/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2041/// if (lane_id < offset)
2042/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2043/// else
2044/// reduce_elem = remote_elem
2045///
2046/// This algorithm assumes that the data to be reduced are located in a
2047/// contiguous subset of lanes starting from the first. When there is
2048/// an odd number of active lanes, the data in the last lane is not
2049/// aggregated with any other lane's dat but is instead copied over.
2050///
2051/// Dispersed Partial Warp Reduction
2052///
2053/// This algorithm is used within a warp when any discontiguous subset of
2054/// lanes are active. It is used to implement the reduction operation
2055/// across lanes in an OpenMP simd region or in a nested parallel region.
2056///
2057/// void
2058/// dispersed_partial_reduce(void *reduce_data,
2059/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
2060/// int size, remote_id;
2061/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
2062/// do {
2063/// remote_id = next_active_lane_id_right_after_me();
2064/// # the above function returns 0 of no active lane
2065/// # is present right after the current lane.
2066/// size = number_of_active_lanes_in_this_warp();
2067/// logical_lane_id /= 2;
2068/// ShuffleReduceFn(reduce_data, logical_lane_id,
2069/// remote_id-1-threadIdx.x, 2);
2070/// } while (logical_lane_id % 2 == 0 && size > 1);
2071/// }
2072///
2073/// There is no assumption made about the initial state of the reduction.
2074/// Any number of lanes (>=1) could be active at any position. The reduction
2075/// result is returned in the first active lane.
2076///
2077/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
2078///
2079/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
2080/// if (lane_id % 2 == 0 && offset > 0)
2081/// reduce_elem = reduce_elem REDUCE_OP remote_elem
2082/// else
2083/// reduce_elem = remote_elem
2084///
2085///
2086/// Intra-Team Reduction
2087///
2088/// This function, as implemented in the runtime call
2089/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
2090/// threads in a team. It first reduces within a warp using the
2091/// aforementioned algorithms. We then proceed to gather all such
2092/// reduced values at the first warp.
2093///
2094/// The runtime makes use of the function 'InterWarpCpyFn', which copies
2095/// data from each of the "warp master" (zeroth lane of each warp, where
2096/// warp-reduced data is held) to the zeroth warp. This step reduces (in
2097/// a mathematical sense) the problem of reduction across warp masters in
2098/// a block to the problem of warp reduction.
2099///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002100///
2101/// Inter-Team Reduction
2102///
2103/// Once a team has reduced its data to a single value, it is stored in
2104/// a global scratchpad array. Since each team has a distinct slot, this
2105/// can be done without locking.
2106///
2107/// The last team to write to the scratchpad array proceeds to reduce the
2108/// scratchpad array. One or more workers in the last team use the helper
2109/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
2110/// the k'th worker reduces every k'th element.
2111///
2112/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
2113/// reduce across workers and compute a globally reduced value.
2114///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002115void CGOpenMPRuntimeNVPTX::emitReduction(
2116 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
2117 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
2118 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
2119 if (!CGF.HaveInsertPoint())
2120 return;
2121
2122 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002123 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
2124 // FIXME: Add support for simd reduction.
2125 assert((TeamsReduction || ParallelReduction) &&
2126 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002127
2128 auto &C = CGM.getContext();
2129
2130 // 1. Build a list of reduction variables.
2131 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2132 auto Size = RHSExprs.size();
2133 for (auto *E : Privates) {
2134 if (E->getType()->isVariablyModifiedType())
2135 // Reserve place for array size.
2136 ++Size;
2137 }
2138 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
2139 QualType ReductionArrayTy =
2140 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2141 /*IndexTypeQuals=*/0);
2142 Address ReductionList =
2143 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2144 auto IPriv = Privates.begin();
2145 unsigned Idx = 0;
2146 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
2147 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2148 CGF.getPointerSize());
2149 CGF.Builder.CreateStore(
2150 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2151 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
2152 Elem);
2153 if ((*IPriv)->getType()->isVariablyModifiedType()) {
2154 // Store array size.
2155 ++Idx;
2156 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
2157 CGF.getPointerSize());
2158 llvm::Value *Size = CGF.Builder.CreateIntCast(
2159 CGF.getVLASize(
2160 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00002161 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002162 CGF.SizeTy, /*isSigned=*/false);
2163 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2164 Elem);
2165 }
2166 }
2167
2168 // 2. Emit reduce_func().
2169 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002170 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
2171 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002172
2173 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
2174 // RedList, shuffle_reduce_func, interwarp_copy_func);
2175 auto *ThreadId = getThreadID(CGF, Loc);
2176 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
2177 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2178 ReductionList.getPointer(), CGF.VoidPtrTy);
2179
2180 auto *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002181 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002182 auto *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002183 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002184
2185 llvm::Value *Res = nullptr;
2186 if (ParallelReduction) {
2187 llvm::Value *Args[] = {ThreadId,
2188 CGF.Builder.getInt32(RHSExprs.size()),
2189 ReductionArrayTySize,
2190 RL,
2191 ShuffleAndReduceFn,
2192 InterWarpCopyFn};
2193
2194 Res = CGF.EmitRuntimeCall(
2195 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
2196 Args);
2197 }
2198
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002199 if (TeamsReduction) {
2200 auto *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002201 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002202 auto *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002203 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002204
2205 llvm::Value *Args[] = {ThreadId,
2206 CGF.Builder.getInt32(RHSExprs.size()),
2207 ReductionArrayTySize,
2208 RL,
2209 ShuffleAndReduceFn,
2210 InterWarpCopyFn,
2211 ScratchPadCopyFn,
2212 LoadAndReduceFn};
2213 Res = CGF.EmitRuntimeCall(
2214 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
2215 Args);
2216 }
2217
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002218 // 5. Build switch(res)
2219 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
2220 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
2221
2222 // 6. Build case 1: where we have reduced values in the master
2223 // thread in each team.
2224 // __kmpc_end_reduce{_nowait}(<gtid>);
2225 // break;
2226 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
2227 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
2228 CGF.EmitBlock(Case1BB);
2229
2230 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
2231 llvm::Value *EndArgs[] = {ThreadId};
2232 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps,
2233 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
2234 auto IPriv = Privates.begin();
2235 auto ILHS = LHSExprs.begin();
2236 auto IRHS = RHSExprs.begin();
2237 for (auto *E : ReductionOps) {
2238 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
2239 cast<DeclRefExpr>(*IRHS));
2240 ++IPriv;
2241 ++ILHS;
2242 ++IRHS;
2243 }
2244 };
2245 RegionCodeGenTy RCG(CodeGen);
2246 NVPTXActionTy Action(
2247 nullptr, llvm::None,
2248 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
2249 EndArgs);
2250 RCG.setAction(Action);
2251 RCG(CGF);
2252 CGF.EmitBranch(DefaultBB);
2253 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
2254}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002255
2256const VarDecl *
2257CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
2258 const VarDecl *NativeParam) const {
2259 if (!NativeParam->getType()->isReferenceType())
2260 return NativeParam;
2261 QualType ArgType = NativeParam->getType();
2262 QualifierCollector QC;
2263 const Type *NonQualTy = QC.strip(ArgType);
2264 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2265 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
2266 if (Attr->getCaptureKind() == OMPC_map) {
2267 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
2268 LangAS::opencl_global);
2269 }
2270 }
2271 ArgType = CGM.getContext().getPointerType(PointeeTy);
2272 QC.addRestrict();
2273 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00002274 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002275 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00002276 if (isa<ImplicitParamDecl>(NativeParam)) {
2277 return ImplicitParamDecl::Create(
2278 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
2279 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
2280 }
2281 return ParmVarDecl::Create(
2282 CGM.getContext(),
2283 const_cast<DeclContext *>(NativeParam->getDeclContext()),
2284 NativeParam->getLocStart(), NativeParam->getLocation(),
2285 NativeParam->getIdentifier(), ArgType,
2286 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002287}
2288
2289Address
2290CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
2291 const VarDecl *NativeParam,
2292 const VarDecl *TargetParam) const {
2293 assert(NativeParam != TargetParam &&
2294 NativeParam->getType()->isReferenceType() &&
2295 "Native arg must not be the same as target arg.");
2296 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
2297 QualType NativeParamType = NativeParam->getType();
2298 QualifierCollector QC;
2299 const Type *NonQualTy = QC.strip(NativeParamType);
2300 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
2301 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00002302 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002303 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002304 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002305 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002306 // First cast to generic.
2307 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2308 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2309 /*AddrSpace=*/0));
2310 // Cast from generic to native address space.
2311 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2312 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
2313 NativePointeeAddrSpace));
2314 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
2315 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00002316 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002317 return NativeParamAddr;
2318}
2319
2320void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00002321 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002322 ArrayRef<llvm::Value *> Args) const {
2323 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002324 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002325 auto *FnType =
2326 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
2327 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00002328 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
2329 TargetArgs.append(std::next(Args.begin(), I), Args.end());
2330 break;
2331 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002332 llvm::Type *TargetType = FnType->getParamType(I);
2333 llvm::Value *NativeArg = Args[I];
2334 if (!TargetType->isPointerTy()) {
2335 TargetArgs.emplace_back(NativeArg);
2336 continue;
2337 }
2338 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2339 NativeArg, NativeArg->getType()->getPointerElementType()->getPointerTo(
2340 /*AddrSpace=*/0));
2341 TargetArgs.emplace_back(
2342 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
2343 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00002344 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002345}