blob: 14845b586202dfe6ba5015db44cc2c257841dddd [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
20#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035 /// Call to void __kmpc_spmd_kernel_deinit();
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000036 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait(kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
63 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000064 /// Call to __kmpc_nvptx_simd_reduce_nowait(kmp_int32
Alexey Bataevfac26cf2018-05-02 20:03:27 +000065 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
66 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
67 /// lane_offset, int16_t shortCircuit),
68 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
69 OMPRTL_NVPTX__kmpc_simd_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Call to __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +000071 /// int32_t num_vars, size_t reduce_size, void *reduce_data,
72 /// void (*kmp_ShuffleReductFctPtr)(void *rhs, int16_t lane_id, int16_t
73 /// lane_offset, int16_t shortCircuit),
74 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
75 /// void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
76 /// int32_t index, int32_t width),
77 /// void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad, int32_t
78 /// index, int32_t width, int32_t reduce))
79 OMPRTL_NVPTX__kmpc_teams_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000084 /// Call to void __kmpc_data_sharing_init_stack_spmd();
85 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000086 /// Call to void* __kmpc_data_sharing_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000087 /// int16_t UseSharedMemory);
88 OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000089 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000090 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000091 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000092 /// size_t n_args);
93 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000095 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000096 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000097 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000098 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
99 /// global_tid);
100 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +0000101 /// Call to int8_t __kmpc_is_spmd_exec_mode();
102 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000103};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104
105/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
106class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000107 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000111 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000112 llvm::BasicBlock *ContBlock = nullptr;
113
114public:
115 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
116 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
117 bool Conditional = false)
118 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
119 ExitArgs(ExitArgs), Conditional(Conditional) {}
120 void Enter(CodeGenFunction &CGF) override {
121 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
122 if (Conditional) {
123 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
124 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
125 ContBlock = CGF.createBasicBlock("omp_if.end");
126 // Generate the branch (If-stmt)
127 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
128 CGF.EmitBlock(ThenBlock);
129 }
130 }
131 void Done(CodeGenFunction &CGF) {
132 // Emit the rest of blocks/branches
133 CGF.EmitBranch(ContBlock);
134 CGF.EmitBlock(ContBlock, true);
135 }
136 void Exit(CodeGenFunction &CGF) override {
137 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
138 }
139};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000140
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000141/// A class to track the execution mode when codegening directives within
142/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
143/// to the target region and used by containing directives such as 'parallel'
144/// to emit optimized code.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000145class ExecutionModeRAII {
146private:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000147 CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode;
148 CGOpenMPRuntimeNVPTX::ExecutionMode &Mode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000149
150public:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000151 ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, bool IsSPMD)
152 : Mode(Mode) {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000153 SavedMode = Mode;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000154 Mode = IsSPMD ? CGOpenMPRuntimeNVPTX::EM_SPMD
155 : CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000156 }
157 ~ExecutionModeRAII() { Mode = SavedMode; }
158};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000159
160/// GPU Configuration: This information can be derived from cuda registers,
161/// however, providing compile time constants helps generate more efficient
162/// code. For all practical purposes this is fine because the configuration
163/// is the same for all known NVPTX architectures.
164enum MachineConfiguration : unsigned {
165 WarpSize = 32,
166 /// Number of bits required to represent a lane identifier, which is
167 /// computed as log_2(WarpSize).
168 LaneIDBits = 5,
169 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000170
171 /// Global memory alignment for performance.
172 GlobalMemoryAlignment = 256,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000173};
174
175enum NamedBarrier : unsigned {
176 /// Synchronize on this barrier #ID using a named barrier primitive.
177 /// Only the subset of active threads in a parallel region arrive at the
178 /// barrier.
179 NB_Parallel = 1,
180};
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000181
182/// Get the list of variables that can escape their declaration context.
183class CheckVarsEscapingDeclContext final
184 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
185 CodeGenFunction &CGF;
186 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000187 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000188 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000189 RecordDecl *GlobalizedRD = nullptr;
190 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000191 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000192 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000193
194 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000195 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000196 if (!isa<VarDecl>(VD) ||
197 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000198 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000199 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000200 // Variables captured by value must be globalized.
201 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000202 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000203 // Check if need to capture the variable that was already captured by
204 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000205 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000206 if (!FD->hasAttrs())
207 return;
208 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
209 if (!Attr)
210 return;
211 if (!isOpenMPPrivate(
212 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
213 Attr->getCaptureKind() == OMPC_map)
214 return;
215 }
216 if (!FD->getType()->isReferenceType()) {
217 assert(!VD->getType()->isVariablyModifiedType() &&
218 "Parameter captured by value with variably modified type");
219 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000220 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000221 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000222 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000223 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000224 }
225 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000226 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000227 VD->getType()->isReferenceType())
228 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000229 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000230 if (VD->getType()->isVariablyModifiedType())
231 EscapedVariableLengthDecls.insert(VD);
232 else
233 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000234 }
235
236 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000237 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000238 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000239 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
240 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
241 const bool SavedAllEscaped = AllEscaped;
242 AllEscaped = VD->getType()->isLValueReferenceType();
243 Visit(VarD->getInit());
244 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000245 }
246 }
247 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000248 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
249 ArrayRef<OMPClause *> Clauses,
250 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000251 if (!S)
252 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000253 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000254 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
255 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000256 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
257 if (IsCombinedParallelRegion) {
258 // Check if the variable is privatized in the combined construct and
259 // those private copies must be shared in the inner parallel
260 // directive.
261 IsForCombinedParallelRegion = false;
262 for (const OMPClause *C : Clauses) {
263 if (!isOpenMPPrivate(C->getClauseKind()) ||
264 C->getClauseKind() == OMPC_reduction ||
265 C->getClauseKind() == OMPC_linear ||
266 C->getClauseKind() == OMPC_private)
267 continue;
268 ArrayRef<const Expr *> Vars;
269 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
270 Vars = PC->getVarRefs();
271 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
272 Vars = PC->getVarRefs();
273 else
274 llvm_unreachable("Unexpected clause.");
275 for (const auto *E : Vars) {
276 const Decl *D =
277 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
278 if (D == VD->getCanonicalDecl()) {
279 IsForCombinedParallelRegion = true;
280 break;
281 }
282 }
283 if (IsForCombinedParallelRegion)
284 break;
285 }
286 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000287 markAsEscaped(VD);
288 if (isa<OMPCapturedExprDecl>(VD))
289 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000290 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000291 }
292 }
293 }
294
295 typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
296 static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
297 return P1.first > P2.first;
298 }
299
300 void buildRecordForGlobalizedVars() {
301 assert(!GlobalizedRD &&
302 "Record for globalized variables is built already.");
303 if (EscapedDecls.empty())
304 return;
305 ASTContext &C = CGF.getContext();
306 SmallVector<VarsDataTy, 4> GlobalizedVars;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000307 for (const ValueDecl *D : EscapedDecls)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000308 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
309 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
310 stable_sort_comparator);
311 // Build struct _globalized_locals_ty {
312 // /* globalized vars */
313 // };
314 GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
315 GlobalizedRD->startDefinition();
316 for (const auto &Pair : GlobalizedVars) {
317 const ValueDecl *VD = Pair.second;
318 QualType Type = VD->getType();
319 if (Type->isLValueReferenceType())
320 Type = C.getPointerType(Type.getNonReferenceType());
321 else
322 Type = Type.getNonReferenceType();
323 SourceLocation Loc = VD->getLocation();
324 auto *Field = FieldDecl::Create(
325 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
326 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
327 /*BW=*/nullptr, /*Mutable=*/false,
328 /*InitStyle=*/ICIS_NoInit);
329 Field->setAccess(AS_public);
330 GlobalizedRD->addDecl(Field);
331 if (VD->hasAttrs()) {
332 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
333 E(VD->getAttrs().end());
334 I != E; ++I)
335 Field->addAttr(*I);
336 }
337 MappedDeclsFields.try_emplace(VD, Field);
338 }
339 GlobalizedRD->completeDefinition();
340 }
341
342public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000343 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000344 virtual ~CheckVarsEscapingDeclContext() = default;
345 void VisitDeclStmt(const DeclStmt *S) {
346 if (!S)
347 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000348 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000349 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
350 VisitValueDecl(VD);
351 }
352 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
353 if (!D)
354 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000355 if (!D->hasAssociatedStmt())
356 return;
357 if (const auto *S =
358 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
359 // Do not analyze directives that do not actually require capturing,
360 // like `omp for` or `omp simd` directives.
361 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
362 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
363 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
364 VisitStmt(S->getCapturedStmt());
365 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000366 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000367 VisitOpenMPCapturedStmt(
368 S, D->clauses(),
369 CaptureRegions.back() == OMPD_parallel &&
370 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000371 }
372 }
373 void VisitCapturedStmt(const CapturedStmt *S) {
374 if (!S)
375 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000376 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000377 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
378 const ValueDecl *VD = C.getCapturedVar();
379 markAsEscaped(VD);
380 if (isa<OMPCapturedExprDecl>(VD))
381 VisitValueDecl(VD);
382 }
383 }
384 }
385 void VisitLambdaExpr(const LambdaExpr *E) {
386 if (!E)
387 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000388 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000389 if (C.capturesVariable()) {
390 if (C.getCaptureKind() == LCK_ByRef) {
391 const ValueDecl *VD = C.getCapturedVar();
392 markAsEscaped(VD);
393 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
394 VisitValueDecl(VD);
395 }
396 }
397 }
398 }
399 void VisitBlockExpr(const BlockExpr *E) {
400 if (!E)
401 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000402 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000403 if (C.isByRef()) {
404 const VarDecl *VD = C.getVariable();
405 markAsEscaped(VD);
406 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
407 VisitValueDecl(VD);
408 }
409 }
410 }
411 void VisitCallExpr(const CallExpr *E) {
412 if (!E)
413 return;
414 for (const Expr *Arg : E->arguments()) {
415 if (!Arg)
416 continue;
417 if (Arg->isLValue()) {
418 const bool SavedAllEscaped = AllEscaped;
419 AllEscaped = true;
420 Visit(Arg);
421 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000422 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000423 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000424 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000425 }
426 Visit(E->getCallee());
427 }
428 void VisitDeclRefExpr(const DeclRefExpr *E) {
429 if (!E)
430 return;
431 const ValueDecl *VD = E->getDecl();
432 if (AllEscaped)
433 markAsEscaped(VD);
434 if (isa<OMPCapturedExprDecl>(VD))
435 VisitValueDecl(VD);
436 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
437 if (VarD->isInitCapture())
438 VisitValueDecl(VD);
439 }
440 void VisitUnaryOperator(const UnaryOperator *E) {
441 if (!E)
442 return;
443 if (E->getOpcode() == UO_AddrOf) {
444 const bool SavedAllEscaped = AllEscaped;
445 AllEscaped = true;
446 Visit(E->getSubExpr());
447 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000448 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000449 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000450 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000451 }
452 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
453 if (!E)
454 return;
455 if (E->getCastKind() == CK_ArrayToPointerDecay) {
456 const bool SavedAllEscaped = AllEscaped;
457 AllEscaped = true;
458 Visit(E->getSubExpr());
459 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000460 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000461 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000462 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463 }
464 void VisitExpr(const Expr *E) {
465 if (!E)
466 return;
467 bool SavedAllEscaped = AllEscaped;
468 if (!E->isLValue())
469 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000470 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 if (Child)
472 Visit(Child);
473 AllEscaped = SavedAllEscaped;
474 }
475 void VisitStmt(const Stmt *S) {
476 if (!S)
477 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000478 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000479 if (Child)
480 Visit(Child);
481 }
482
Alexey Bataevc99042b2018-03-15 18:10:54 +0000483 /// Returns the record that handles all the escaped local variables and used
484 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000485 const RecordDecl *getGlobalizedRecord() {
486 if (!GlobalizedRD)
487 buildRecordForGlobalizedVars();
488 return GlobalizedRD;
489 }
490
Alexey Bataevc99042b2018-03-15 18:10:54 +0000491 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000492 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
493 assert(GlobalizedRD &&
494 "Record for globalized variables must be generated already.");
495 auto I = MappedDeclsFields.find(VD);
496 if (I == MappedDeclsFields.end())
497 return nullptr;
498 return I->getSecond();
499 }
500
Alexey Bataevc99042b2018-03-15 18:10:54 +0000501 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000502 ArrayRef<const ValueDecl *> getEscapedDecls() const {
503 return EscapedDecls.getArrayRef();
504 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000505
506 /// Checks if the escaped local variable is actually a parameter passed by
507 /// value.
508 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
509 return EscapedParameters;
510 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000511
512 /// Returns the list of the escaped variables with the variably modified
513 /// types.
514 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
515 return EscapedVariableLengthDecls.getArrayRef();
516 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000517};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000518} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000519
520/// Get the GPU warp size.
521static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000522 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000523 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000524 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000525 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000526}
527
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000528/// Get the id of the current thread on the GPU.
529static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000530 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000531 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000532 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000533 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000534}
535
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000536/// Get the id of the warp in the block.
537/// We assume that the warp size is 32, which is always the case
538/// on the NVPTX device, to generate more efficient code.
539static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
540 CGBuilderTy &Bld = CGF.Builder;
541 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
542}
543
544/// Get the id of the current lane in the Warp.
545/// We assume that the warp size is 32, which is always the case
546/// on the NVPTX device, to generate more efficient code.
547static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
548 CGBuilderTy &Bld = CGF.Builder;
549 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
550 "nvptx_lane_id");
551}
552
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000553/// Get the maximum number of threads in a block of the GPU.
554static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000555 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000556 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000557 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000558 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000559}
560
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000561/// Get barrier to synchronize all threads in a block.
562static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000563 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000564 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000565}
566
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000567/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
568/// a CTA.
569static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
570 llvm::Value *NumThreads) {
571 CGBuilderTy &Bld = CGF.Builder;
572 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000573 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
574 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
575 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000576}
577
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000578/// Synchronize all GPU threads in a block.
579static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000580
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000581/// Synchronize worker threads in a parallel region.
582static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
583 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
584}
585
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000586/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000587/// For the 'generic' execution mode, the runtime encodes thread_limit in
588/// the launch parameters, always starting thread_limit+warpSize threads per
589/// CTA. The threads in the last warp are reserved for master execution.
590/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
591static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000592 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000593 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000594 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000595 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000596 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
597 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000598}
599
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000600/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000601/// The master thread id is the first thread (lane) of the last warp in the
602/// GPU block. Warp size is assumed to be some power of 2.
603/// Thread id is 0 indexed.
604/// E.g: If NumThreads is 33, master id is 32.
605/// If NumThreads is 64, master id is 32.
606/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000607static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000608 CGBuilderTy &Bld = CGF.Builder;
609 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
610
611 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000612 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000613
Alexey Bataeve290ec02018-04-06 16:03:36 +0000614 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000615 Bld.CreateNot(Mask), "master_tid");
616}
617
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000619 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000620 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
621 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000622 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000623}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000624
625void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
626 CodeGenModule &CGM) {
627 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000628
629 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000630 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000631 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000632 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000633 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000634}
635
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000636CGOpenMPRuntimeNVPTX::ExecutionMode
637CGOpenMPRuntimeNVPTX::getExecutionMode() const {
638 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000639}
640
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000641static CGOpenMPRuntimeNVPTX::DataSharingMode
642getDataSharingMode(CodeGenModule &CGM) {
643 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
644 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000645}
646
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000647/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
648/// iff there is only one.
649static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000650 if (const auto *C = dyn_cast<CompoundStmt>(Body))
651 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000652 return C->body_front();
653 return Body;
654}
655
656/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000657/// false condition. Also, check if the number of threads is strictly specified
658/// and run those directives in non-SPMD mode.
659static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
660 const OMPExecutableDirective &D) {
661 if (D.hasClausesOfKind<OMPNumThreadsClause>())
662 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000663 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
664 OpenMPDirectiveKind NameModifier = C->getNameModifier();
665 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
666 continue;
667 const Expr *Cond = C->getCondition();
668 bool Result;
669 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
670 return true;
671 }
672 return false;
673}
674
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000675/// Checks if the directive is the distribute clause with the lastprivate
676/// clauses. This construct does not support SPMD execution mode.
677static bool hasDistributeWithLastprivateClauses(const OMPExecutableDirective &D) {
678 return isOpenMPDistributeDirective(D.getDirectiveKind()) &&
679 D.hasClausesOfKind<OMPLastprivateClause>();
680}
681
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000682/// Check for inner (nested) SPMD construct, if any
683static bool hasNestedSPMDDirective(ASTContext &Ctx,
684 const OMPExecutableDirective &D) {
685 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000686 const auto *Body =
687 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000688 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000689
690 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
691 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000692 switch (D.getDirectiveKind()) {
693 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000694 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000695 !hasParallelIfNumThreadsClause(Ctx, *NestedDir) &&
696 !hasDistributeWithLastprivateClauses(*NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000697 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000698 if (DKind == OMPD_teams) {
699 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
700 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000701 if (!Body)
702 return false;
703 ChildStmt = getSingleCompoundChild(Body);
704 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
705 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000706 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000707 !hasParallelIfNumThreadsClause(Ctx, *NND) &&
708 !hasDistributeWithLastprivateClauses(*NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000709 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000710 }
711 }
712 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000713 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000714 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000715 !hasParallelIfNumThreadsClause(Ctx, *NestedDir) &&
716 !hasDistributeWithLastprivateClauses(*NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000717 case OMPD_target_simd:
718 case OMPD_target_parallel:
719 case OMPD_target_parallel_for:
720 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000721 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000722 case OMPD_target_teams_distribute_simd:
723 case OMPD_target_teams_distribute_parallel_for:
724 case OMPD_target_teams_distribute_parallel_for_simd:
725 case OMPD_parallel:
726 case OMPD_for:
727 case OMPD_parallel_for:
728 case OMPD_parallel_sections:
729 case OMPD_for_simd:
730 case OMPD_parallel_for_simd:
731 case OMPD_cancel:
732 case OMPD_cancellation_point:
733 case OMPD_ordered:
734 case OMPD_threadprivate:
735 case OMPD_task:
736 case OMPD_simd:
737 case OMPD_sections:
738 case OMPD_section:
739 case OMPD_single:
740 case OMPD_master:
741 case OMPD_critical:
742 case OMPD_taskyield:
743 case OMPD_barrier:
744 case OMPD_taskwait:
745 case OMPD_taskgroup:
746 case OMPD_atomic:
747 case OMPD_flush:
748 case OMPD_teams:
749 case OMPD_target_data:
750 case OMPD_target_exit_data:
751 case OMPD_target_enter_data:
752 case OMPD_distribute:
753 case OMPD_distribute_simd:
754 case OMPD_distribute_parallel_for:
755 case OMPD_distribute_parallel_for_simd:
756 case OMPD_teams_distribute:
757 case OMPD_teams_distribute_simd:
758 case OMPD_teams_distribute_parallel_for:
759 case OMPD_teams_distribute_parallel_for_simd:
760 case OMPD_target_update:
761 case OMPD_declare_simd:
762 case OMPD_declare_target:
763 case OMPD_end_declare_target:
764 case OMPD_declare_reduction:
765 case OMPD_taskloop:
766 case OMPD_taskloop_simd:
767 case OMPD_unknown:
768 llvm_unreachable("Unexpected directive.");
769 }
770 }
771
772 return false;
773}
774
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000775static bool supportsSPMDExecutionMode(ASTContext &Ctx,
776 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000777 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
778 switch (DirectiveKind) {
779 case OMPD_target:
780 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000781 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000782 case OMPD_target_parallel:
783 case OMPD_target_parallel_for:
784 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000785 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000786 case OMPD_target_teams_distribute_parallel_for:
787 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000788 // Distribute with lastprivates requires non-SPMD execution mode.
789 return !hasParallelIfNumThreadsClause(Ctx, D) &&
790 !hasDistributeWithLastprivateClauses(D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000791 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000792 case OMPD_target_teams_distribute:
793 case OMPD_target_teams_distribute_simd:
794 return false;
795 case OMPD_parallel:
796 case OMPD_for:
797 case OMPD_parallel_for:
798 case OMPD_parallel_sections:
799 case OMPD_for_simd:
800 case OMPD_parallel_for_simd:
801 case OMPD_cancel:
802 case OMPD_cancellation_point:
803 case OMPD_ordered:
804 case OMPD_threadprivate:
805 case OMPD_task:
806 case OMPD_simd:
807 case OMPD_sections:
808 case OMPD_section:
809 case OMPD_single:
810 case OMPD_master:
811 case OMPD_critical:
812 case OMPD_taskyield:
813 case OMPD_barrier:
814 case OMPD_taskwait:
815 case OMPD_taskgroup:
816 case OMPD_atomic:
817 case OMPD_flush:
818 case OMPD_teams:
819 case OMPD_target_data:
820 case OMPD_target_exit_data:
821 case OMPD_target_enter_data:
822 case OMPD_distribute:
823 case OMPD_distribute_simd:
824 case OMPD_distribute_parallel_for:
825 case OMPD_distribute_parallel_for_simd:
826 case OMPD_teams_distribute:
827 case OMPD_teams_distribute_simd:
828 case OMPD_teams_distribute_parallel_for:
829 case OMPD_teams_distribute_parallel_for_simd:
830 case OMPD_target_update:
831 case OMPD_declare_simd:
832 case OMPD_declare_target:
833 case OMPD_end_declare_target:
834 case OMPD_declare_reduction:
835 case OMPD_taskloop:
836 case OMPD_taskloop_simd:
837 case OMPD_unknown:
838 break;
839 }
840 llvm_unreachable(
841 "Unknown programming model for OpenMP directive on NVPTX target.");
842}
843
844/// Check if the directive is loops based and has schedule clause at all or has
845/// static scheduling.
846static bool hasStaticScheduling(const OMPExecutableDirective &D) {
847 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
848 isOpenMPLoopDirective(D.getDirectiveKind()) &&
849 "Expected loop-based directive.");
850 return !D.hasClausesOfKind<OMPOrderedClause>() &&
851 (!D.hasClausesOfKind<OMPScheduleClause>() ||
852 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
853 [](const OMPScheduleClause *C) {
854 return C->getScheduleKind() == OMPC_SCHEDULE_static;
855 }));
856}
857
858/// Check for inner (nested) lightweight runtime construct, if any
859static bool hasNestedLightweightDirective(ASTContext &Ctx,
860 const OMPExecutableDirective &D) {
861 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
862 const auto *CS = D.getInnermostCapturedStmt();
863 const auto *Body =
864 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
865 const Stmt *ChildStmt = getSingleCompoundChild(Body);
866
867 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
868 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
869 switch (D.getDirectiveKind()) {
870 case OMPD_target:
871 if (isOpenMPParallelDirective(DKind) &&
872 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
873 hasStaticScheduling(*NestedDir))
874 return true;
875 if (DKind == OMPD_parallel) {
876 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
877 /*IgnoreCaptured=*/true);
878 if (!Body)
879 return false;
880 ChildStmt = getSingleCompoundChild(Body);
881 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
882 DKind = NND->getDirectiveKind();
883 if (isOpenMPWorksharingDirective(DKind) &&
884 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
885 return true;
886 }
887 } else if (DKind == OMPD_teams) {
888 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
889 /*IgnoreCaptured=*/true);
890 if (!Body)
891 return false;
892 ChildStmt = getSingleCompoundChild(Body);
893 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
894 DKind = NND->getDirectiveKind();
895 if (isOpenMPParallelDirective(DKind) &&
896 isOpenMPWorksharingDirective(DKind) &&
897 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
898 return true;
899 if (DKind == OMPD_parallel) {
900 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
901 /*IgnoreCaptured=*/true);
902 if (!Body)
903 return false;
904 ChildStmt = getSingleCompoundChild(Body);
905 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
906 DKind = NND->getDirectiveKind();
907 if (isOpenMPWorksharingDirective(DKind) &&
908 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
909 return true;
910 }
911 }
912 }
913 }
914 return false;
915 case OMPD_target_teams:
916 if (isOpenMPParallelDirective(DKind) &&
917 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
918 hasStaticScheduling(*NestedDir))
919 return true;
920 if (DKind == OMPD_parallel) {
921 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
922 /*IgnoreCaptured=*/true);
923 if (!Body)
924 return false;
925 ChildStmt = getSingleCompoundChild(Body);
926 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
927 DKind = NND->getDirectiveKind();
928 if (isOpenMPWorksharingDirective(DKind) &&
929 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
930 return true;
931 }
932 }
933 return false;
934 case OMPD_target_parallel:
935 return isOpenMPWorksharingDirective(DKind) &&
936 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
937 case OMPD_target_teams_distribute:
938 case OMPD_target_simd:
939 case OMPD_target_parallel_for:
940 case OMPD_target_parallel_for_simd:
941 case OMPD_target_teams_distribute_simd:
942 case OMPD_target_teams_distribute_parallel_for:
943 case OMPD_target_teams_distribute_parallel_for_simd:
944 case OMPD_parallel:
945 case OMPD_for:
946 case OMPD_parallel_for:
947 case OMPD_parallel_sections:
948 case OMPD_for_simd:
949 case OMPD_parallel_for_simd:
950 case OMPD_cancel:
951 case OMPD_cancellation_point:
952 case OMPD_ordered:
953 case OMPD_threadprivate:
954 case OMPD_task:
955 case OMPD_simd:
956 case OMPD_sections:
957 case OMPD_section:
958 case OMPD_single:
959 case OMPD_master:
960 case OMPD_critical:
961 case OMPD_taskyield:
962 case OMPD_barrier:
963 case OMPD_taskwait:
964 case OMPD_taskgroup:
965 case OMPD_atomic:
966 case OMPD_flush:
967 case OMPD_teams:
968 case OMPD_target_data:
969 case OMPD_target_exit_data:
970 case OMPD_target_enter_data:
971 case OMPD_distribute:
972 case OMPD_distribute_simd:
973 case OMPD_distribute_parallel_for:
974 case OMPD_distribute_parallel_for_simd:
975 case OMPD_teams_distribute:
976 case OMPD_teams_distribute_simd:
977 case OMPD_teams_distribute_parallel_for:
978 case OMPD_teams_distribute_parallel_for_simd:
979 case OMPD_target_update:
980 case OMPD_declare_simd:
981 case OMPD_declare_target:
982 case OMPD_end_declare_target:
983 case OMPD_declare_reduction:
984 case OMPD_taskloop:
985 case OMPD_taskloop_simd:
986 case OMPD_unknown:
987 llvm_unreachable("Unexpected directive.");
988 }
989 }
990
991 return false;
992}
993
994/// Checks if the construct supports lightweight runtime. It must be SPMD
995/// construct + inner loop-based construct with static scheduling.
996static bool supportsLightweightRuntime(ASTContext &Ctx,
997 const OMPExecutableDirective &D) {
998 if (!supportsSPMDExecutionMode(Ctx, D))
999 return false;
1000 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1001 switch (DirectiveKind) {
1002 case OMPD_target:
1003 case OMPD_target_teams:
1004 case OMPD_target_parallel:
1005 return hasNestedLightweightDirective(Ctx, D);
1006 case OMPD_target_parallel_for:
1007 case OMPD_target_parallel_for_simd:
1008 case OMPD_target_teams_distribute_parallel_for:
1009 case OMPD_target_teams_distribute_parallel_for_simd:
1010 // (Last|First)-privates must be shared in parallel region.
1011 return hasStaticScheduling(D);
1012 case OMPD_target_simd:
1013 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001014 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001015 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001016 case OMPD_parallel:
1017 case OMPD_for:
1018 case OMPD_parallel_for:
1019 case OMPD_parallel_sections:
1020 case OMPD_for_simd:
1021 case OMPD_parallel_for_simd:
1022 case OMPD_cancel:
1023 case OMPD_cancellation_point:
1024 case OMPD_ordered:
1025 case OMPD_threadprivate:
1026 case OMPD_task:
1027 case OMPD_simd:
1028 case OMPD_sections:
1029 case OMPD_section:
1030 case OMPD_single:
1031 case OMPD_master:
1032 case OMPD_critical:
1033 case OMPD_taskyield:
1034 case OMPD_barrier:
1035 case OMPD_taskwait:
1036 case OMPD_taskgroup:
1037 case OMPD_atomic:
1038 case OMPD_flush:
1039 case OMPD_teams:
1040 case OMPD_target_data:
1041 case OMPD_target_exit_data:
1042 case OMPD_target_enter_data:
1043 case OMPD_distribute:
1044 case OMPD_distribute_simd:
1045 case OMPD_distribute_parallel_for:
1046 case OMPD_distribute_parallel_for_simd:
1047 case OMPD_teams_distribute:
1048 case OMPD_teams_distribute_simd:
1049 case OMPD_teams_distribute_parallel_for:
1050 case OMPD_teams_distribute_parallel_for_simd:
1051 case OMPD_target_update:
1052 case OMPD_declare_simd:
1053 case OMPD_declare_target:
1054 case OMPD_end_declare_target:
1055 case OMPD_declare_reduction:
1056 case OMPD_taskloop:
1057 case OMPD_taskloop_simd:
1058 case OMPD_unknown:
1059 break;
1060 }
1061 llvm_unreachable(
1062 "Unknown programming model for OpenMP directive on NVPTX target.");
1063}
1064
1065void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001066 StringRef ParentName,
1067 llvm::Function *&OutlinedFn,
1068 llvm::Constant *&OutlinedFnID,
1069 bool IsOffloadEntry,
1070 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001071 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001072 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001073 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001074 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001075 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001076
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001077 // Emit target region as a standalone region.
1078 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001079 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1080 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001081
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001082 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001083 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001084 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001085 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001086 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001087 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001088 .emitNonSPMDEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001089 }
1090 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001091 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001092 .emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001093 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001094 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001095 CodeGen.setAction(Action);
1096 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1097 IsOffloadEntry, CodeGen);
1098
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001099 // Now change the name of the worker function to correspond to this target
1100 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001101 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001102
1103 // Create the worker function
1104 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001105}
1106
1107// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001108void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001109 EntryFunctionState &EST,
1110 WorkerFunctionState &WST) {
1111 CGBuilderTy &Bld = CGF.Builder;
1112
1113 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1114 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1115 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1116 EST.ExitBB = CGF.createBasicBlock(".exit");
1117
Alexey Bataev9ff80832018-04-16 20:16:21 +00001118 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001119 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1120 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1121
1122 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001123 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001124 CGF.EmitBranch(EST.ExitBB);
1125
1126 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001127 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001128 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1129 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1130
1131 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001132 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001133 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001134 // First action in sequential region:
1135 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001136 // TODO: Optimize runtime initialization and pass in correct value.
1137 llvm::Value *Args[] = {getThreadLimit(CGF),
1138 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001139 CGF.EmitRuntimeCall(
1140 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001141
1142 // For data sharing, we need to initialize the stack.
1143 CGF.EmitRuntimeCall(
1144 createNVPTXRuntimeFunction(
1145 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1146
Alexey Bataevc99042b2018-03-15 18:10:54 +00001147 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001148}
1149
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001150void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001152 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001153 if (!CGF.HaveInsertPoint())
1154 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001155
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001156 emitGenericVarsEpilog(CGF);
1157
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001158 if (!EST.ExitBB)
1159 EST.ExitBB = CGF.createBasicBlock(".exit");
1160
1161 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1162 CGF.EmitBranch(TerminateBB);
1163
1164 CGF.EmitBlock(TerminateBB);
1165 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001166 // TODO: Optimize runtime initialization and pass in correct value.
1167 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001169 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001170 // Barrier to terminate worker threads.
1171 syncCTAThreads(CGF);
1172 // Master thread jumps to exit point.
1173 CGF.EmitBranch(EST.ExitBB);
1174
1175 CGF.EmitBlock(EST.ExitBB);
1176 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001177}
1178
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001179void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001180 StringRef ParentName,
1181 llvm::Function *&OutlinedFn,
1182 llvm::Constant *&OutlinedFnID,
1183 bool IsOffloadEntry,
1184 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001185 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001186 EntryFunctionState EST;
1187
1188 // Emit target region as a standalone region.
1189 class NVPTXPrePostActionTy : public PrePostActionTy {
1190 CGOpenMPRuntimeNVPTX &RT;
1191 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1192 const OMPExecutableDirective &D;
1193
1194 public:
1195 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1196 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1197 const OMPExecutableDirective &D)
1198 : RT(RT), EST(EST), D(D) {}
1199 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001200 RT.emitSPMDEntryHeader(CGF, EST, D);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001201 }
1202 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001203 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001204 }
1205 } Action(*this, EST, D);
1206 CodeGen.setAction(Action);
1207 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1208 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001209}
1210
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001211void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001212 CodeGenFunction &CGF, EntryFunctionState &EST,
1213 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001214 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001215
1216 // Setup BBs in entry function.
1217 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1218 EST.ExitBB = CGF.createBasicBlock(".exit");
1219
1220 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001221 bool RequiresFullRuntime = !supportsLightweightRuntime(CGF.getContext(), D);
1222 llvm::Value *Args[] = {
1223 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1224 /*RequiresOMPRuntime=*/
1225 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1226 /*RequiresDataSharing=*/Bld.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001227 CGF.EmitRuntimeCall(
1228 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001229
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001230 if (RequiresFullRuntime) {
1231 // For data sharing, we need to initialize the stack.
1232 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1233 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1234 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001235
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001236 CGF.EmitBranch(ExecuteBB);
1237
1238 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001239
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001240 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001241}
1242
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001243void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001244 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001245 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001246 if (!CGF.HaveInsertPoint())
1247 return;
1248
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001249 if (!EST.ExitBB)
1250 EST.ExitBB = CGF.createBasicBlock(".exit");
1251
1252 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1253 CGF.EmitBranch(OMPDeInitBB);
1254
1255 CGF.EmitBlock(OMPDeInitBB);
1256 // DeInitialize the OMP state in the runtime; called by all active threads.
1257 CGF.EmitRuntimeCall(
1258 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1259 CGF.EmitBranch(EST.ExitBB);
1260
1261 CGF.EmitBlock(EST.ExitBB);
1262 EST.ExitBB = nullptr;
1263}
1264
1265// Create a unique global variable to indicate the execution mode of this target
1266// region. The execution mode is either 'generic', or 'spmd' depending on the
1267// target directive. This variable is picked up by the offload library to setup
1268// the device appropriately before kernel launch. If the execution mode is
1269// 'generic', the runtime reserves one warp for the master, otherwise, all
1270// warps participate in parallel work.
1271static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001272 bool Mode) {
1273 auto *GVMode =
1274 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1275 llvm::GlobalValue::WeakAnyLinkage,
1276 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1277 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001278 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001279}
1280
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001281void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001282 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001283
1284 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001285 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001286 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001287 emitWorkerLoop(CGF, WST);
1288 CGF.FinishFunction();
1289}
1290
1291void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1292 WorkerFunctionState &WST) {
1293 //
1294 // The workers enter this loop and wait for parallel work from the master.
1295 // When the master encounters a parallel region it sets up the work + variable
1296 // arguments, and wakes up the workers. The workers first check to see if
1297 // they are required for the parallel region, i.e., within the # of requested
1298 // parallel threads. The activated workers load the variable arguments and
1299 // execute the parallel work.
1300 //
1301
1302 CGBuilderTy &Bld = CGF.Builder;
1303
1304 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1305 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1306 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1307 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1308 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1309 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1310
1311 CGF.EmitBranch(AwaitBB);
1312
1313 // Workers wait for work from master.
1314 CGF.EmitBlock(AwaitBB);
1315 // Wait for parallel work
1316 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001317
1318 Address WorkFn =
1319 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1320 Address ExecStatus =
1321 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1322 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1323 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1324
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001325 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001326 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001327 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001328 llvm::Value *Ret = CGF.EmitRuntimeCall(
1329 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1330 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001331
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001332 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001333 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1334 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001335 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1336
1337 // Activate requested workers.
1338 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001339 llvm::Value *IsActive =
1340 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1341 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001342
1343 // Signal start of parallel region.
1344 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001345
1346 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001347 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001348 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001349 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001350
1351 llvm::Value *WorkFnMatch =
1352 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1353
1354 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1355 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1356 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1357
1358 // Execute this outlined function.
1359 CGF.EmitBlock(ExecuteFNBB);
1360
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001361 // Insert call to work function via shared wrapper. The shared
1362 // wrapper takes two arguments:
1363 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001364 // - the thread ID;
1365 emitCall(CGF, WST.Loc, W,
1366 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001367
1368 // Go to end of parallel region.
1369 CGF.EmitBranch(TerminateBB);
1370
1371 CGF.EmitBlock(CheckNextBB);
1372 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001373 // Default case: call to outlined function through pointer if the target
1374 // region makes a declare target call that may contain an orphaned parallel
1375 // directive.
1376 auto *ParallelFnTy =
1377 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1378 /*isVarArg=*/false)
1379 ->getPointerTo();
1380 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1381 // Insert call to work function via shared wrapper. The shared
1382 // wrapper takes two arguments:
1383 // - the parallelism level;
1384 // - the thread ID;
1385 emitCall(CGF, WST.Loc, WorkFnCast,
1386 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1387 // Go to end of parallel region.
1388 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001389
1390 // Signal end of parallel region.
1391 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001392 CGF.EmitRuntimeCall(
1393 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1394 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001395 CGF.EmitBranch(BarrierBB);
1396
1397 // All active and inactive workers wait at a barrier after parallel region.
1398 CGF.EmitBlock(BarrierBB);
1399 // Barrier after parallel region.
1400 syncCTAThreads(CGF);
1401 CGF.EmitBranch(AwaitBB);
1402
1403 // Exit target region.
1404 CGF.EmitBlock(ExitBB);
1405}
1406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001407/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001408/// implementation. Specialized for the NVPTX device.
1409/// \param Function OpenMP runtime function.
1410/// \return Specified function.
1411llvm::Constant *
1412CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1413 llvm::Constant *RTLFn = nullptr;
1414 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1415 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001416 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1417 // RequiresOMPRuntime);
1418 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001419 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001420 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1421 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1422 break;
1423 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001424 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001425 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1426 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001427 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001428 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001429 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1430 break;
1431 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001432 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1433 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001434 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001435 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001436 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001437 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1438 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1439 break;
1440 }
1441 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1442 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001443 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001444 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1445 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1446 break;
1447 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001448 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1449 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001450 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001451 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001452 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001453 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1454 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1455 break;
1456 }
1457 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001458 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1459 /// int16_t IsOMPRuntimeInitialized);
1460 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001461 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001462 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001463 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1464 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1465 break;
1466 }
1467 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1468 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001469 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001470 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1471 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1472 break;
1473 }
1474 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1475 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1476 // global_tid);
1477 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001478 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001479 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1480 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1481 break;
1482 }
1483 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1484 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1485 // global_tid);
1486 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001487 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001488 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1489 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1490 break;
1491 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001492 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1493 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1494 // int16_t lane_offset, int16_t warp_size);
1495 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001496 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001497 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1498 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1499 break;
1500 }
1501 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1502 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1503 // int16_t lane_offset, int16_t warp_size);
1504 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001505 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001506 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1508 break;
1509 }
1510 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1511 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1512 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1513 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1514 // lane_offset, int16_t Algorithm Version),
1515 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1516 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1517 CGM.Int16Ty, CGM.Int16Ty};
1518 auto *ShuffleReduceFnTy =
1519 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1520 /*isVarArg=*/false);
1521 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1522 auto *InterWarpCopyFnTy =
1523 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1524 /*isVarArg=*/false);
1525 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1526 CGM.Int32Ty,
1527 CGM.SizeTy,
1528 CGM.VoidPtrTy,
1529 ShuffleReduceFnTy->getPointerTo(),
1530 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001531 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001532 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1533 RTLFn = CGM.CreateRuntimeFunction(
1534 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1535 break;
1536 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001537 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1538 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1539 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1540 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1541 // lane_offset, int16_t Algorithm Version),
1542 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1543 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1544 CGM.Int16Ty, CGM.Int16Ty};
1545 auto *ShuffleReduceFnTy =
1546 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1547 /*isVarArg=*/false);
1548 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1549 auto *InterWarpCopyFnTy =
1550 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1551 /*isVarArg=*/false);
1552 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1553 CGM.Int32Ty,
1554 CGM.SizeTy,
1555 CGM.VoidPtrTy,
1556 ShuffleReduceFnTy->getPointerTo(),
1557 InterWarpCopyFnTy->getPointerTo()};
1558 auto *FnTy =
1559 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1560 RTLFn = CGM.CreateRuntimeFunction(
1561 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1562 break;
1563 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001564 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1565 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1566 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1567 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1568 // lane_offset, int16_t shortCircuit),
1569 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1570 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1571 // int32_t index, int32_t width),
1572 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1573 // int32_t index, int32_t width, int32_t reduce))
1574 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1575 CGM.Int16Ty, CGM.Int16Ty};
1576 auto *ShuffleReduceFnTy =
1577 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1578 /*isVarArg=*/false);
1579 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1580 auto *InterWarpCopyFnTy =
1581 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1582 /*isVarArg=*/false);
1583 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1584 CGM.Int32Ty, CGM.Int32Ty};
1585 auto *CopyToScratchpadFnTy =
1586 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1587 /*isVarArg=*/false);
1588 llvm::Type *LoadReduceTypeParams[] = {
1589 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1590 auto *LoadReduceFnTy =
1591 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1592 /*isVarArg=*/false);
1593 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1594 CGM.Int32Ty,
1595 CGM.SizeTy,
1596 CGM.VoidPtrTy,
1597 ShuffleReduceFnTy->getPointerTo(),
1598 InterWarpCopyFnTy->getPointerTo(),
1599 CopyToScratchpadFnTy->getPointerTo(),
1600 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001601 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001602 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1603 RTLFn = CGM.CreateRuntimeFunction(
1604 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1605 break;
1606 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001607 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1608 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1609 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001610 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001611 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1612 RTLFn = CGM.CreateRuntimeFunction(
1613 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1614 break;
1615 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001616 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1617 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001618 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001619 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1620 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1621 break;
1622 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001623 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1624 /// Build void __kmpc_data_sharing_init_stack_spmd();
1625 auto *FnTy =
1626 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001627 RTLFn =
1628 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001629 break;
1630 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001631 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1632 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1633 // int16_t UseSharedMemory);
1634 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001635 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001636 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1637 RTLFn = CGM.CreateRuntimeFunction(
1638 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1639 break;
1640 }
1641 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1642 // Build void __kmpc_data_sharing_pop_stack(void *a);
1643 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001644 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001645 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1646 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1647 /*Name=*/"__kmpc_data_sharing_pop_stack");
1648 break;
1649 }
1650 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1651 /// Build void __kmpc_begin_sharing_variables(void ***args,
1652 /// size_t n_args);
1653 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001654 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001655 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1656 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1657 break;
1658 }
1659 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1660 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001661 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001662 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1663 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1664 break;
1665 }
1666 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1667 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1668 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001669 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001670 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1671 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1672 break;
1673 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001674 case OMPRTL_NVPTX__kmpc_parallel_level: {
1675 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1677 auto *FnTy =
1678 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1680 break;
1681 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001682 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1683 // Build int8_t __kmpc_is_spmd_exec_mode();
1684 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1685 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1686 break;
1687 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001688 }
1689 return RTLFn;
1690}
1691
1692void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1693 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001694 uint64_t Size, int32_t,
1695 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001696 // TODO: Add support for global variables on the device after declare target
1697 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001698 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001699 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001700 llvm::Module &M = CGM.getModule();
1701 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001702
1703 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001704 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001705
1706 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001707 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001708 llvm::ConstantAsMetadata::get(
1709 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1710 // Append metadata to nvvm.annotations
1711 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1712}
1713
1714void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1715 const OMPExecutableDirective &D, StringRef ParentName,
1716 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001717 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001718 if (!IsOffloadEntry) // Nothing to do.
1719 return;
1720
1721 assert(!ParentName.empty() && "Invalid target region parent name!");
1722
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001723 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001724 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001725 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001726 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001727 else
1728 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1729 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001730
1731 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001732}
1733
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001734CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001735 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001736 if (!CGM.getLangOpts().OpenMPIsDevice)
1737 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001738}
Carlo Bertollic6872252016-04-04 15:55:02 +00001739
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001740void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1741 OpenMPProcBindClauseKind ProcBind,
1742 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001743 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001744 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001745 return;
1746
1747 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1748}
1749
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001750void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1751 llvm::Value *NumThreads,
1752 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001753 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001754 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001755 return;
1756
1757 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1758}
1759
Carlo Bertollic6872252016-04-04 15:55:02 +00001760void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1761 const Expr *NumTeams,
1762 const Expr *ThreadLimit,
1763 SourceLocation Loc) {}
1764
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001765llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1766 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1767 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001768 // Emit target region as a standalone region.
1769 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001770 bool &IsInParallelRegion;
1771 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001772
1773 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001774 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1775 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001776 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001777 PrevIsInParallelRegion = IsInParallelRegion;
1778 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001779 }
1780 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001781 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001782 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001783 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001784 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001785 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1786 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001787 auto *OutlinedFun =
1788 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1789 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001790 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001791 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1792 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001793 llvm::Function *WrapperFun =
1794 createParallelDataSharingWrapper(OutlinedFun, D);
1795 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1796 }
1797
1798 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001799}
1800
1801llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001802 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1803 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001804 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001805
Alexey Bataevc99042b2018-03-15 18:10:54 +00001806 // Emit target region as a standalone region.
1807 class NVPTXPrePostActionTy : public PrePostActionTy {
1808 SourceLocation &Loc;
1809
1810 public:
1811 NVPTXPrePostActionTy(SourceLocation &Loc) : Loc(Loc) {}
1812 void Enter(CodeGenFunction &CGF) override {
1813 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1814 .emitGenericVarsProlog(CGF, Loc);
1815 }
1816 void Exit(CodeGenFunction &CGF) override {
1817 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1818 .emitGenericVarsEpilog(CGF);
1819 }
1820 } Action(Loc);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001821 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1822 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001823 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1824 D, ThreadIDVar, InnermostKind, CodeGen);
1825 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1826 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001827 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001828 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001829
1830 return OutlinedFun;
1831}
1832
Alexey Bataevc99042b2018-03-15 18:10:54 +00001833void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
1834 SourceLocation Loc) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001835 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1836 return;
1837
Alexey Bataevc99042b2018-03-15 18:10:54 +00001838 CGBuilderTy &Bld = CGF.Builder;
1839
1840 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1841 if (I == FunctionGlobalizedDecls.end())
1842 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001843 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1844 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001845
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001846 // Recover pointer to this function's global record. The runtime will
1847 // handle the specifics of the allocation of the memory.
1848 // Use actual memory size of the record including the padding
1849 // for alignment purposes.
1850 unsigned Alignment =
1851 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1852 unsigned GlobalRecordSize =
1853 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1854 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001855
1856 llvm::Value *GlobalRecCastAddr;
1857 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
1858 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1859 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1860 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1861 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1862 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1863 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1864 // There is no need to emit line number for unconditional branch.
1865 (void)ApplyDebugLocation::CreateEmpty(CGF);
1866 CGF.EmitBlock(SPMDBB);
1867 Address RecPtr = CGF.CreateMemTemp(RecTy, "_local_stack");
1868 CGF.EmitBranch(ExitBB);
1869 // There is no need to emit line number for unconditional branch.
1870 (void)ApplyDebugLocation::CreateEmpty(CGF);
1871 CGF.EmitBlock(NonSPMDBB);
1872 // TODO: allow the usage of shared memory to be controlled by
1873 // the user, for now, default to global.
1874 llvm::Value *GlobalRecordSizeArg[] = {
1875 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1876 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1877 llvm::Value *GlobalRecValue =
1878 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1879 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1880 GlobalRecordSizeArg);
1881 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1882 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1883 CGF.EmitBlock(ExitBB);
1884 auto *Phi = Bld.CreatePHI(GlobalRecCastAddr->getType(),
1885 /*NumReservedValues=*/2, "_select_stack");
1886 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
1887 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
1888 GlobalRecCastAddr = Phi;
1889 I->getSecond().GlobalRecordAddr = Phi;
1890 I->getSecond().IsInSPMDModeFlag = IsSPMD;
1891 } else {
1892 assert(getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD &&
1893 "Expected Non-SPMD construct.");
1894 // TODO: allow the usage of shared memory to be controlled by
1895 // the user, for now, default to global.
1896 llvm::Value *GlobalRecordSizeArg[] = {
1897 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1898 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1899 llvm::Value *GlobalRecValue =
1900 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1901 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1902 GlobalRecordSizeArg);
1903 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1904 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1905 I->getSecond().GlobalRecordAddr = GlobalRecValue;
1906 I->getSecond().IsInSPMDModeFlag = nullptr;
1907 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001908 LValue Base =
1909 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001910
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001911 // Emit the "global alloca" which is a GEP from the global declaration
1912 // record using the pointer returned by the runtime.
1913 for (auto &Rec : I->getSecond().LocalVarData) {
1914 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1915 llvm::Value *ParValue;
1916 if (EscapedParam) {
1917 const auto *VD = cast<VarDecl>(Rec.first);
1918 LValue ParLVal =
1919 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1920 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1921 }
1922 const FieldDecl *FD = Rec.second.first;
1923 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
1924 Rec.second.second = VarAddr.getAddress();
1925 if (EscapedParam) {
1926 const auto *VD = cast<VarDecl>(Rec.first);
1927 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1928 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1929 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001930 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001931 }
1932 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1933 // Recover pointer to this function's global record. The runtime will
1934 // handle the specifics of the allocation of the memory.
1935 // Use actual memory size of the record including the padding
1936 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001937 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001938 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1939 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1940 Size = Bld.CreateNUWAdd(
1941 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1942 llvm::Value *AlignVal =
1943 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1944 Size = Bld.CreateUDiv(Size, AlignVal);
1945 Size = Bld.CreateNUWMul(Size, AlignVal);
1946 // TODO: allow the usage of shared memory to be controlled by
1947 // the user, for now, default to global.
1948 llvm::Value *GlobalRecordSizeArg[] = {
1949 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1950 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1951 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1952 GlobalRecordSizeArg);
1953 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1954 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1955 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1956 CGM.getContext().getDeclAlign(VD),
1957 AlignmentSource::Decl);
1958 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1959 Base.getAddress());
1960 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001961 }
1962 I->getSecond().MappedParams->apply(CGF);
1963}
1964
1965void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001966 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1967 return;
1968
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001970 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001971 I->getSecond().MappedParams->restore(CGF);
1972 if (!CGF.HaveInsertPoint())
1973 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001974 for (llvm::Value *Addr :
1975 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1976 CGF.EmitRuntimeCall(
1977 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1978 Addr);
1979 }
1980 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001981 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
1982 CGBuilderTy &Bld = CGF.Builder;
1983 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1984 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1985 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
1986 // There is no need to emit line number for unconditional branch.
1987 (void)ApplyDebugLocation::CreateEmpty(CGF);
1988 CGF.EmitBlock(NonSPMDBB);
1989 CGF.EmitRuntimeCall(
1990 createNVPTXRuntimeFunction(
1991 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1992 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
1993 CGF.EmitBlock(ExitBB);
1994 } else {
1995 assert(getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD &&
1996 "Expected Non-SPMD mode.");
1997 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1998 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1999 I->getSecond().GlobalRecordAddr);
2000 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002001 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002002 }
2003}
2004
Carlo Bertollic6872252016-04-04 15:55:02 +00002005void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2006 const OMPExecutableDirective &D,
2007 SourceLocation Loc,
2008 llvm::Value *OutlinedFn,
2009 ArrayRef<llvm::Value *> CapturedVars) {
2010 if (!CGF.HaveInsertPoint())
2011 return;
2012
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002013 Address ZeroAddr = CGF.CreateMemTemp(
2014 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2015 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002016 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2017 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002018 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002019 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2020 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002021 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002022}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002023
2024void CGOpenMPRuntimeNVPTX::emitParallelCall(
2025 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2026 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2027 if (!CGF.HaveInsertPoint())
2028 return;
2029
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002030 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002031 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002032 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002033 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002034}
2035
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002036void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002037 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2038 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2039 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002040
2041 // Force inline this outlined function at its call site.
2042 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2043
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002044 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2045 /*DestWidth=*/32, /*Signed=*/1),
2046 ".zero.addr");
2047 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002048 // ThreadId for serialized parallels is 0.
2049 Address ThreadIDAddr = ZeroAddr;
2050 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002051 CodeGenFunction &CGF, PrePostActionTy &Action) {
2052 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002053
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002054 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2055 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2056 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2057 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2058 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2059 };
2060 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2061 PrePostActionTy &) {
2062
2063 RegionCodeGenTy RCG(CodeGen);
2064 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2065 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2066 llvm::Value *Args[] = {RTLoc, ThreadID};
2067
2068 NVPTXActionTy Action(
2069 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2070 Args,
2071 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2072 Args);
2073 RCG.setAction(Action);
2074 RCG(CGF);
2075 };
2076
2077 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2078 PrePostActionTy &Action) {
2079 CGBuilderTy &Bld = CGF.Builder;
2080 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2081 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002082 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2083
2084 // Prepare for parallel region. Indicate the outlined function.
2085 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002086 CGF.EmitRuntimeCall(
2087 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2088 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002089
2090 // Create a private scope that will globalize the arguments
2091 // passed from the outside of the target region.
2092 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2093
2094 // There's somehting to share.
2095 if (!CapturedVars.empty()) {
2096 // Prepare for parallel region. Indicate the outlined function.
2097 Address SharedArgs =
2098 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2099 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2100
2101 llvm::Value *DataSharingArgs[] = {
2102 SharedArgsPtr,
2103 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2104 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2105 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2106 DataSharingArgs);
2107
2108 // Store variable address in a list of references to pass to workers.
2109 unsigned Idx = 0;
2110 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002111 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2112 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2113 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002114 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002115 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2116 CGF.getPointerSize());
2117 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002118 if (V->getType()->isIntegerTy())
2119 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2120 else
2121 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002122 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2123 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002124 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002125 }
2126 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002127
2128 // Activate workers. This barrier is used by the master to signal
2129 // work for the workers.
2130 syncCTAThreads(CGF);
2131
2132 // OpenMP [2.5, Parallel Construct, p.49]
2133 // There is an implied barrier at the end of a parallel region. After the
2134 // end of a parallel region, only the master thread of the team resumes
2135 // execution of the enclosing task region.
2136 //
2137 // The master waits at this barrier until all workers are done.
2138 syncCTAThreads(CGF);
2139
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002140 if (!CapturedVars.empty())
2141 CGF.EmitRuntimeCall(
2142 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2143
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002144 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002145 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002146 };
2147
Alexey Bataev8521ff62018-07-25 20:03:01 +00002148 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen, &CodeGen,
2149 &ThreadIDAddr](CodeGenFunction &CGF,
2150 PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002151 RegionCodeGenTy RCG(CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002152 if (IsInParallelRegion) {
2153 SeqGen(CGF, Action);
2154 } else if (IsInTargetMasterThreadRegion) {
2155 L0ParallelGen(CGF, Action);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002156 } else if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD) {
2157 RCG(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002158 } else {
2159 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002160 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Alexey Bataev673110d2018-05-16 13:36:30 +00002161 // Serialized execution.
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002162 // } else if (master) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002163 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002164 // } else {
2165 // Outlined function call.
2166 // }
2167 CGBuilderTy &Bld = CGF.Builder;
2168 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002169 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2170 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002171 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
Alexey Bataev673110d2018-05-16 13:36:30 +00002172 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2173 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002174 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002175 // There is no need to emit line number for unconditional branch.
2176 (void)ApplyDebugLocation::CreateEmpty(CGF);
2177 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002178 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2179 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2180 llvm::Value *PL = CGF.EmitRuntimeCall(
2181 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2182 {RTLoc, ThreadID});
2183 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002184 Bld.CreateCondBr(Res, SeqBB, MasterCheckBB);
2185 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002186 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002187 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002188 // There is no need to emit line number for unconditional branch.
2189 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002190 CGF.EmitBlock(MasterCheckBB);
2191 llvm::BasicBlock *MasterThenBB = CGF.createBasicBlock("master.then");
2192 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2193 llvm::Value *IsMaster =
2194 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
2195 Bld.CreateCondBr(IsMaster, MasterThenBB, ElseBlock);
2196 CGF.EmitBlock(MasterThenBB);
2197 L0ParallelGen(CGF, Action);
2198 CGF.EmitBranch(ExitBB);
2199 // There is no need to emit line number for unconditional branch.
2200 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002201 CGF.EmitBlock(ElseBlock);
Alexey Bataev8521ff62018-07-25 20:03:01 +00002202 // In the worker need to use the real thread id.
2203 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002204 RCG(CGF);
2205 // There is no need to emit line number for unconditional branch.
2206 (void)ApplyDebugLocation::CreateEmpty(CGF);
2207 // Emit the continuation block for code after the if.
2208 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2209 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002210 };
2211
Alexey Bataev9ff80832018-04-16 20:16:21 +00002212 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002213 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002214 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002215 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002216 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002217 ThenRCG(CGF);
2218 }
2219}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002220
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002221void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002222 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2223 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2224 // Just call the outlined function to execute the parallel region.
2225 // OutlinedFn(&GTid, &zero, CapturedStruct);
2226 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002227 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002228
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002229 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2230 /*DestWidth=*/32, /*Signed=*/1),
2231 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002232 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002233 // ThreadId for serialized parallels is 0.
2234 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002235 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002236 &ThreadIDAddr](CodeGenFunction &CGF,
2237 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002238 Action.Enter(CGF);
2239
2240 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2241 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2242 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2243 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2244 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2245 };
2246 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2247 PrePostActionTy &) {
2248
2249 RegionCodeGenTy RCG(CodeGen);
2250 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2251 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2252 llvm::Value *Args[] = {RTLoc, ThreadID};
2253
2254 NVPTXActionTy Action(
2255 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2256 Args,
2257 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2258 Args);
2259 RCG.setAction(Action);
2260 RCG(CGF);
2261 };
2262
2263 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002264 // In the worker need to use the real thread id.
2265 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002266 RegionCodeGenTy RCG(CodeGen);
2267 RCG(CGF);
2268 } else {
2269 // If we are not in the target region, it is definitely L2 parallelism or
2270 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2271 // need to check for orphaned directives.
2272 RegionCodeGenTy RCG(SeqGen);
2273 RCG(CGF);
2274 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002275}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002276
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002277void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2278 CodeGenFunction &CGF, StringRef CriticalName,
2279 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2280 const Expr *Hint) {
2281 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2282 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2283 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2284 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2285 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2286
2287 // Fetch team-local id of the thread.
2288 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2289
2290 // Get the width of the team.
2291 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2292
2293 // Initialize the counter variable for the loop.
2294 QualType Int32Ty =
2295 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2296 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2297 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2298 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2299 /*isInit=*/true);
2300
2301 // Block checks if loop counter exceeds upper bound.
2302 CGF.EmitBlock(LoopBB);
2303 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2304 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2305 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2306
2307 // Block tests which single thread should execute region, and which threads
2308 // should go straight to synchronisation point.
2309 CGF.EmitBlock(TestBB);
2310 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2311 llvm::Value *CmpThreadToCounter =
2312 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2313 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2314
2315 // Block emits the body of the critical region.
2316 CGF.EmitBlock(BodyBB);
2317
2318 // Output the critical statement.
2319 CriticalOpGen(CGF);
2320
2321 // After the body surrounded by the critical region, the single executing
2322 // thread will jump to the synchronisation point.
2323 // Block waits for all threads in current team to finish then increments the
2324 // counter variable and returns to the loop.
2325 CGF.EmitBlock(SyncBB);
2326 getNVPTXCTABarrier(CGF);
2327
2328 llvm::Value *IncCounterVal =
2329 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2330 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2331 CGF.EmitBranch(LoopBB);
2332
2333 // Block that is reached when all threads in the team complete the region.
2334 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2335}
2336
Alexey Bataevb2575932018-01-04 20:18:55 +00002337/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002338static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2339 QualType ValTy, QualType CastTy,
2340 SourceLocation Loc) {
2341 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2342 "Cast type must sized.");
2343 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2344 "Val type must sized.");
2345 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2346 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002347 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002348 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2349 CGF.getContext().getTypeSizeInChars(CastTy))
2350 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2351 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2352 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2353 CastTy->hasSignedIntegerRepresentation());
2354 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002355 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2356 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002357 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2358 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002359}
2360
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002361/// This function creates calls to one of two shuffle functions to copy
2362/// variables between lanes in a warp.
2363static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002364 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002365 QualType ElemType,
2366 llvm::Value *Offset,
2367 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002368 CodeGenModule &CGM = CGF.CGM;
2369 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002370 CGOpenMPRuntimeNVPTX &RT =
2371 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2372
Alexey Bataeva453f362018-03-19 17:53:56 +00002373 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2374 assert(Size.getQuantity() <= 8 &&
2375 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002376
Alexey Bataeva453f362018-03-19 17:53:56 +00002377 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002378 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2379 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2380
2381 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002382 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2383 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2384 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002385 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002386 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002387
Alexey Bataev9ff80832018-04-16 20:16:21 +00002388 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2389 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002390
Alexey Bataeva453f362018-03-19 17:53:56 +00002391 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002392}
2393
Alexey Bataev12c62902018-06-22 19:10:38 +00002394static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2395 Address DestAddr, QualType ElemType,
2396 llvm::Value *Offset, SourceLocation Loc) {
2397 CGBuilderTy &Bld = CGF.Builder;
2398
2399 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2400 // Create the loop over the big sized data.
2401 // ptr = (void*)Elem;
2402 // ptrEnd = (void*) Elem + 1;
2403 // Step = 8;
2404 // while (ptr + Step < ptrEnd)
2405 // shuffle((int64_t)*ptr);
2406 // Step = 4;
2407 // while (ptr + Step < ptrEnd)
2408 // shuffle((int32_t)*ptr);
2409 // ...
2410 Address ElemPtr = DestAddr;
2411 Address Ptr = SrcAddr;
2412 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2413 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2414 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2415 if (Size < CharUnits::fromQuantity(IntSize))
2416 continue;
2417 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2418 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2419 /*Signed=*/1);
2420 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2421 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2422 ElemPtr =
2423 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2424 if (Size.getQuantity() / IntSize > 1) {
2425 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2426 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2427 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2428 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2429 CGF.EmitBlock(PreCondBB);
2430 llvm::PHINode *PhiSrc =
2431 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2432 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2433 llvm::PHINode *PhiDest =
2434 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2435 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2436 Ptr = Address(PhiSrc, Ptr.getAlignment());
2437 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2438 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2439 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2440 Ptr.getPointer(), CGF.VoidPtrTy));
2441 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2442 ThenBB, ExitBB);
2443 CGF.EmitBlock(ThenBB);
2444 llvm::Value *Res = createRuntimeShuffleFunction(
2445 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2446 IntType, Offset, Loc);
2447 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2448 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2449 ElemPtr =
2450 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2451 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2452 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2453 CGF.EmitBranch(PreCondBB);
2454 CGF.EmitBlock(ExitBB);
2455 } else {
2456 llvm::Value *Res = createRuntimeShuffleFunction(
2457 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2458 IntType, Offset, Loc);
2459 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2460 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2461 ElemPtr =
2462 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2463 }
2464 Size = Size % IntSize;
2465 }
2466}
2467
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002468namespace {
2469enum CopyAction : unsigned {
2470 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2471 // the warp using shuffle instructions.
2472 RemoteLaneToThread,
2473 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2474 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002475 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2476 ThreadToScratchpad,
2477 // ScratchpadToThread: Copy from a scratchpad array in global memory
2478 // containing team-reduced data to a thread's stack.
2479 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002480};
2481} // namespace
2482
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002483struct CopyOptionsTy {
2484 llvm::Value *RemoteLaneOffset;
2485 llvm::Value *ScratchpadIndex;
2486 llvm::Value *ScratchpadWidth;
2487};
2488
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002489/// Emit instructions to copy a Reduce list, which contains partially
2490/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002491static void emitReductionListCopy(
2492 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2493 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2494 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002495
Alexey Bataev9ff80832018-04-16 20:16:21 +00002496 CodeGenModule &CGM = CGF.CGM;
2497 ASTContext &C = CGM.getContext();
2498 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002499
Alexey Bataev9ff80832018-04-16 20:16:21 +00002500 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2501 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2502 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002503
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002504 // Iterates, element-by-element, through the source Reduce list and
2505 // make a copy.
2506 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002507 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002508 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002509 Address SrcElementAddr = Address::invalid();
2510 Address DestElementAddr = Address::invalid();
2511 Address DestElementPtrAddr = Address::invalid();
2512 // Should we shuffle in an element from a remote lane?
2513 bool ShuffleInElement = false;
2514 // Set to true to update the pointer in the dest Reduce list to a
2515 // newly created element.
2516 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002517 // Increment the src or dest pointer to the scratchpad, for each
2518 // new element.
2519 bool IncrScratchpadSrc = false;
2520 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002521
2522 switch (Action) {
2523 case RemoteLaneToThread: {
2524 // Step 1.1: Get the address for the src element in the Reduce list.
2525 Address SrcElementPtrAddr =
2526 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002527 SrcElementAddr = CGF.EmitLoadOfPointer(
2528 SrcElementPtrAddr,
2529 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002530
2531 // Step 1.2: Create a temporary to store the element in the destination
2532 // Reduce list.
2533 DestElementPtrAddr =
2534 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2535 DestElementAddr =
2536 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2537 ShuffleInElement = true;
2538 UpdateDestListPtr = true;
2539 break;
2540 }
2541 case ThreadCopy: {
2542 // Step 1.1: Get the address for the src element in the Reduce list.
2543 Address SrcElementPtrAddr =
2544 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002545 SrcElementAddr = CGF.EmitLoadOfPointer(
2546 SrcElementPtrAddr,
2547 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002548
2549 // Step 1.2: Get the address for dest element. The destination
2550 // element has already been created on the thread's stack.
2551 DestElementPtrAddr =
2552 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002553 DestElementAddr = CGF.EmitLoadOfPointer(
2554 DestElementPtrAddr,
2555 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002556 break;
2557 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002558 case ThreadToScratchpad: {
2559 // Step 1.1: Get the address for the src element in the Reduce list.
2560 Address SrcElementPtrAddr =
2561 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002562 SrcElementAddr = CGF.EmitLoadOfPointer(
2563 SrcElementPtrAddr,
2564 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002565
2566 // Step 1.2: Get the address for dest element:
2567 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002568 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002569 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002570 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002571 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002572 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002573 ScratchPadElemAbsolutePtrVal =
2574 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002575 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2576 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002577 IncrScratchpadDest = true;
2578 break;
2579 }
2580 case ScratchpadToThread: {
2581 // Step 1.1: Get the address for the src element in the scratchpad.
2582 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002583 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002584 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002585 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002586 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002587 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002588 ScratchPadElemAbsolutePtrVal =
2589 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2590 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2591 C.getTypeAlignInChars(Private->getType()));
2592 IncrScratchpadSrc = true;
2593
2594 // Step 1.2: Create a temporary to store the element in the destination
2595 // Reduce list.
2596 DestElementPtrAddr =
2597 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2598 DestElementAddr =
2599 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2600 UpdateDestListPtr = true;
2601 break;
2602 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002603 }
2604
2605 // Regardless of src and dest of copy, we emit the load of src
2606 // element as this is required in all directions
2607 SrcElementAddr = Bld.CreateElementBitCast(
2608 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002609 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2610 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002611
2612 // Now that all active lanes have read the element in the
2613 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002614 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002615 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2616 RemoteLaneOffset, Private->getExprLoc());
2617 } else {
2618 if (Private->getType()->isScalarType()) {
2619 llvm::Value *Elem =
2620 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2621 Private->getType(), Private->getExprLoc());
2622 // Store the source element value to the dest element address.
2623 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2624 Private->getType());
2625 } else {
2626 CGF.EmitAggregateCopy(
2627 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2628 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2629 Private->getType(), AggValueSlot::DoesNotOverlap);
2630 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002631 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002632
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002633 // Step 3.1: Modify reference in dest Reduce list as needed.
2634 // Modifying the reference in Reduce list to point to the newly
2635 // created element. The element is live in the current function
2636 // scope and that of functions it invokes (i.e., reduce_function).
2637 // RemoteReduceData[i] = (void*)&RemoteElem
2638 if (UpdateDestListPtr) {
2639 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2640 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2641 DestElementPtrAddr, /*Volatile=*/false,
2642 C.VoidPtrTy);
2643 }
2644
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002645 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2646 // address of the next element in scratchpad memory, unless we're currently
2647 // processing the last one. Memory alignment is also taken care of here.
2648 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2649 llvm::Value *ScratchpadBasePtr =
2650 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002651 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2652 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002653 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002654 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002655
2656 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002657 ScratchpadBasePtr = Bld.CreateNUWSub(
2658 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2659 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002660 ScratchpadBasePtr,
2661 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002662 ScratchpadBasePtr = Bld.CreateNUWAdd(
2663 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2664 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002665 ScratchpadBasePtr,
2666 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2667
2668 if (IncrScratchpadDest)
2669 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2670 else /* IncrScratchpadSrc = true */
2671 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2672 }
2673
Alexey Bataev9ff80832018-04-16 20:16:21 +00002674 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002675 }
2676}
2677
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002678/// This function emits a helper that loads data from the scratchpad array
2679/// and (optionally) reduces it with the input operand.
2680///
2681/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2682/// reduce_data remote;
2683/// for elem in remote:
2684/// remote.elem = Scratchpad[elem_id][index]
2685/// if (should_reduce)
2686/// local = local @ remote
2687/// else
2688/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002689static llvm::Value *emitReduceScratchpadFunction(
2690 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2691 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002692 ASTContext &C = CGM.getContext();
2693 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002694
2695 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002696 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2697 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002698 // Base address of the scratchpad array, with each element storing a
2699 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002700 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2701 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002702 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002703 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2704 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002705 // Row width of an element in the scratchpad array, typically
2706 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002707 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2708 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002709 // If should_reduce == 1, then it's load AND reduce,
2710 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2711 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002712 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2713 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002714
2715 FunctionArgList Args;
2716 Args.push_back(&ReduceListArg);
2717 Args.push_back(&ScratchPadArg);
2718 Args.push_back(&IndexArg);
2719 Args.push_back(&WidthArg);
2720 Args.push_back(&ShouldReduceArg);
2721
Alexey Bataev9ff80832018-04-16 20:16:21 +00002722 const CGFunctionInfo &CGFI =
2723 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002724 auto *Fn = llvm::Function::Create(
2725 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2726 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002727 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002728 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002729 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002730 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002731
Alexey Bataev9ff80832018-04-16 20:16:21 +00002732 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002733
2734 // Get local Reduce list pointer.
2735 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2736 Address ReduceListAddr(
2737 Bld.CreatePointerBitCastOrAddrSpaceCast(
2738 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002739 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002740 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2741 CGF.getPointerAlign());
2742
2743 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2744 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002745 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002746
2747 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002748 llvm::Value *IndexVal = Bld.CreateIntCast(
2749 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2750 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002751
2752 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002753 llvm::Value *WidthVal = Bld.CreateIntCast(
2754 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2755 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002756
2757 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2758 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002759 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002760
2761 // The absolute ptr address to the base addr of the next element to copy.
2762 llvm::Value *CumulativeElemBasePtr =
2763 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2764 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2765
2766 // Create a Remote Reduce list to store the elements read from the
2767 // scratchpad array.
2768 Address RemoteReduceList =
2769 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2770
2771 // Assemble remote Reduce list from scratchpad array.
2772 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2773 SrcDataAddr, RemoteReduceList,
2774 {/*RemoteLaneOffset=*/nullptr,
2775 /*ScratchpadIndex=*/IndexVal,
2776 /*ScratchpadWidth=*/WidthVal});
2777
2778 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2779 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2780 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2781
Alexey Bataev9ff80832018-04-16 20:16:21 +00002782 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002783 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2784
2785 CGF.EmitBlock(ThenBB);
2786 // We should reduce with the local Reduce list.
2787 // reduce_function(LocalReduceList, RemoteReduceList)
2788 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2789 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2790 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2791 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002792 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2793 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002794 Bld.CreateBr(MergeBB);
2795
2796 CGF.EmitBlock(ElseBB);
2797 // No reduction; just copy:
2798 // Local Reduce list = Remote Reduce list.
2799 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2800 RemoteReduceList, ReduceListAddr);
2801 Bld.CreateBr(MergeBB);
2802
2803 CGF.EmitBlock(MergeBB);
2804
2805 CGF.FinishFunction();
2806 return Fn;
2807}
2808
2809/// This function emits a helper that stores reduced data from the team
2810/// master to a scratchpad array in global memory.
2811///
2812/// for elem in Reduce List:
2813/// scratchpad[elem_id][index] = elem
2814///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002815static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2816 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002817 QualType ReductionArrayTy,
2818 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002819
Alexey Bataev9ff80832018-04-16 20:16:21 +00002820 ASTContext &C = CGM.getContext();
2821 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002822
2823 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002824 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2825 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002826 // Base address of the scratchpad array, with each element storing a
2827 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002828 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2829 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002830 // A destination index into the scratchpad array, typically the team
2831 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002832 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2833 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002834 // Row width of an element in the scratchpad array, typically
2835 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002836 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2837 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002838
2839 FunctionArgList Args;
2840 Args.push_back(&ReduceListArg);
2841 Args.push_back(&ScratchPadArg);
2842 Args.push_back(&IndexArg);
2843 Args.push_back(&WidthArg);
2844
Alexey Bataev9ff80832018-04-16 20:16:21 +00002845 const CGFunctionInfo &CGFI =
2846 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002847 auto *Fn = llvm::Function::Create(
2848 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2849 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002850 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002851 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002852 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002853 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002854
Alexey Bataev9ff80832018-04-16 20:16:21 +00002855 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002856
2857 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2858 Address SrcDataAddr(
2859 Bld.CreatePointerBitCastOrAddrSpaceCast(
2860 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002861 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002862 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2863 CGF.getPointerAlign());
2864
2865 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2866 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002867 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002868
2869 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002870 llvm::Value *IndexVal = Bld.CreateIntCast(
2871 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2872 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002873
2874 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2875 llvm::Value *WidthVal =
2876 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2877 Int32Ty, SourceLocation()),
2878 CGF.SizeTy, /*isSigned=*/true);
2879
2880 // The absolute ptr address to the base addr of the next element to copy.
2881 llvm::Value *CumulativeElemBasePtr =
2882 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2883 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2884
2885 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2886 SrcDataAddr, DestDataAddr,
2887 {/*RemoteLaneOffset=*/nullptr,
2888 /*ScratchpadIndex=*/IndexVal,
2889 /*ScratchpadWidth=*/WidthVal});
2890
2891 CGF.FinishFunction();
2892 return Fn;
2893}
2894
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002895/// This function emits a helper that gathers Reduce lists from the first
2896/// lane of every active warp to lanes in the first warp.
2897///
2898/// void inter_warp_copy_func(void* reduce_data, num_warps)
2899/// shared smem[warp_size];
2900/// For all data entries D in reduce_data:
2901/// If (I am the first lane in each warp)
2902/// Copy my local D to smem[warp_id]
2903/// sync
2904/// if (I am the first warp)
2905/// Copy smem[thread_id] to my local D
2906/// sync
2907static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2908 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002909 QualType ReductionArrayTy,
2910 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002911 ASTContext &C = CGM.getContext();
2912 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002913
2914 // ReduceList: thread local Reduce list.
2915 // At the stage of the computation when this function is called, partially
2916 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002917 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2918 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002919 // NumWarps: number of warps active in the parallel region. This could
2920 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002921 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002922 C.getIntTypeForBitwidth(32, /* Signed */ true),
2923 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002924 FunctionArgList Args;
2925 Args.push_back(&ReduceListArg);
2926 Args.push_back(&NumWarpsArg);
2927
Alexey Bataev9ff80832018-04-16 20:16:21 +00002928 const CGFunctionInfo &CGFI =
2929 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002930 auto *Fn = llvm::Function::Create(
2931 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2932 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002933 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002934 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002935 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002936 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937
Alexey Bataev9ff80832018-04-16 20:16:21 +00002938 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002939
2940 // This array is used as a medium to transfer, one reduce element at a time,
2941 // the data from the first lane of every warp to lanes in the first warp
2942 // in order to perform the final step of a reduction in a parallel region
2943 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2944 // for reduced latency, as well as to have a distinct copy for concurrently
2945 // executing target regions. The array is declared with common linkage so
2946 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002947 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002948 "__openmp_nvptx_data_transfer_temporary_storage";
2949 llvm::GlobalVariable *TransferMedium =
2950 M.getGlobalVariable(TransferMediumName);
2951 if (!TransferMedium) {
2952 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2953 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2954 TransferMedium = new llvm::GlobalVariable(
2955 M, Ty,
2956 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2957 llvm::Constant::getNullValue(Ty), TransferMediumName,
2958 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2959 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002960 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002961 }
2962
2963 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002964 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002965 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002966 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002967 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002968 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002969
2970 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2971 Address LocalReduceList(
2972 Bld.CreatePointerBitCastOrAddrSpaceCast(
2973 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2974 C.VoidPtrTy, SourceLocation()),
2975 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2976 CGF.getPointerAlign());
2977
2978 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002979 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002980 //
2981 // Warp master copies reduce element to transfer medium in __shared__
2982 // memory.
2983 //
2984 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2985 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2986 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2987
2988 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002989 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2991 CGF.EmitBlock(ThenBB);
2992
2993 // Reduce element = LocalReduceList[i]
2994 Address ElemPtrPtrAddr =
2995 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2996 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2997 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2998 // elemptr = (type[i]*)(elemptrptr)
2999 Address ElemPtr =
3000 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3001 ElemPtr = Bld.CreateElementBitCast(
3002 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003003
3004 // Get pointer to location in transfer medium.
3005 // MediumPtr = &medium[warp_id]
3006 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3007 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3008 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3009 // Casting to actual data type.
3010 // MediumPtr = (type[i]*)MediumPtrAddr;
3011 MediumPtr = Bld.CreateElementBitCast(
3012 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3013
Alexey Bataev12c62902018-06-22 19:10:38 +00003014 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003015 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003016 if (Private->getType()->isScalarType()) {
3017 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3018 Private->getType(), Loc);
3019 // Store the source element value to the dest element address.
3020 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3021 Private->getType());
3022 } else {
3023 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3024 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3025 Private->getType(), AggValueSlot::DoesNotOverlap);
3026 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003027
3028 Bld.CreateBr(MergeBB);
3029
3030 CGF.EmitBlock(ElseBB);
3031 Bld.CreateBr(MergeBB);
3032
3033 CGF.EmitBlock(MergeBB);
3034
3035 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3036 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3037 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3038
Alexey Bataev9ff80832018-04-16 20:16:21 +00003039 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003040 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3041 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3042 syncParallelThreads(CGF, NumActiveThreads);
3043
3044 //
3045 // Warp 0 copies reduce element from transfer medium.
3046 //
3047 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3048 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3049 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3050
3051 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003052 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003053 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3054 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3055
3056 CGF.EmitBlock(W0ThenBB);
3057
3058 // SrcMediumPtr = &medium[tid]
3059 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3060 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3061 Address SrcMediumPtr(SrcMediumPtrVal,
3062 C.getTypeAlignInChars(Private->getType()));
3063 // SrcMediumVal = *SrcMediumPtr;
3064 SrcMediumPtr = Bld.CreateElementBitCast(
3065 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003066
3067 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3068 Address TargetElemPtrPtr =
3069 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3070 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3071 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3072 Address TargetElemPtr =
3073 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3074 TargetElemPtr = Bld.CreateElementBitCast(
3075 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3076
3077 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003078 if (Private->getType()->isScalarType()) {
3079 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3080 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3081 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3082 Private->getType());
3083 } else {
3084 CGF.EmitAggregateCopy(
3085 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3086 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3087 Private->getType(), AggValueSlot::DoesNotOverlap);
3088 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003089 Bld.CreateBr(W0MergeBB);
3090
3091 CGF.EmitBlock(W0ElseBB);
3092 Bld.CreateBr(W0MergeBB);
3093
3094 CGF.EmitBlock(W0MergeBB);
3095
3096 // While warp 0 copies values from transfer medium, all other warps must
3097 // wait.
3098 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003099 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003100 }
3101
3102 CGF.FinishFunction();
3103 return Fn;
3104}
3105
3106/// Emit a helper that reduces data across two OpenMP threads (lanes)
3107/// in the same warp. It uses shuffle instructions to copy over data from
3108/// a remote lane's stack. The reduction algorithm performed is specified
3109/// by the fourth parameter.
3110///
3111/// Algorithm Versions.
3112/// Full Warp Reduce (argument value 0):
3113/// This algorithm assumes that all 32 lanes are active and gathers
3114/// data from these 32 lanes, producing a single resultant value.
3115/// Contiguous Partial Warp Reduce (argument value 1):
3116/// This algorithm assumes that only a *contiguous* subset of lanes
3117/// are active. This happens for the last warp in a parallel region
3118/// when the user specified num_threads is not an integer multiple of
3119/// 32. This contiguous subset always starts with the zeroth lane.
3120/// Partial Warp Reduce (argument value 2):
3121/// This algorithm gathers data from any number of lanes at any position.
3122/// All reduced values are stored in the lowest possible lane. The set
3123/// of problems every algorithm addresses is a super set of those
3124/// addressable by algorithms with a lower version number. Overhead
3125/// increases as algorithm version increases.
3126///
3127/// Terminology
3128/// Reduce element:
3129/// Reduce element refers to the individual data field with primitive
3130/// data types to be combined and reduced across threads.
3131/// Reduce list:
3132/// Reduce list refers to a collection of local, thread-private
3133/// reduce elements.
3134/// Remote Reduce list:
3135/// Remote Reduce list refers to a collection of remote (relative to
3136/// the current thread) reduce elements.
3137///
3138/// We distinguish between three states of threads that are important to
3139/// the implementation of this function.
3140/// Alive threads:
3141/// Threads in a warp executing the SIMT instruction, as distinguished from
3142/// threads that are inactive due to divergent control flow.
3143/// Active threads:
3144/// The minimal set of threads that has to be alive upon entry to this
3145/// function. The computation is correct iff active threads are alive.
3146/// Some threads are alive but they are not active because they do not
3147/// contribute to the computation in any useful manner. Turning them off
3148/// may introduce control flow overheads without any tangible benefits.
3149/// Effective threads:
3150/// In order to comply with the argument requirements of the shuffle
3151/// function, we must keep all lanes holding data alive. But at most
3152/// half of them perform value aggregation; we refer to this half of
3153/// threads as effective. The other half is simply handing off their
3154/// data.
3155///
3156/// Procedure
3157/// Value shuffle:
3158/// In this step active threads transfer data from higher lane positions
3159/// in the warp to lower lane positions, creating Remote Reduce list.
3160/// Value aggregation:
3161/// In this step, effective threads combine their thread local Reduce list
3162/// with Remote Reduce list and store the result in the thread local
3163/// Reduce list.
3164/// Value copy:
3165/// In this step, we deal with the assumption made by algorithm 2
3166/// (i.e. contiguity assumption). When we have an odd number of lanes
3167/// active, say 2k+1, only k threads will be effective and therefore k
3168/// new values will be produced. However, the Reduce list owned by the
3169/// (2k+1)th thread is ignored in the value aggregation. Therefore
3170/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3171/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003172static llvm::Value *emitShuffleAndReduceFunction(
3173 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3174 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176
3177 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003178 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3179 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003181 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3182 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003183 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003184 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3185 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003186 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003187 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3188 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189 FunctionArgList Args;
3190 Args.push_back(&ReduceListArg);
3191 Args.push_back(&LaneIDArg);
3192 Args.push_back(&RemoteLaneOffsetArg);
3193 Args.push_back(&AlgoVerArg);
3194
Alexey Bataev9ff80832018-04-16 20:16:21 +00003195 const CGFunctionInfo &CGFI =
3196 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003197 auto *Fn = llvm::Function::Create(
3198 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3199 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003200 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003201 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003202 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003203 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003204
Alexey Bataev9ff80832018-04-16 20:16:21 +00003205 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003206
3207 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3208 Address LocalReduceList(
3209 Bld.CreatePointerBitCastOrAddrSpaceCast(
3210 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3211 C.VoidPtrTy, SourceLocation()),
3212 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3213 CGF.getPointerAlign());
3214
3215 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3216 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3217 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3218
3219 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3220 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3221 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3222
3223 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3224 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3225 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3226
3227 // Create a local thread-private variable to host the Reduce list
3228 // from a remote lane.
3229 Address RemoteReduceList =
3230 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3231
3232 // This loop iterates through the list of reduce elements and copies,
3233 // element by element, from a remote lane in the warp to RemoteReduceList,
3234 // hosted on the thread's stack.
3235 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3236 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003237 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3238 /*ScratchpadIndex=*/nullptr,
3239 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003240
3241 // The actions to be performed on the Remote Reduce list is dependent
3242 // on the algorithm version.
3243 //
3244 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3245 // LaneId % 2 == 0 && Offset > 0):
3246 // do the reduction value aggregation
3247 //
3248 // The thread local variable Reduce list is mutated in place to host the
3249 // reduced data, which is the aggregated value produced from local and
3250 // remote lanes.
3251 //
3252 // Note that AlgoVer is expected to be a constant integer known at compile
3253 // time.
3254 // When AlgoVer==0, the first conjunction evaluates to true, making
3255 // the entire predicate true during compile time.
3256 // When AlgoVer==1, the second conjunction has only the second part to be
3257 // evaluated during runtime. Other conjunctions evaluates to false
3258 // during compile time.
3259 // When AlgoVer==2, the third conjunction has only the second part to be
3260 // evaluated during runtime. Other conjunctions evaluates to false
3261 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003262 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
Alexey Bataev9ff80832018-04-16 20:16:21 +00003264 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3265 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003266 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3267
Alexey Bataev9ff80832018-04-16 20:16:21 +00003268 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3269 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3270 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003271 CondAlgo2 = Bld.CreateAnd(
3272 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3273
Alexey Bataev9ff80832018-04-16 20:16:21 +00003274 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3276
3277 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3278 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3279 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3280 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3281
3282 CGF.EmitBlock(ThenBB);
3283 // reduce_function(LocalReduceList, RemoteReduceList)
3284 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3285 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3286 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3287 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003288 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3289 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003290 Bld.CreateBr(MergeBB);
3291
3292 CGF.EmitBlock(ElseBB);
3293 Bld.CreateBr(MergeBB);
3294
3295 CGF.EmitBlock(MergeBB);
3296
3297 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3298 // Reduce list.
3299 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003300 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003301 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3302
3303 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3304 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3305 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3306 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3307
3308 CGF.EmitBlock(CpyThenBB);
3309 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3310 RemoteReduceList, LocalReduceList);
3311 Bld.CreateBr(CpyMergeBB);
3312
3313 CGF.EmitBlock(CpyElseBB);
3314 Bld.CreateBr(CpyMergeBB);
3315
3316 CGF.EmitBlock(CpyMergeBB);
3317
3318 CGF.FinishFunction();
3319 return Fn;
3320}
3321
3322///
3323/// Design of OpenMP reductions on the GPU
3324///
3325/// Consider a typical OpenMP program with one or more reduction
3326/// clauses:
3327///
3328/// float foo;
3329/// double bar;
3330/// #pragma omp target teams distribute parallel for \
3331/// reduction(+:foo) reduction(*:bar)
3332/// for (int i = 0; i < N; i++) {
3333/// foo += A[i]; bar *= B[i];
3334/// }
3335///
3336/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3337/// all teams. In our OpenMP implementation on the NVPTX device an
3338/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3339/// within a team are mapped to CUDA threads within a threadblock.
3340/// Our goal is to efficiently aggregate values across all OpenMP
3341/// threads such that:
3342///
3343/// - the compiler and runtime are logically concise, and
3344/// - the reduction is performed efficiently in a hierarchical
3345/// manner as follows: within OpenMP threads in the same warp,
3346/// across warps in a threadblock, and finally across teams on
3347/// the NVPTX device.
3348///
3349/// Introduction to Decoupling
3350///
3351/// We would like to decouple the compiler and the runtime so that the
3352/// latter is ignorant of the reduction variables (number, data types)
3353/// and the reduction operators. This allows a simpler interface
3354/// and implementation while still attaining good performance.
3355///
3356/// Pseudocode for the aforementioned OpenMP program generated by the
3357/// compiler is as follows:
3358///
3359/// 1. Create private copies of reduction variables on each OpenMP
3360/// thread: 'foo_private', 'bar_private'
3361/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3362/// to it and writes the result in 'foo_private' and 'bar_private'
3363/// respectively.
3364/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3365/// and store the result on the team master:
3366///
3367/// __kmpc_nvptx_parallel_reduce_nowait(...,
3368/// reduceData, shuffleReduceFn, interWarpCpyFn)
3369///
3370/// where:
3371/// struct ReduceData {
3372/// double *foo;
3373/// double *bar;
3374/// } reduceData
3375/// reduceData.foo = &foo_private
3376/// reduceData.bar = &bar_private
3377///
3378/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3379/// auxiliary functions generated by the compiler that operate on
3380/// variables of type 'ReduceData'. They aid the runtime perform
3381/// algorithmic steps in a data agnostic manner.
3382///
3383/// 'shuffleReduceFn' is a pointer to a function that reduces data
3384/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3385/// same warp. It takes the following arguments as input:
3386///
3387/// a. variable of type 'ReduceData' on the calling lane,
3388/// b. its lane_id,
3389/// c. an offset relative to the current lane_id to generate a
3390/// remote_lane_id. The remote lane contains the second
3391/// variable of type 'ReduceData' that is to be reduced.
3392/// d. an algorithm version parameter determining which reduction
3393/// algorithm to use.
3394///
3395/// 'shuffleReduceFn' retrieves data from the remote lane using
3396/// efficient GPU shuffle intrinsics and reduces, using the
3397/// algorithm specified by the 4th parameter, the two operands
3398/// element-wise. The result is written to the first operand.
3399///
3400/// Different reduction algorithms are implemented in different
3401/// runtime functions, all calling 'shuffleReduceFn' to perform
3402/// the essential reduction step. Therefore, based on the 4th
3403/// parameter, this function behaves slightly differently to
3404/// cooperate with the runtime to ensure correctness under
3405/// different circumstances.
3406///
3407/// 'InterWarpCpyFn' is a pointer to a function that transfers
3408/// reduced variables across warps. It tunnels, through CUDA
3409/// shared memory, the thread-private data of type 'ReduceData'
3410/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003411/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3412/// The last team writes the global reduced value to memory.
3413///
3414/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3415/// reduceData, shuffleReduceFn, interWarpCpyFn,
3416/// scratchpadCopyFn, loadAndReduceFn)
3417///
3418/// 'scratchpadCopyFn' is a helper that stores reduced
3419/// data from the team master to a scratchpad array in
3420/// global memory.
3421///
3422/// 'loadAndReduceFn' is a helper that loads data from
3423/// the scratchpad array and reduces it with the input
3424/// operand.
3425///
3426/// These compiler generated functions hide address
3427/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428/// 5. if ret == 1:
3429/// The team master of the last team stores the reduced
3430/// result to the globals in memory.
3431/// foo += reduceData.foo; bar *= reduceData.bar
3432///
3433///
3434/// Warp Reduction Algorithms
3435///
3436/// On the warp level, we have three algorithms implemented in the
3437/// OpenMP runtime depending on the number of active lanes:
3438///
3439/// Full Warp Reduction
3440///
3441/// The reduce algorithm within a warp where all lanes are active
3442/// is implemented in the runtime as follows:
3443///
3444/// full_warp_reduce(void *reduce_data,
3445/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3446/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3447/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3448/// }
3449///
3450/// The algorithm completes in log(2, WARPSIZE) steps.
3451///
3452/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3453/// not used therefore we save instructions by not retrieving lane_id
3454/// from the corresponding special registers. The 4th parameter, which
3455/// represents the version of the algorithm being used, is set to 0 to
3456/// signify full warp reduction.
3457///
3458/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3459///
3460/// #reduce_elem refers to an element in the local lane's data structure
3461/// #remote_elem is retrieved from a remote lane
3462/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3463/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3464///
3465/// Contiguous Partial Warp Reduction
3466///
3467/// This reduce algorithm is used within a warp where only the first
3468/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3469/// number of OpenMP threads in a parallel region is not a multiple of
3470/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3471///
3472/// void
3473/// contiguous_partial_reduce(void *reduce_data,
3474/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3475/// int size, int lane_id) {
3476/// int curr_size;
3477/// int offset;
3478/// curr_size = size;
3479/// mask = curr_size/2;
3480/// while (offset>0) {
3481/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3482/// curr_size = (curr_size+1)/2;
3483/// offset = curr_size/2;
3484/// }
3485/// }
3486///
3487/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3488///
3489/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3490/// if (lane_id < offset)
3491/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3492/// else
3493/// reduce_elem = remote_elem
3494///
3495/// This algorithm assumes that the data to be reduced are located in a
3496/// contiguous subset of lanes starting from the first. When there is
3497/// an odd number of active lanes, the data in the last lane is not
3498/// aggregated with any other lane's dat but is instead copied over.
3499///
3500/// Dispersed Partial Warp Reduction
3501///
3502/// This algorithm is used within a warp when any discontiguous subset of
3503/// lanes are active. It is used to implement the reduction operation
3504/// across lanes in an OpenMP simd region or in a nested parallel region.
3505///
3506/// void
3507/// dispersed_partial_reduce(void *reduce_data,
3508/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3509/// int size, remote_id;
3510/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3511/// do {
3512/// remote_id = next_active_lane_id_right_after_me();
3513/// # the above function returns 0 of no active lane
3514/// # is present right after the current lane.
3515/// size = number_of_active_lanes_in_this_warp();
3516/// logical_lane_id /= 2;
3517/// ShuffleReduceFn(reduce_data, logical_lane_id,
3518/// remote_id-1-threadIdx.x, 2);
3519/// } while (logical_lane_id % 2 == 0 && size > 1);
3520/// }
3521///
3522/// There is no assumption made about the initial state of the reduction.
3523/// Any number of lanes (>=1) could be active at any position. The reduction
3524/// result is returned in the first active lane.
3525///
3526/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3527///
3528/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3529/// if (lane_id % 2 == 0 && offset > 0)
3530/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3531/// else
3532/// reduce_elem = remote_elem
3533///
3534///
3535/// Intra-Team Reduction
3536///
3537/// This function, as implemented in the runtime call
3538/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3539/// threads in a team. It first reduces within a warp using the
3540/// aforementioned algorithms. We then proceed to gather all such
3541/// reduced values at the first warp.
3542///
3543/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3544/// data from each of the "warp master" (zeroth lane of each warp, where
3545/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3546/// a mathematical sense) the problem of reduction across warp masters in
3547/// a block to the problem of warp reduction.
3548///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003549///
3550/// Inter-Team Reduction
3551///
3552/// Once a team has reduced its data to a single value, it is stored in
3553/// a global scratchpad array. Since each team has a distinct slot, this
3554/// can be done without locking.
3555///
3556/// The last team to write to the scratchpad array proceeds to reduce the
3557/// scratchpad array. One or more workers in the last team use the helper
3558/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3559/// the k'th worker reduces every k'th element.
3560///
3561/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3562/// reduce across workers and compute a globally reduced value.
3563///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003564void CGOpenMPRuntimeNVPTX::emitReduction(
3565 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3566 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3567 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3568 if (!CGF.HaveInsertPoint())
3569 return;
3570
3571 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003572 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003573 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3574 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003575 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003576
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003577 if (Options.SimpleReduction) {
3578 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3579 ReductionOps, Options);
3580 return;
3581 }
3582
Alexey Bataev9ff80832018-04-16 20:16:21 +00003583 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003584
3585 // 1. Build a list of reduction variables.
3586 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3587 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003588 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003589 if (E->getType()->isVariablyModifiedType())
3590 // Reserve place for array size.
3591 ++Size;
3592 }
3593 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3594 QualType ReductionArrayTy =
3595 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3596 /*IndexTypeQuals=*/0);
3597 Address ReductionList =
3598 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3599 auto IPriv = Privates.begin();
3600 unsigned Idx = 0;
3601 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3602 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3603 CGF.getPointerSize());
3604 CGF.Builder.CreateStore(
3605 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3606 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3607 Elem);
3608 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3609 // Store array size.
3610 ++Idx;
3611 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3612 CGF.getPointerSize());
3613 llvm::Value *Size = CGF.Builder.CreateIntCast(
3614 CGF.getVLASize(
3615 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003616 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003617 CGF.SizeTy, /*isSigned=*/false);
3618 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3619 Elem);
3620 }
3621 }
3622
3623 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003624 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003625 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3626 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003627
3628 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3629 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003630 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3631 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3632 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003633 ReductionList.getPointer(), CGF.VoidPtrTy);
3634
Alexey Bataev9ff80832018-04-16 20:16:21 +00003635 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003636 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003637 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003638 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003639
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003640 llvm::Value *Args[] = {ThreadId,
3641 CGF.Builder.getInt32(RHSExprs.size()),
3642 ReductionArrayTySize,
3643 RL,
3644 ShuffleAndReduceFn,
3645 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003646
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003647 llvm::Value *Res = nullptr;
3648 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003649 Res = CGF.EmitRuntimeCall(
3650 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3651 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003652 else if (SimdReduction)
3653 Res = CGF.EmitRuntimeCall(
3654 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3655 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003656
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003657 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003658 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003659 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003660 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003661 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003662
3663 llvm::Value *Args[] = {ThreadId,
3664 CGF.Builder.getInt32(RHSExprs.size()),
3665 ReductionArrayTySize,
3666 RL,
3667 ShuffleAndReduceFn,
3668 InterWarpCopyFn,
3669 ScratchPadCopyFn,
3670 LoadAndReduceFn};
3671 Res = CGF.EmitRuntimeCall(
3672 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3673 Args);
3674 }
3675
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003676 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003677 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3678 llvm::SwitchInst *SwInst =
3679 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003680
3681 // 6. Build case 1: where we have reduced values in the master
3682 // thread in each team.
3683 // __kmpc_end_reduce{_nowait}(<gtid>);
3684 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003685 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003686 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3687 CGF.EmitBlock(Case1BB);
3688
3689 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3690 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003691 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003692 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3693 auto IPriv = Privates.begin();
3694 auto ILHS = LHSExprs.begin();
3695 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003696 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003697 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3698 cast<DeclRefExpr>(*IRHS));
3699 ++IPriv;
3700 ++ILHS;
3701 ++IRHS;
3702 }
3703 };
3704 RegionCodeGenTy RCG(CodeGen);
3705 NVPTXActionTy Action(
3706 nullptr, llvm::None,
3707 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3708 EndArgs);
3709 RCG.setAction(Action);
3710 RCG(CGF);
3711 CGF.EmitBranch(DefaultBB);
3712 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3713}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003714
3715const VarDecl *
3716CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3717 const VarDecl *NativeParam) const {
3718 if (!NativeParam->getType()->isReferenceType())
3719 return NativeParam;
3720 QualType ArgType = NativeParam->getType();
3721 QualifierCollector QC;
3722 const Type *NonQualTy = QC.strip(ArgType);
3723 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3724 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3725 if (Attr->getCaptureKind() == OMPC_map) {
3726 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3727 LangAS::opencl_global);
3728 }
3729 }
3730 ArgType = CGM.getContext().getPointerType(PointeeTy);
3731 QC.addRestrict();
3732 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003733 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003734 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003735 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003736 return ImplicitParamDecl::Create(
3737 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3738 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003739 return ParmVarDecl::Create(
3740 CGM.getContext(),
3741 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003742 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003743 NativeParam->getIdentifier(), ArgType,
3744 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003745}
3746
3747Address
3748CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3749 const VarDecl *NativeParam,
3750 const VarDecl *TargetParam) const {
3751 assert(NativeParam != TargetParam &&
3752 NativeParam->getType()->isReferenceType() &&
3753 "Native arg must not be the same as target arg.");
3754 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3755 QualType NativeParamType = NativeParam->getType();
3756 QualifierCollector QC;
3757 const Type *NonQualTy = QC.strip(NativeParamType);
3758 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3759 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003760 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003761 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003762 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003763 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003764 // First cast to generic.
3765 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3766 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3767 /*AddrSpace=*/0));
3768 // Cast from generic to native address space.
3769 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3770 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3771 NativePointeeAddrSpace));
3772 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3773 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003774 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003775 return NativeParamAddr;
3776}
3777
3778void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003779 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003780 ArrayRef<llvm::Value *> Args) const {
3781 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003782 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003783 auto *FnType =
3784 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3785 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003786 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3787 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3788 break;
3789 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003790 llvm::Type *TargetType = FnType->getParamType(I);
3791 llvm::Value *NativeArg = Args[I];
3792 if (!TargetType->isPointerTy()) {
3793 TargetArgs.emplace_back(NativeArg);
3794 continue;
3795 }
3796 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003797 NativeArg,
3798 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003799 TargetArgs.emplace_back(
3800 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3801 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003802 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003803}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003804
3805/// Emit function which wraps the outline parallel region
3806/// and controls the arguments which are passed to this function.
3807/// The wrapper ensures that the outlined function is called
3808/// with the correct arguments when data is shared.
3809llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3810 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3811 ASTContext &Ctx = CGM.getContext();
3812 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3813
3814 // Create a function that takes as argument the source thread.
3815 FunctionArgList WrapperArgs;
3816 QualType Int16QTy =
3817 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3818 QualType Int32QTy =
3819 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003820 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003821 /*Id=*/nullptr, Int16QTy,
3822 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003823 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003824 /*Id=*/nullptr, Int32QTy,
3825 ImplicitParamDecl::Other);
3826 WrapperArgs.emplace_back(&ParallelLevelArg);
3827 WrapperArgs.emplace_back(&WrapperArg);
3828
Alexey Bataev9ff80832018-04-16 20:16:21 +00003829 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003830 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3831
3832 auto *Fn = llvm::Function::Create(
3833 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003834 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003835 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003836 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003837 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003838
3839 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3840 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003841 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003842
3843 const auto *RD = CS.getCapturedRecordDecl();
3844 auto CurField = RD->field_begin();
3845
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003846 Address ZeroAddr = CGF.CreateMemTemp(
3847 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3848 /*Name*/ ".zero.addr");
3849 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003850 // Get the array of arguments.
3851 SmallVector<llvm::Value *, 8> Args;
3852
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003853 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3854 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003855
3856 CGBuilderTy &Bld = CGF.Builder;
3857 auto CI = CS.capture_begin();
3858
3859 // Use global memory for data sharing.
3860 // Handle passing of global args to workers.
3861 Address GlobalArgs =
3862 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3863 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3864 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3865 CGF.EmitRuntimeCall(
3866 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3867 DataSharingArgs);
3868
3869 // Retrieve the shared variables from the list of references returned
3870 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003871 Address SharedArgListAddress = Address::invalid();
3872 if (CS.capture_size() > 0 ||
3873 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3874 SharedArgListAddress = CGF.EmitLoadOfPointer(
3875 GlobalArgs, CGF.getContext()
3876 .getPointerType(CGF.getContext().getPointerType(
3877 CGF.getContext().VoidPtrTy))
3878 .castAs<PointerType>());
3879 }
3880 unsigned Idx = 0;
3881 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3882 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3883 CGF.getPointerSize());
3884 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3885 Src, CGF.SizeTy->getPointerTo());
3886 llvm::Value *LB = CGF.EmitLoadOfScalar(
3887 TypedAddress,
3888 /*Volatile=*/false,
3889 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3890 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3891 Args.emplace_back(LB);
3892 ++Idx;
3893 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3894 CGF.getPointerSize());
3895 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3896 Src, CGF.SizeTy->getPointerTo());
3897 llvm::Value *UB = CGF.EmitLoadOfScalar(
3898 TypedAddress,
3899 /*Volatile=*/false,
3900 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3901 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3902 Args.emplace_back(UB);
3903 ++Idx;
3904 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003905 if (CS.capture_size() > 0) {
3906 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003907 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3908 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003909 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3910 CGF.getPointerSize());
3911 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003912 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3913 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3914 /*Volatile=*/false,
3915 CGFContext.getPointerType(ElemTy),
3916 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003917 if (CI->capturesVariableByCopy() &&
3918 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003919 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3920 CI->getLocation());
3921 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003922 Args.emplace_back(Arg);
3923 }
3924 }
3925
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003926 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003927 CGF.FinishFunction();
3928 return Fn;
3929}
3930
3931void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3932 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003933 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3934 return;
3935
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003936 assert(D && "Expected function or captured|block decl.");
3937 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3938 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003939 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003940 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003941 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3942 Body = FD->getBody();
3943 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3944 Body = BD->getBody();
3945 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3946 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003947 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003948 }
3949 if (!Body)
3950 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003951 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003952 VarChecker.Visit(Body);
3953 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003954 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3955 VarChecker.getEscapedVariableLengthDecls();
3956 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003957 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003958 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3959 I->getSecond().MappedParams =
3960 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3961 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3962 I->getSecond().EscapedParameters.insert(
3963 VarChecker.getEscapedParameters().begin(),
3964 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003965 I->getSecond().EscapedVariableLengthDecls.append(
3966 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003967 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003968 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003969 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003970 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003971 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3972 }
3973 if (!NeedToDelayGlobalization) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003974 emitGenericVarsProlog(CGF, D->getBeginLoc());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003975 struct GlobalizationScope final : EHScopeStack::Cleanup {
3976 GlobalizationScope() = default;
3977
3978 void Emit(CodeGenFunction &CGF, Flags flags) override {
3979 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3980 .emitGenericVarsEpilog(CGF);
3981 }
3982 };
3983 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003984 }
3985}
3986
3987Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3988 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003989 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3990 return Address::invalid();
3991
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003992 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003993 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3994 if (I == FunctionGlobalizedDecls.end())
3995 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003996 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003997 if (VDI != I->getSecond().LocalVarData.end())
3998 return VDI->second.second;
3999 if (VD->hasAttrs()) {
4000 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4001 E(VD->attr_end());
4002 IT != E; ++IT) {
4003 auto VDI = I->getSecond().LocalVarData.find(
4004 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4005 ->getCanonicalDecl());
4006 if (VDI != I->getSecond().LocalVarData.end())
4007 return VDI->second.second;
4008 }
4009 }
4010 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004011}
4012
4013void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004014 FunctionGlobalizedDecls.erase(CGF.CurFn);
4015 CGOpenMPRuntime::functionFinished(CGF);
4016}