blob: 9dce947e17a01234b1ce132018a5238dd281c1fc [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 Bataev80a9a612018-08-30 14:45:24 +00001221 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1222 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001223 llvm::Value *Args[] = {
1224 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1225 /*RequiresOMPRuntime=*/
1226 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1227 /*RequiresDataSharing=*/Bld.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001228 CGF.EmitRuntimeCall(
1229 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001230
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001231 if (RequiresFullRuntime) {
1232 // For data sharing, we need to initialize the stack.
1233 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1234 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1235 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001236
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001237 CGF.EmitBranch(ExecuteBB);
1238
1239 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001240
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001241 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001242}
1243
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001244void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001245 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001246 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001247 if (!CGF.HaveInsertPoint())
1248 return;
1249
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001250 if (!EST.ExitBB)
1251 EST.ExitBB = CGF.createBasicBlock(".exit");
1252
1253 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1254 CGF.EmitBranch(OMPDeInitBB);
1255
1256 CGF.EmitBlock(OMPDeInitBB);
1257 // DeInitialize the OMP state in the runtime; called by all active threads.
1258 CGF.EmitRuntimeCall(
1259 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1260 CGF.EmitBranch(EST.ExitBB);
1261
1262 CGF.EmitBlock(EST.ExitBB);
1263 EST.ExitBB = nullptr;
1264}
1265
1266// Create a unique global variable to indicate the execution mode of this target
1267// region. The execution mode is either 'generic', or 'spmd' depending on the
1268// target directive. This variable is picked up by the offload library to setup
1269// the device appropriately before kernel launch. If the execution mode is
1270// 'generic', the runtime reserves one warp for the master, otherwise, all
1271// warps participate in parallel work.
1272static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001273 bool Mode) {
1274 auto *GVMode =
1275 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1276 llvm::GlobalValue::WeakAnyLinkage,
1277 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1278 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001279 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001280}
1281
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001282void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001283 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001284
1285 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001286 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001287 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001288 emitWorkerLoop(CGF, WST);
1289 CGF.FinishFunction();
1290}
1291
1292void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1293 WorkerFunctionState &WST) {
1294 //
1295 // The workers enter this loop and wait for parallel work from the master.
1296 // When the master encounters a parallel region it sets up the work + variable
1297 // arguments, and wakes up the workers. The workers first check to see if
1298 // they are required for the parallel region, i.e., within the # of requested
1299 // parallel threads. The activated workers load the variable arguments and
1300 // execute the parallel work.
1301 //
1302
1303 CGBuilderTy &Bld = CGF.Builder;
1304
1305 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1306 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1307 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1308 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1309 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1310 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1311
1312 CGF.EmitBranch(AwaitBB);
1313
1314 // Workers wait for work from master.
1315 CGF.EmitBlock(AwaitBB);
1316 // Wait for parallel work
1317 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001318
1319 Address WorkFn =
1320 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1321 Address ExecStatus =
1322 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1323 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1324 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1325
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001326 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001327 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001328 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001329 llvm::Value *Ret = CGF.EmitRuntimeCall(
1330 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1331 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001332
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001333 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001334 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1335 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001336 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1337
1338 // Activate requested workers.
1339 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001340 llvm::Value *IsActive =
1341 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1342 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001343
1344 // Signal start of parallel region.
1345 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001346
1347 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001348 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001349 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001350 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001351
1352 llvm::Value *WorkFnMatch =
1353 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1354
1355 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1356 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1357 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1358
1359 // Execute this outlined function.
1360 CGF.EmitBlock(ExecuteFNBB);
1361
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001362 // Insert call to work function via shared wrapper. The shared
1363 // wrapper takes two arguments:
1364 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001365 // - the thread ID;
1366 emitCall(CGF, WST.Loc, W,
1367 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001368
1369 // Go to end of parallel region.
1370 CGF.EmitBranch(TerminateBB);
1371
1372 CGF.EmitBlock(CheckNextBB);
1373 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001374 // Default case: call to outlined function through pointer if the target
1375 // region makes a declare target call that may contain an orphaned parallel
1376 // directive.
1377 auto *ParallelFnTy =
1378 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1379 /*isVarArg=*/false)
1380 ->getPointerTo();
1381 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1382 // Insert call to work function via shared wrapper. The shared
1383 // wrapper takes two arguments:
1384 // - the parallelism level;
1385 // - the thread ID;
1386 emitCall(CGF, WST.Loc, WorkFnCast,
1387 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1388 // Go to end of parallel region.
1389 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001390
1391 // Signal end of parallel region.
1392 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001393 CGF.EmitRuntimeCall(
1394 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1395 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001396 CGF.EmitBranch(BarrierBB);
1397
1398 // All active and inactive workers wait at a barrier after parallel region.
1399 CGF.EmitBlock(BarrierBB);
1400 // Barrier after parallel region.
1401 syncCTAThreads(CGF);
1402 CGF.EmitBranch(AwaitBB);
1403
1404 // Exit target region.
1405 CGF.EmitBlock(ExitBB);
1406}
1407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001408/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001409/// implementation. Specialized for the NVPTX device.
1410/// \param Function OpenMP runtime function.
1411/// \return Specified function.
1412llvm::Constant *
1413CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1414 llvm::Constant *RTLFn = nullptr;
1415 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1416 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001417 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1418 // RequiresOMPRuntime);
1419 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001420 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001421 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1423 break;
1424 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001425 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001426 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1427 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001428 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001429 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001430 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1431 break;
1432 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001433 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1434 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001435 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001436 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001437 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001438 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1439 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1440 break;
1441 }
1442 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1443 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001444 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001445 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1446 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1447 break;
1448 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001449 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1450 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001451 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001452 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001453 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001454 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1455 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1456 break;
1457 }
1458 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001459 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1460 /// int16_t IsOMPRuntimeInitialized);
1461 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001462 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001463 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001464 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1466 break;
1467 }
1468 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1469 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001470 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001471 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1472 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1473 break;
1474 }
1475 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1476 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1477 // global_tid);
1478 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001479 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001480 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1481 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1482 break;
1483 }
1484 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1485 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1486 // global_tid);
1487 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001488 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001489 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1491 break;
1492 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001493 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1494 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1495 // int16_t lane_offset, int16_t warp_size);
1496 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001497 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001498 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1499 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1500 break;
1501 }
1502 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1503 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1504 // int16_t lane_offset, int16_t warp_size);
1505 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001506 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001507 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1508 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1509 break;
1510 }
1511 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1512 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1513 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1514 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1515 // lane_offset, int16_t Algorithm Version),
1516 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1517 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1518 CGM.Int16Ty, CGM.Int16Ty};
1519 auto *ShuffleReduceFnTy =
1520 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1521 /*isVarArg=*/false);
1522 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1523 auto *InterWarpCopyFnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1525 /*isVarArg=*/false);
1526 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1527 CGM.Int32Ty,
1528 CGM.SizeTy,
1529 CGM.VoidPtrTy,
1530 ShuffleReduceFnTy->getPointerTo(),
1531 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001532 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001533 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1534 RTLFn = CGM.CreateRuntimeFunction(
1535 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1536 break;
1537 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001538 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1539 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1540 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1541 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1542 // lane_offset, int16_t Algorithm Version),
1543 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1544 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1545 CGM.Int16Ty, CGM.Int16Ty};
1546 auto *ShuffleReduceFnTy =
1547 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1548 /*isVarArg=*/false);
1549 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1550 auto *InterWarpCopyFnTy =
1551 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1552 /*isVarArg=*/false);
1553 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1554 CGM.Int32Ty,
1555 CGM.SizeTy,
1556 CGM.VoidPtrTy,
1557 ShuffleReduceFnTy->getPointerTo(),
1558 InterWarpCopyFnTy->getPointerTo()};
1559 auto *FnTy =
1560 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1561 RTLFn = CGM.CreateRuntimeFunction(
1562 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1563 break;
1564 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001565 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1566 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1567 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1568 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1569 // lane_offset, int16_t shortCircuit),
1570 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1571 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1572 // int32_t index, int32_t width),
1573 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1574 // int32_t index, int32_t width, int32_t reduce))
1575 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1576 CGM.Int16Ty, CGM.Int16Ty};
1577 auto *ShuffleReduceFnTy =
1578 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1579 /*isVarArg=*/false);
1580 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1581 auto *InterWarpCopyFnTy =
1582 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1583 /*isVarArg=*/false);
1584 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1585 CGM.Int32Ty, CGM.Int32Ty};
1586 auto *CopyToScratchpadFnTy =
1587 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1588 /*isVarArg=*/false);
1589 llvm::Type *LoadReduceTypeParams[] = {
1590 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1591 auto *LoadReduceFnTy =
1592 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1593 /*isVarArg=*/false);
1594 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1595 CGM.Int32Ty,
1596 CGM.SizeTy,
1597 CGM.VoidPtrTy,
1598 ShuffleReduceFnTy->getPointerTo(),
1599 InterWarpCopyFnTy->getPointerTo(),
1600 CopyToScratchpadFnTy->getPointerTo(),
1601 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001602 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001603 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1604 RTLFn = CGM.CreateRuntimeFunction(
1605 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1606 break;
1607 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001608 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1609 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1610 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001611 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1613 RTLFn = CGM.CreateRuntimeFunction(
1614 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1615 break;
1616 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001617 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1618 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001619 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001620 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1622 break;
1623 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001624 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1625 /// Build void __kmpc_data_sharing_init_stack_spmd();
1626 auto *FnTy =
1627 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001628 RTLFn =
1629 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001630 break;
1631 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001632 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1633 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1634 // int16_t UseSharedMemory);
1635 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001636 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001637 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1638 RTLFn = CGM.CreateRuntimeFunction(
1639 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1640 break;
1641 }
1642 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1643 // Build void __kmpc_data_sharing_pop_stack(void *a);
1644 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001645 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001646 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1648 /*Name=*/"__kmpc_data_sharing_pop_stack");
1649 break;
1650 }
1651 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1652 /// Build void __kmpc_begin_sharing_variables(void ***args,
1653 /// size_t n_args);
1654 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001655 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1658 break;
1659 }
1660 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1661 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001662 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001663 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1664 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1665 break;
1666 }
1667 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1668 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1669 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001670 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001671 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1672 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1673 break;
1674 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001675 case OMPRTL_NVPTX__kmpc_parallel_level: {
1676 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1677 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1678 auto *FnTy =
1679 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1680 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1681 break;
1682 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001683 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1684 // Build int8_t __kmpc_is_spmd_exec_mode();
1685 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1686 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1687 break;
1688 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001689 }
1690 return RTLFn;
1691}
1692
1693void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1694 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001695 uint64_t Size, int32_t,
1696 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001697 // TODO: Add support for global variables on the device after declare target
1698 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001699 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001700 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001701 llvm::Module &M = CGM.getModule();
1702 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001703
1704 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001705 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001706
1707 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001708 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001709 llvm::ConstantAsMetadata::get(
1710 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1711 // Append metadata to nvvm.annotations
1712 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1713}
1714
1715void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1716 const OMPExecutableDirective &D, StringRef ParentName,
1717 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001718 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001719 if (!IsOffloadEntry) // Nothing to do.
1720 return;
1721
1722 assert(!ParentName.empty() && "Invalid target region parent name!");
1723
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001724 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001725 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001726 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001727 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001728 else
1729 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1730 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001731
1732 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001733}
1734
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001735CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001736 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001737 if (!CGM.getLangOpts().OpenMPIsDevice)
1738 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001739}
Carlo Bertollic6872252016-04-04 15:55:02 +00001740
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001741void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1742 OpenMPProcBindClauseKind ProcBind,
1743 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001744 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001745 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001746 return;
1747
1748 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1749}
1750
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001751void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1752 llvm::Value *NumThreads,
1753 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001754 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001755 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001756 return;
1757
1758 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1759}
1760
Carlo Bertollic6872252016-04-04 15:55:02 +00001761void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1762 const Expr *NumTeams,
1763 const Expr *ThreadLimit,
1764 SourceLocation Loc) {}
1765
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001766llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1767 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1768 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001769 // Emit target region as a standalone region.
1770 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001771 bool &IsInParallelRegion;
1772 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001773
1774 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001775 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1776 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001777 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001778 PrevIsInParallelRegion = IsInParallelRegion;
1779 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001780 }
1781 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001782 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001783 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001784 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001785 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001786 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1787 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001788 auto *OutlinedFun =
1789 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1790 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001791 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001792 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1793 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001794 llvm::Function *WrapperFun =
1795 createParallelDataSharingWrapper(OutlinedFun, D);
1796 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1797 }
1798
1799 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001800}
1801
1802llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001803 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1804 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001805 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001806
Alexey Bataevc99042b2018-03-15 18:10:54 +00001807 // Emit target region as a standalone region.
1808 class NVPTXPrePostActionTy : public PrePostActionTy {
1809 SourceLocation &Loc;
1810
1811 public:
1812 NVPTXPrePostActionTy(SourceLocation &Loc) : Loc(Loc) {}
1813 void Enter(CodeGenFunction &CGF) override {
1814 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1815 .emitGenericVarsProlog(CGF, Loc);
1816 }
1817 void Exit(CodeGenFunction &CGF) override {
1818 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1819 .emitGenericVarsEpilog(CGF);
1820 }
1821 } Action(Loc);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001822 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1823 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001824 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1825 D, ThreadIDVar, InnermostKind, CodeGen);
1826 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1827 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001828 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001829 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001830
1831 return OutlinedFun;
1832}
1833
Alexey Bataevc99042b2018-03-15 18:10:54 +00001834void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
1835 SourceLocation Loc) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001836 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1837 return;
1838
Alexey Bataevc99042b2018-03-15 18:10:54 +00001839 CGBuilderTy &Bld = CGF.Builder;
1840
1841 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1842 if (I == FunctionGlobalizedDecls.end())
1843 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001844 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1845 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001846
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001847 // Recover pointer to this function's global record. The runtime will
1848 // handle the specifics of the allocation of the memory.
1849 // Use actual memory size of the record including the padding
1850 // for alignment purposes.
1851 unsigned Alignment =
1852 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1853 unsigned GlobalRecordSize =
1854 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1855 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001856
1857 llvm::Value *GlobalRecCastAddr;
1858 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
1859 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1860 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1861 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1862 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1863 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1864 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1865 // There is no need to emit line number for unconditional branch.
1866 (void)ApplyDebugLocation::CreateEmpty(CGF);
1867 CGF.EmitBlock(SPMDBB);
1868 Address RecPtr = CGF.CreateMemTemp(RecTy, "_local_stack");
1869 CGF.EmitBranch(ExitBB);
1870 // There is no need to emit line number for unconditional branch.
1871 (void)ApplyDebugLocation::CreateEmpty(CGF);
1872 CGF.EmitBlock(NonSPMDBB);
1873 // TODO: allow the usage of shared memory to be controlled by
1874 // the user, for now, default to global.
1875 llvm::Value *GlobalRecordSizeArg[] = {
1876 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1877 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1878 llvm::Value *GlobalRecValue =
1879 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1880 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1881 GlobalRecordSizeArg);
1882 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1883 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1884 CGF.EmitBlock(ExitBB);
1885 auto *Phi = Bld.CreatePHI(GlobalRecCastAddr->getType(),
1886 /*NumReservedValues=*/2, "_select_stack");
1887 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
1888 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
1889 GlobalRecCastAddr = Phi;
1890 I->getSecond().GlobalRecordAddr = Phi;
1891 I->getSecond().IsInSPMDModeFlag = IsSPMD;
1892 } else {
1893 assert(getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD &&
1894 "Expected Non-SPMD construct.");
1895 // TODO: allow the usage of shared memory to be controlled by
1896 // the user, for now, default to global.
1897 llvm::Value *GlobalRecordSizeArg[] = {
1898 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1899 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1900 llvm::Value *GlobalRecValue =
1901 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1902 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1903 GlobalRecordSizeArg);
1904 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1905 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1906 I->getSecond().GlobalRecordAddr = GlobalRecValue;
1907 I->getSecond().IsInSPMDModeFlag = nullptr;
1908 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001909 LValue Base =
1910 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001911
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001912 // Emit the "global alloca" which is a GEP from the global declaration
1913 // record using the pointer returned by the runtime.
1914 for (auto &Rec : I->getSecond().LocalVarData) {
1915 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1916 llvm::Value *ParValue;
1917 if (EscapedParam) {
1918 const auto *VD = cast<VarDecl>(Rec.first);
1919 LValue ParLVal =
1920 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1921 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1922 }
1923 const FieldDecl *FD = Rec.second.first;
1924 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
1925 Rec.second.second = VarAddr.getAddress();
1926 if (EscapedParam) {
1927 const auto *VD = cast<VarDecl>(Rec.first);
1928 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1929 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1930 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00001931 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001932 }
1933 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1934 // Recover pointer to this function's global record. The runtime will
1935 // handle the specifics of the allocation of the memory.
1936 // Use actual memory size of the record including the padding
1937 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001938 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001939 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1940 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1941 Size = Bld.CreateNUWAdd(
1942 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1943 llvm::Value *AlignVal =
1944 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1945 Size = Bld.CreateUDiv(Size, AlignVal);
1946 Size = Bld.CreateNUWMul(Size, AlignVal);
1947 // TODO: allow the usage of shared memory to be controlled by
1948 // the user, for now, default to global.
1949 llvm::Value *GlobalRecordSizeArg[] = {
1950 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1951 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1952 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1953 GlobalRecordSizeArg);
1954 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1955 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1956 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1957 CGM.getContext().getDeclAlign(VD),
1958 AlignmentSource::Decl);
1959 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1960 Base.getAddress());
1961 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001962 }
1963 I->getSecond().MappedParams->apply(CGF);
1964}
1965
1966void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001967 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
1968 return;
1969
Alexey Bataevc99042b2018-03-15 18:10:54 +00001970 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001971 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001972 I->getSecond().MappedParams->restore(CGF);
1973 if (!CGF.HaveInsertPoint())
1974 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001975 for (llvm::Value *Addr :
1976 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1977 CGF.EmitRuntimeCall(
1978 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1979 Addr);
1980 }
1981 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001982 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
1983 CGBuilderTy &Bld = CGF.Builder;
1984 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1985 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1986 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
1987 // There is no need to emit line number for unconditional branch.
1988 (void)ApplyDebugLocation::CreateEmpty(CGF);
1989 CGF.EmitBlock(NonSPMDBB);
1990 CGF.EmitRuntimeCall(
1991 createNVPTXRuntimeFunction(
1992 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
1993 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
1994 CGF.EmitBlock(ExitBB);
1995 } else {
1996 assert(getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD &&
1997 "Expected Non-SPMD mode.");
1998 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1999 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2000 I->getSecond().GlobalRecordAddr);
2001 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002002 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002003 }
2004}
2005
Carlo Bertollic6872252016-04-04 15:55:02 +00002006void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2007 const OMPExecutableDirective &D,
2008 SourceLocation Loc,
2009 llvm::Value *OutlinedFn,
2010 ArrayRef<llvm::Value *> CapturedVars) {
2011 if (!CGF.HaveInsertPoint())
2012 return;
2013
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002014 Address ZeroAddr = CGF.CreateMemTemp(
2015 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2016 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002017 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2018 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002019 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002020 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2021 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002022 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002023}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002024
2025void CGOpenMPRuntimeNVPTX::emitParallelCall(
2026 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2027 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2028 if (!CGF.HaveInsertPoint())
2029 return;
2030
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002031 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002032 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002033 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002034 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002035}
2036
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002037void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002038 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2039 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2040 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002041
2042 // Force inline this outlined function at its call site.
2043 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2044
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002045 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2046 /*DestWidth=*/32, /*Signed=*/1),
2047 ".zero.addr");
2048 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002049 // ThreadId for serialized parallels is 0.
2050 Address ThreadIDAddr = ZeroAddr;
2051 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002052 CodeGenFunction &CGF, PrePostActionTy &Action) {
2053 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002054
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002055 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2056 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2057 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2058 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2059 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2060 };
2061 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2062 PrePostActionTy &) {
2063
2064 RegionCodeGenTy RCG(CodeGen);
2065 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2066 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2067 llvm::Value *Args[] = {RTLoc, ThreadID};
2068
2069 NVPTXActionTy Action(
2070 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2071 Args,
2072 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2073 Args);
2074 RCG.setAction(Action);
2075 RCG(CGF);
2076 };
2077
2078 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2079 PrePostActionTy &Action) {
2080 CGBuilderTy &Bld = CGF.Builder;
2081 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2082 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002083 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2084
2085 // Prepare for parallel region. Indicate the outlined function.
2086 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002087 CGF.EmitRuntimeCall(
2088 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2089 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002090
2091 // Create a private scope that will globalize the arguments
2092 // passed from the outside of the target region.
2093 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2094
2095 // There's somehting to share.
2096 if (!CapturedVars.empty()) {
2097 // Prepare for parallel region. Indicate the outlined function.
2098 Address SharedArgs =
2099 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2100 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2101
2102 llvm::Value *DataSharingArgs[] = {
2103 SharedArgsPtr,
2104 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2105 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2106 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2107 DataSharingArgs);
2108
2109 // Store variable address in a list of references to pass to workers.
2110 unsigned Idx = 0;
2111 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002112 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2113 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2114 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002115 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002116 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2117 CGF.getPointerSize());
2118 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002119 if (V->getType()->isIntegerTy())
2120 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2121 else
2122 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002123 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2124 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002125 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002126 }
2127 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002128
2129 // Activate workers. This barrier is used by the master to signal
2130 // work for the workers.
2131 syncCTAThreads(CGF);
2132
2133 // OpenMP [2.5, Parallel Construct, p.49]
2134 // There is an implied barrier at the end of a parallel region. After the
2135 // end of a parallel region, only the master thread of the team resumes
2136 // execution of the enclosing task region.
2137 //
2138 // The master waits at this barrier until all workers are done.
2139 syncCTAThreads(CGF);
2140
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002141 if (!CapturedVars.empty())
2142 CGF.EmitRuntimeCall(
2143 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2144
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002145 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002146 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002147 };
2148
Alexey Bataev8521ff62018-07-25 20:03:01 +00002149 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen, &CodeGen,
2150 &ThreadIDAddr](CodeGenFunction &CGF,
2151 PrePostActionTy &Action) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002152 RegionCodeGenTy RCG(CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002153 if (IsInParallelRegion) {
2154 SeqGen(CGF, Action);
2155 } else if (IsInTargetMasterThreadRegion) {
2156 L0ParallelGen(CGF, Action);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002157 } else if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_NonSPMD) {
2158 RCG(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002159 } else {
2160 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002161 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Alexey Bataev673110d2018-05-16 13:36:30 +00002162 // Serialized execution.
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002163 // } else if (master) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002164 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002165 // } else {
2166 // Outlined function call.
2167 // }
2168 CGBuilderTy &Bld = CGF.Builder;
2169 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002170 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2171 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002172 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
Alexey Bataev673110d2018-05-16 13:36:30 +00002173 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2174 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002175 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002176 // There is no need to emit line number for unconditional branch.
2177 (void)ApplyDebugLocation::CreateEmpty(CGF);
2178 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002179 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2180 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2181 llvm::Value *PL = CGF.EmitRuntimeCall(
2182 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2183 {RTLoc, ThreadID});
2184 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002185 Bld.CreateCondBr(Res, SeqBB, MasterCheckBB);
2186 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002187 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002188 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002189 // There is no need to emit line number for unconditional branch.
2190 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002191 CGF.EmitBlock(MasterCheckBB);
2192 llvm::BasicBlock *MasterThenBB = CGF.createBasicBlock("master.then");
2193 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2194 llvm::Value *IsMaster =
2195 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
2196 Bld.CreateCondBr(IsMaster, MasterThenBB, ElseBlock);
2197 CGF.EmitBlock(MasterThenBB);
2198 L0ParallelGen(CGF, Action);
2199 CGF.EmitBranch(ExitBB);
2200 // There is no need to emit line number for unconditional branch.
2201 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002202 CGF.EmitBlock(ElseBlock);
Alexey Bataev8521ff62018-07-25 20:03:01 +00002203 // In the worker need to use the real thread id.
2204 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002205 RCG(CGF);
2206 // There is no need to emit line number for unconditional branch.
2207 (void)ApplyDebugLocation::CreateEmpty(CGF);
2208 // Emit the continuation block for code after the if.
2209 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2210 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002211 };
2212
Alexey Bataev9ff80832018-04-16 20:16:21 +00002213 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002214 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002215 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002216 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002217 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002218 ThenRCG(CGF);
2219 }
2220}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002221
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002222void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002223 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2224 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2225 // Just call the outlined function to execute the parallel region.
2226 // OutlinedFn(&GTid, &zero, CapturedStruct);
2227 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002228 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002229
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002230 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2231 /*DestWidth=*/32, /*Signed=*/1),
2232 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002233 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002234 // ThreadId for serialized parallels is 0.
2235 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002236 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002237 &ThreadIDAddr](CodeGenFunction &CGF,
2238 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002239 Action.Enter(CGF);
2240
2241 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2242 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2243 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2244 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2245 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2246 };
2247 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2248 PrePostActionTy &) {
2249
2250 RegionCodeGenTy RCG(CodeGen);
2251 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2252 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2253 llvm::Value *Args[] = {RTLoc, ThreadID};
2254
2255 NVPTXActionTy Action(
2256 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2257 Args,
2258 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2259 Args);
2260 RCG.setAction(Action);
2261 RCG(CGF);
2262 };
2263
2264 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002265 // In the worker need to use the real thread id.
2266 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002267 RegionCodeGenTy RCG(CodeGen);
2268 RCG(CGF);
2269 } else {
2270 // If we are not in the target region, it is definitely L2 parallelism or
2271 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2272 // need to check for orphaned directives.
2273 RegionCodeGenTy RCG(SeqGen);
2274 RCG(CGF);
2275 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002276}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002277
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002278void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2279 CodeGenFunction &CGF, StringRef CriticalName,
2280 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2281 const Expr *Hint) {
2282 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2283 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2284 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2285 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2286 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2287
2288 // Fetch team-local id of the thread.
2289 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2290
2291 // Get the width of the team.
2292 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2293
2294 // Initialize the counter variable for the loop.
2295 QualType Int32Ty =
2296 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2297 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2298 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2299 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2300 /*isInit=*/true);
2301
2302 // Block checks if loop counter exceeds upper bound.
2303 CGF.EmitBlock(LoopBB);
2304 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2305 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2306 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2307
2308 // Block tests which single thread should execute region, and which threads
2309 // should go straight to synchronisation point.
2310 CGF.EmitBlock(TestBB);
2311 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2312 llvm::Value *CmpThreadToCounter =
2313 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2314 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2315
2316 // Block emits the body of the critical region.
2317 CGF.EmitBlock(BodyBB);
2318
2319 // Output the critical statement.
2320 CriticalOpGen(CGF);
2321
2322 // After the body surrounded by the critical region, the single executing
2323 // thread will jump to the synchronisation point.
2324 // Block waits for all threads in current team to finish then increments the
2325 // counter variable and returns to the loop.
2326 CGF.EmitBlock(SyncBB);
2327 getNVPTXCTABarrier(CGF);
2328
2329 llvm::Value *IncCounterVal =
2330 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2331 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2332 CGF.EmitBranch(LoopBB);
2333
2334 // Block that is reached when all threads in the team complete the region.
2335 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2336}
2337
Alexey Bataevb2575932018-01-04 20:18:55 +00002338/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002339static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2340 QualType ValTy, QualType CastTy,
2341 SourceLocation Loc) {
2342 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2343 "Cast type must sized.");
2344 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2345 "Val type must sized.");
2346 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2347 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002348 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002349 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2350 CGF.getContext().getTypeSizeInChars(CastTy))
2351 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2352 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2353 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2354 CastTy->hasSignedIntegerRepresentation());
2355 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002356 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2357 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002358 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2359 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002360}
2361
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002362/// This function creates calls to one of two shuffle functions to copy
2363/// variables between lanes in a warp.
2364static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002365 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002366 QualType ElemType,
2367 llvm::Value *Offset,
2368 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002369 CodeGenModule &CGM = CGF.CGM;
2370 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002371 CGOpenMPRuntimeNVPTX &RT =
2372 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2373
Alexey Bataeva453f362018-03-19 17:53:56 +00002374 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2375 assert(Size.getQuantity() <= 8 &&
2376 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002377
Alexey Bataeva453f362018-03-19 17:53:56 +00002378 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002379 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2380 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2381
2382 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002383 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2384 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2385 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002386 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002387 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002388
Alexey Bataev9ff80832018-04-16 20:16:21 +00002389 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2390 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002391
Alexey Bataeva453f362018-03-19 17:53:56 +00002392 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002393}
2394
Alexey Bataev12c62902018-06-22 19:10:38 +00002395static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2396 Address DestAddr, QualType ElemType,
2397 llvm::Value *Offset, SourceLocation Loc) {
2398 CGBuilderTy &Bld = CGF.Builder;
2399
2400 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2401 // Create the loop over the big sized data.
2402 // ptr = (void*)Elem;
2403 // ptrEnd = (void*) Elem + 1;
2404 // Step = 8;
2405 // while (ptr + Step < ptrEnd)
2406 // shuffle((int64_t)*ptr);
2407 // Step = 4;
2408 // while (ptr + Step < ptrEnd)
2409 // shuffle((int32_t)*ptr);
2410 // ...
2411 Address ElemPtr = DestAddr;
2412 Address Ptr = SrcAddr;
2413 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2414 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2415 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2416 if (Size < CharUnits::fromQuantity(IntSize))
2417 continue;
2418 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2419 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2420 /*Signed=*/1);
2421 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2422 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2423 ElemPtr =
2424 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2425 if (Size.getQuantity() / IntSize > 1) {
2426 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2427 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2428 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2429 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2430 CGF.EmitBlock(PreCondBB);
2431 llvm::PHINode *PhiSrc =
2432 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2433 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2434 llvm::PHINode *PhiDest =
2435 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2436 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2437 Ptr = Address(PhiSrc, Ptr.getAlignment());
2438 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2439 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2440 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2441 Ptr.getPointer(), CGF.VoidPtrTy));
2442 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2443 ThenBB, ExitBB);
2444 CGF.EmitBlock(ThenBB);
2445 llvm::Value *Res = createRuntimeShuffleFunction(
2446 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2447 IntType, Offset, Loc);
2448 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2449 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2450 ElemPtr =
2451 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2452 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2453 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2454 CGF.EmitBranch(PreCondBB);
2455 CGF.EmitBlock(ExitBB);
2456 } else {
2457 llvm::Value *Res = createRuntimeShuffleFunction(
2458 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2459 IntType, Offset, Loc);
2460 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2461 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2462 ElemPtr =
2463 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2464 }
2465 Size = Size % IntSize;
2466 }
2467}
2468
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002469namespace {
2470enum CopyAction : unsigned {
2471 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2472 // the warp using shuffle instructions.
2473 RemoteLaneToThread,
2474 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2475 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002476 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2477 ThreadToScratchpad,
2478 // ScratchpadToThread: Copy from a scratchpad array in global memory
2479 // containing team-reduced data to a thread's stack.
2480 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002481};
2482} // namespace
2483
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002484struct CopyOptionsTy {
2485 llvm::Value *RemoteLaneOffset;
2486 llvm::Value *ScratchpadIndex;
2487 llvm::Value *ScratchpadWidth;
2488};
2489
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002490/// Emit instructions to copy a Reduce list, which contains partially
2491/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002492static void emitReductionListCopy(
2493 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2494 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2495 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002496
Alexey Bataev9ff80832018-04-16 20:16:21 +00002497 CodeGenModule &CGM = CGF.CGM;
2498 ASTContext &C = CGM.getContext();
2499 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002500
Alexey Bataev9ff80832018-04-16 20:16:21 +00002501 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2502 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2503 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002504
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002505 // Iterates, element-by-element, through the source Reduce list and
2506 // make a copy.
2507 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002508 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002509 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002510 Address SrcElementAddr = Address::invalid();
2511 Address DestElementAddr = Address::invalid();
2512 Address DestElementPtrAddr = Address::invalid();
2513 // Should we shuffle in an element from a remote lane?
2514 bool ShuffleInElement = false;
2515 // Set to true to update the pointer in the dest Reduce list to a
2516 // newly created element.
2517 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002518 // Increment the src or dest pointer to the scratchpad, for each
2519 // new element.
2520 bool IncrScratchpadSrc = false;
2521 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002522
2523 switch (Action) {
2524 case RemoteLaneToThread: {
2525 // Step 1.1: Get the address for the src element in the Reduce list.
2526 Address SrcElementPtrAddr =
2527 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002528 SrcElementAddr = CGF.EmitLoadOfPointer(
2529 SrcElementPtrAddr,
2530 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002531
2532 // Step 1.2: Create a temporary to store the element in the destination
2533 // Reduce list.
2534 DestElementPtrAddr =
2535 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2536 DestElementAddr =
2537 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2538 ShuffleInElement = true;
2539 UpdateDestListPtr = true;
2540 break;
2541 }
2542 case ThreadCopy: {
2543 // Step 1.1: Get the address for the src element in the Reduce list.
2544 Address SrcElementPtrAddr =
2545 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002546 SrcElementAddr = CGF.EmitLoadOfPointer(
2547 SrcElementPtrAddr,
2548 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002549
2550 // Step 1.2: Get the address for dest element. The destination
2551 // element has already been created on the thread's stack.
2552 DestElementPtrAddr =
2553 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002554 DestElementAddr = CGF.EmitLoadOfPointer(
2555 DestElementPtrAddr,
2556 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002557 break;
2558 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002559 case ThreadToScratchpad: {
2560 // Step 1.1: Get the address for the src element in the Reduce list.
2561 Address SrcElementPtrAddr =
2562 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002563 SrcElementAddr = CGF.EmitLoadOfPointer(
2564 SrcElementPtrAddr,
2565 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002566
2567 // Step 1.2: Get the address for dest element:
2568 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002569 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002570 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002571 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002572 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002573 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002574 ScratchPadElemAbsolutePtrVal =
2575 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002576 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2577 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002578 IncrScratchpadDest = true;
2579 break;
2580 }
2581 case ScratchpadToThread: {
2582 // Step 1.1: Get the address for the src element in the scratchpad.
2583 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002584 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002585 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002586 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002587 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002588 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002589 ScratchPadElemAbsolutePtrVal =
2590 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2591 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2592 C.getTypeAlignInChars(Private->getType()));
2593 IncrScratchpadSrc = true;
2594
2595 // Step 1.2: Create a temporary to store the element in the destination
2596 // Reduce list.
2597 DestElementPtrAddr =
2598 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2599 DestElementAddr =
2600 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2601 UpdateDestListPtr = true;
2602 break;
2603 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002604 }
2605
2606 // Regardless of src and dest of copy, we emit the load of src
2607 // element as this is required in all directions
2608 SrcElementAddr = Bld.CreateElementBitCast(
2609 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002610 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2611 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002612
2613 // Now that all active lanes have read the element in the
2614 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002615 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002616 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2617 RemoteLaneOffset, Private->getExprLoc());
2618 } else {
2619 if (Private->getType()->isScalarType()) {
2620 llvm::Value *Elem =
2621 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2622 Private->getType(), Private->getExprLoc());
2623 // Store the source element value to the dest element address.
2624 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2625 Private->getType());
2626 } else {
2627 CGF.EmitAggregateCopy(
2628 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2629 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2630 Private->getType(), AggValueSlot::DoesNotOverlap);
2631 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002632 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002633
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002634 // Step 3.1: Modify reference in dest Reduce list as needed.
2635 // Modifying the reference in Reduce list to point to the newly
2636 // created element. The element is live in the current function
2637 // scope and that of functions it invokes (i.e., reduce_function).
2638 // RemoteReduceData[i] = (void*)&RemoteElem
2639 if (UpdateDestListPtr) {
2640 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2641 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2642 DestElementPtrAddr, /*Volatile=*/false,
2643 C.VoidPtrTy);
2644 }
2645
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002646 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2647 // address of the next element in scratchpad memory, unless we're currently
2648 // processing the last one. Memory alignment is also taken care of here.
2649 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2650 llvm::Value *ScratchpadBasePtr =
2651 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002652 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2653 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002654 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002655 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002656
2657 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002658 ScratchpadBasePtr = Bld.CreateNUWSub(
2659 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2660 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002661 ScratchpadBasePtr,
2662 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002663 ScratchpadBasePtr = Bld.CreateNUWAdd(
2664 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2665 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002666 ScratchpadBasePtr,
2667 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2668
2669 if (IncrScratchpadDest)
2670 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2671 else /* IncrScratchpadSrc = true */
2672 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2673 }
2674
Alexey Bataev9ff80832018-04-16 20:16:21 +00002675 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002676 }
2677}
2678
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002679/// This function emits a helper that loads data from the scratchpad array
2680/// and (optionally) reduces it with the input operand.
2681///
2682/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2683/// reduce_data remote;
2684/// for elem in remote:
2685/// remote.elem = Scratchpad[elem_id][index]
2686/// if (should_reduce)
2687/// local = local @ remote
2688/// else
2689/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002690static llvm::Value *emitReduceScratchpadFunction(
2691 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2692 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002693 ASTContext &C = CGM.getContext();
2694 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002695
2696 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002697 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2698 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002699 // Base address of the scratchpad array, with each element storing a
2700 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002701 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2702 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002703 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002704 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2705 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002706 // Row width of an element in the scratchpad array, typically
2707 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002708 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2709 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002710 // If should_reduce == 1, then it's load AND reduce,
2711 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2712 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002713 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2714 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002715
2716 FunctionArgList Args;
2717 Args.push_back(&ReduceListArg);
2718 Args.push_back(&ScratchPadArg);
2719 Args.push_back(&IndexArg);
2720 Args.push_back(&WidthArg);
2721 Args.push_back(&ShouldReduceArg);
2722
Alexey Bataev9ff80832018-04-16 20:16:21 +00002723 const CGFunctionInfo &CGFI =
2724 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002725 auto *Fn = llvm::Function::Create(
2726 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2727 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002728 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002729 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002730 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002731 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002732
Alexey Bataev9ff80832018-04-16 20:16:21 +00002733 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002734
2735 // Get local Reduce list pointer.
2736 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2737 Address ReduceListAddr(
2738 Bld.CreatePointerBitCastOrAddrSpaceCast(
2739 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002740 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002741 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2742 CGF.getPointerAlign());
2743
2744 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2745 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002746 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002747
2748 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002749 llvm::Value *IndexVal = Bld.CreateIntCast(
2750 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2751 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002752
2753 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002754 llvm::Value *WidthVal = Bld.CreateIntCast(
2755 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2756 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002757
2758 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2759 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002760 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002761
2762 // The absolute ptr address to the base addr of the next element to copy.
2763 llvm::Value *CumulativeElemBasePtr =
2764 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2765 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2766
2767 // Create a Remote Reduce list to store the elements read from the
2768 // scratchpad array.
2769 Address RemoteReduceList =
2770 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2771
2772 // Assemble remote Reduce list from scratchpad array.
2773 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2774 SrcDataAddr, RemoteReduceList,
2775 {/*RemoteLaneOffset=*/nullptr,
2776 /*ScratchpadIndex=*/IndexVal,
2777 /*ScratchpadWidth=*/WidthVal});
2778
2779 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2780 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2781 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2782
Alexey Bataev9ff80832018-04-16 20:16:21 +00002783 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002784 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2785
2786 CGF.EmitBlock(ThenBB);
2787 // We should reduce with the local Reduce list.
2788 // reduce_function(LocalReduceList, RemoteReduceList)
2789 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2790 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2791 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2792 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002793 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2794 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002795 Bld.CreateBr(MergeBB);
2796
2797 CGF.EmitBlock(ElseBB);
2798 // No reduction; just copy:
2799 // Local Reduce list = Remote Reduce list.
2800 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2801 RemoteReduceList, ReduceListAddr);
2802 Bld.CreateBr(MergeBB);
2803
2804 CGF.EmitBlock(MergeBB);
2805
2806 CGF.FinishFunction();
2807 return Fn;
2808}
2809
2810/// This function emits a helper that stores reduced data from the team
2811/// master to a scratchpad array in global memory.
2812///
2813/// for elem in Reduce List:
2814/// scratchpad[elem_id][index] = elem
2815///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002816static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2817 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002818 QualType ReductionArrayTy,
2819 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002820
Alexey Bataev9ff80832018-04-16 20:16:21 +00002821 ASTContext &C = CGM.getContext();
2822 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002823
2824 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002825 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2826 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002827 // Base address of the scratchpad array, with each element storing a
2828 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002829 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2830 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002831 // A destination index into the scratchpad array, typically the team
2832 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002833 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2834 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002835 // Row width of an element in the scratchpad array, typically
2836 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002837 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2838 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002839
2840 FunctionArgList Args;
2841 Args.push_back(&ReduceListArg);
2842 Args.push_back(&ScratchPadArg);
2843 Args.push_back(&IndexArg);
2844 Args.push_back(&WidthArg);
2845
Alexey Bataev9ff80832018-04-16 20:16:21 +00002846 const CGFunctionInfo &CGFI =
2847 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002848 auto *Fn = llvm::Function::Create(
2849 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2850 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002851 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002852 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002853 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002854 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002855
Alexey Bataev9ff80832018-04-16 20:16:21 +00002856 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002857
2858 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2859 Address SrcDataAddr(
2860 Bld.CreatePointerBitCastOrAddrSpaceCast(
2861 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002862 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002863 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2864 CGF.getPointerAlign());
2865
2866 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2867 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002868 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002869
2870 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002871 llvm::Value *IndexVal = Bld.CreateIntCast(
2872 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2873 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002874
2875 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2876 llvm::Value *WidthVal =
2877 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2878 Int32Ty, SourceLocation()),
2879 CGF.SizeTy, /*isSigned=*/true);
2880
2881 // The absolute ptr address to the base addr of the next element to copy.
2882 llvm::Value *CumulativeElemBasePtr =
2883 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2884 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2885
2886 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2887 SrcDataAddr, DestDataAddr,
2888 {/*RemoteLaneOffset=*/nullptr,
2889 /*ScratchpadIndex=*/IndexVal,
2890 /*ScratchpadWidth=*/WidthVal});
2891
2892 CGF.FinishFunction();
2893 return Fn;
2894}
2895
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002896/// This function emits a helper that gathers Reduce lists from the first
2897/// lane of every active warp to lanes in the first warp.
2898///
2899/// void inter_warp_copy_func(void* reduce_data, num_warps)
2900/// shared smem[warp_size];
2901/// For all data entries D in reduce_data:
2902/// If (I am the first lane in each warp)
2903/// Copy my local D to smem[warp_id]
2904/// sync
2905/// if (I am the first warp)
2906/// Copy smem[thread_id] to my local D
2907/// sync
2908static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2909 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002910 QualType ReductionArrayTy,
2911 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002912 ASTContext &C = CGM.getContext();
2913 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002914
2915 // ReduceList: thread local Reduce list.
2916 // At the stage of the computation when this function is called, partially
2917 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002918 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2919 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002920 // NumWarps: number of warps active in the parallel region. This could
2921 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002922 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002923 C.getIntTypeForBitwidth(32, /* Signed */ true),
2924 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925 FunctionArgList Args;
2926 Args.push_back(&ReduceListArg);
2927 Args.push_back(&NumWarpsArg);
2928
Alexey Bataev9ff80832018-04-16 20:16:21 +00002929 const CGFunctionInfo &CGFI =
2930 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002931 auto *Fn = llvm::Function::Create(
2932 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2933 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002934 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002935 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002936 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002937 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002938
Alexey Bataev9ff80832018-04-16 20:16:21 +00002939 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002940
2941 // This array is used as a medium to transfer, one reduce element at a time,
2942 // the data from the first lane of every warp to lanes in the first warp
2943 // in order to perform the final step of a reduction in a parallel region
2944 // (reduction across warps). The array is placed in NVPTX __shared__ memory
2945 // for reduced latency, as well as to have a distinct copy for concurrently
2946 // executing target regions. The array is declared with common linkage so
2947 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002948 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002949 "__openmp_nvptx_data_transfer_temporary_storage";
2950 llvm::GlobalVariable *TransferMedium =
2951 M.getGlobalVariable(TransferMediumName);
2952 if (!TransferMedium) {
2953 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
2954 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2955 TransferMedium = new llvm::GlobalVariable(
2956 M, Ty,
2957 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
2958 llvm::Constant::getNullValue(Ty), TransferMediumName,
2959 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2960 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002961 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002962 }
2963
2964 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002965 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002967 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002968 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00002969 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002970
2971 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2972 Address LocalReduceList(
2973 Bld.CreatePointerBitCastOrAddrSpaceCast(
2974 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2975 C.VoidPtrTy, SourceLocation()),
2976 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2977 CGF.getPointerAlign());
2978
2979 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00002980 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002981 //
2982 // Warp master copies reduce element to transfer medium in __shared__
2983 // memory.
2984 //
2985 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2986 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2987 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2988
2989 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00002990 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002991 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2992 CGF.EmitBlock(ThenBB);
2993
2994 // Reduce element = LocalReduceList[i]
2995 Address ElemPtrPtrAddr =
2996 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
2997 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2998 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2999 // elemptr = (type[i]*)(elemptrptr)
3000 Address ElemPtr =
3001 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3002 ElemPtr = Bld.CreateElementBitCast(
3003 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003004
3005 // Get pointer to location in transfer medium.
3006 // MediumPtr = &medium[warp_id]
3007 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3008 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3009 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3010 // Casting to actual data type.
3011 // MediumPtr = (type[i]*)MediumPtrAddr;
3012 MediumPtr = Bld.CreateElementBitCast(
3013 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3014
Alexey Bataev12c62902018-06-22 19:10:38 +00003015 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003016 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003017 if (Private->getType()->isScalarType()) {
3018 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3019 Private->getType(), Loc);
3020 // Store the source element value to the dest element address.
3021 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3022 Private->getType());
3023 } else {
3024 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3025 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3026 Private->getType(), AggValueSlot::DoesNotOverlap);
3027 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003028
3029 Bld.CreateBr(MergeBB);
3030
3031 CGF.EmitBlock(ElseBB);
3032 Bld.CreateBr(MergeBB);
3033
3034 CGF.EmitBlock(MergeBB);
3035
3036 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3037 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3038 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3039
Alexey Bataev9ff80832018-04-16 20:16:21 +00003040 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003041 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3042 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3043 syncParallelThreads(CGF, NumActiveThreads);
3044
3045 //
3046 // Warp 0 copies reduce element from transfer medium.
3047 //
3048 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3049 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3050 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3051
3052 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003053 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003054 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3055 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3056
3057 CGF.EmitBlock(W0ThenBB);
3058
3059 // SrcMediumPtr = &medium[tid]
3060 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3061 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3062 Address SrcMediumPtr(SrcMediumPtrVal,
3063 C.getTypeAlignInChars(Private->getType()));
3064 // SrcMediumVal = *SrcMediumPtr;
3065 SrcMediumPtr = Bld.CreateElementBitCast(
3066 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003067
3068 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3069 Address TargetElemPtrPtr =
3070 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3071 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3072 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3073 Address TargetElemPtr =
3074 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3075 TargetElemPtr = Bld.CreateElementBitCast(
3076 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3077
3078 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003079 if (Private->getType()->isScalarType()) {
3080 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3081 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3082 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3083 Private->getType());
3084 } else {
3085 CGF.EmitAggregateCopy(
3086 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3087 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3088 Private->getType(), AggValueSlot::DoesNotOverlap);
3089 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003090 Bld.CreateBr(W0MergeBB);
3091
3092 CGF.EmitBlock(W0ElseBB);
3093 Bld.CreateBr(W0MergeBB);
3094
3095 CGF.EmitBlock(W0MergeBB);
3096
3097 // While warp 0 copies values from transfer medium, all other warps must
3098 // wait.
3099 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003100 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003101 }
3102
3103 CGF.FinishFunction();
3104 return Fn;
3105}
3106
3107/// Emit a helper that reduces data across two OpenMP threads (lanes)
3108/// in the same warp. It uses shuffle instructions to copy over data from
3109/// a remote lane's stack. The reduction algorithm performed is specified
3110/// by the fourth parameter.
3111///
3112/// Algorithm Versions.
3113/// Full Warp Reduce (argument value 0):
3114/// This algorithm assumes that all 32 lanes are active and gathers
3115/// data from these 32 lanes, producing a single resultant value.
3116/// Contiguous Partial Warp Reduce (argument value 1):
3117/// This algorithm assumes that only a *contiguous* subset of lanes
3118/// are active. This happens for the last warp in a parallel region
3119/// when the user specified num_threads is not an integer multiple of
3120/// 32. This contiguous subset always starts with the zeroth lane.
3121/// Partial Warp Reduce (argument value 2):
3122/// This algorithm gathers data from any number of lanes at any position.
3123/// All reduced values are stored in the lowest possible lane. The set
3124/// of problems every algorithm addresses is a super set of those
3125/// addressable by algorithms with a lower version number. Overhead
3126/// increases as algorithm version increases.
3127///
3128/// Terminology
3129/// Reduce element:
3130/// Reduce element refers to the individual data field with primitive
3131/// data types to be combined and reduced across threads.
3132/// Reduce list:
3133/// Reduce list refers to a collection of local, thread-private
3134/// reduce elements.
3135/// Remote Reduce list:
3136/// Remote Reduce list refers to a collection of remote (relative to
3137/// the current thread) reduce elements.
3138///
3139/// We distinguish between three states of threads that are important to
3140/// the implementation of this function.
3141/// Alive threads:
3142/// Threads in a warp executing the SIMT instruction, as distinguished from
3143/// threads that are inactive due to divergent control flow.
3144/// Active threads:
3145/// The minimal set of threads that has to be alive upon entry to this
3146/// function. The computation is correct iff active threads are alive.
3147/// Some threads are alive but they are not active because they do not
3148/// contribute to the computation in any useful manner. Turning them off
3149/// may introduce control flow overheads without any tangible benefits.
3150/// Effective threads:
3151/// In order to comply with the argument requirements of the shuffle
3152/// function, we must keep all lanes holding data alive. But at most
3153/// half of them perform value aggregation; we refer to this half of
3154/// threads as effective. The other half is simply handing off their
3155/// data.
3156///
3157/// Procedure
3158/// Value shuffle:
3159/// In this step active threads transfer data from higher lane positions
3160/// in the warp to lower lane positions, creating Remote Reduce list.
3161/// Value aggregation:
3162/// In this step, effective threads combine their thread local Reduce list
3163/// with Remote Reduce list and store the result in the thread local
3164/// Reduce list.
3165/// Value copy:
3166/// In this step, we deal with the assumption made by algorithm 2
3167/// (i.e. contiguity assumption). When we have an odd number of lanes
3168/// active, say 2k+1, only k threads will be effective and therefore k
3169/// new values will be produced. However, the Reduce list owned by the
3170/// (2k+1)th thread is ignored in the value aggregation. Therefore
3171/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3172/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003173static llvm::Value *emitShuffleAndReduceFunction(
3174 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3175 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003176 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177
3178 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003179 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3180 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003182 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3183 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003184 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003185 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3186 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003188 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3189 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003190 FunctionArgList Args;
3191 Args.push_back(&ReduceListArg);
3192 Args.push_back(&LaneIDArg);
3193 Args.push_back(&RemoteLaneOffsetArg);
3194 Args.push_back(&AlgoVerArg);
3195
Alexey Bataev9ff80832018-04-16 20:16:21 +00003196 const CGFunctionInfo &CGFI =
3197 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003198 auto *Fn = llvm::Function::Create(
3199 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3200 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003201 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003202 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003203 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003204 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003205
Alexey Bataev9ff80832018-04-16 20:16:21 +00003206 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207
3208 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3209 Address LocalReduceList(
3210 Bld.CreatePointerBitCastOrAddrSpaceCast(
3211 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3212 C.VoidPtrTy, SourceLocation()),
3213 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3214 CGF.getPointerAlign());
3215
3216 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3217 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3218 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3219
3220 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3221 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3222 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3223
3224 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3225 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3226 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3227
3228 // Create a local thread-private variable to host the Reduce list
3229 // from a remote lane.
3230 Address RemoteReduceList =
3231 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3232
3233 // This loop iterates through the list of reduce elements and copies,
3234 // element by element, from a remote lane in the warp to RemoteReduceList,
3235 // hosted on the thread's stack.
3236 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3237 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003238 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3239 /*ScratchpadIndex=*/nullptr,
3240 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003241
3242 // The actions to be performed on the Remote Reduce list is dependent
3243 // on the algorithm version.
3244 //
3245 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3246 // LaneId % 2 == 0 && Offset > 0):
3247 // do the reduction value aggregation
3248 //
3249 // The thread local variable Reduce list is mutated in place to host the
3250 // reduced data, which is the aggregated value produced from local and
3251 // remote lanes.
3252 //
3253 // Note that AlgoVer is expected to be a constant integer known at compile
3254 // time.
3255 // When AlgoVer==0, the first conjunction evaluates to true, making
3256 // the entire predicate true during compile time.
3257 // When AlgoVer==1, the second conjunction has only the second part to be
3258 // evaluated during runtime. Other conjunctions evaluates to false
3259 // during compile time.
3260 // When AlgoVer==2, the third conjunction has only the second part to be
3261 // evaluated during runtime. Other conjunctions evaluates to false
3262 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003263 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003264
Alexey Bataev9ff80832018-04-16 20:16:21 +00003265 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3266 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3268
Alexey Bataev9ff80832018-04-16 20:16:21 +00003269 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3270 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3271 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272 CondAlgo2 = Bld.CreateAnd(
3273 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3274
Alexey Bataev9ff80832018-04-16 20:16:21 +00003275 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3277
3278 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3279 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3280 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3281 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3282
3283 CGF.EmitBlock(ThenBB);
3284 // reduce_function(LocalReduceList, RemoteReduceList)
3285 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3286 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3287 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3288 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003289 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3290 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003291 Bld.CreateBr(MergeBB);
3292
3293 CGF.EmitBlock(ElseBB);
3294 Bld.CreateBr(MergeBB);
3295
3296 CGF.EmitBlock(MergeBB);
3297
3298 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3299 // Reduce list.
3300 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003301 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003302 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3303
3304 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3305 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3306 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3307 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3308
3309 CGF.EmitBlock(CpyThenBB);
3310 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3311 RemoteReduceList, LocalReduceList);
3312 Bld.CreateBr(CpyMergeBB);
3313
3314 CGF.EmitBlock(CpyElseBB);
3315 Bld.CreateBr(CpyMergeBB);
3316
3317 CGF.EmitBlock(CpyMergeBB);
3318
3319 CGF.FinishFunction();
3320 return Fn;
3321}
3322
3323///
3324/// Design of OpenMP reductions on the GPU
3325///
3326/// Consider a typical OpenMP program with one or more reduction
3327/// clauses:
3328///
3329/// float foo;
3330/// double bar;
3331/// #pragma omp target teams distribute parallel for \
3332/// reduction(+:foo) reduction(*:bar)
3333/// for (int i = 0; i < N; i++) {
3334/// foo += A[i]; bar *= B[i];
3335/// }
3336///
3337/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3338/// all teams. In our OpenMP implementation on the NVPTX device an
3339/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3340/// within a team are mapped to CUDA threads within a threadblock.
3341/// Our goal is to efficiently aggregate values across all OpenMP
3342/// threads such that:
3343///
3344/// - the compiler and runtime are logically concise, and
3345/// - the reduction is performed efficiently in a hierarchical
3346/// manner as follows: within OpenMP threads in the same warp,
3347/// across warps in a threadblock, and finally across teams on
3348/// the NVPTX device.
3349///
3350/// Introduction to Decoupling
3351///
3352/// We would like to decouple the compiler and the runtime so that the
3353/// latter is ignorant of the reduction variables (number, data types)
3354/// and the reduction operators. This allows a simpler interface
3355/// and implementation while still attaining good performance.
3356///
3357/// Pseudocode for the aforementioned OpenMP program generated by the
3358/// compiler is as follows:
3359///
3360/// 1. Create private copies of reduction variables on each OpenMP
3361/// thread: 'foo_private', 'bar_private'
3362/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3363/// to it and writes the result in 'foo_private' and 'bar_private'
3364/// respectively.
3365/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3366/// and store the result on the team master:
3367///
3368/// __kmpc_nvptx_parallel_reduce_nowait(...,
3369/// reduceData, shuffleReduceFn, interWarpCpyFn)
3370///
3371/// where:
3372/// struct ReduceData {
3373/// double *foo;
3374/// double *bar;
3375/// } reduceData
3376/// reduceData.foo = &foo_private
3377/// reduceData.bar = &bar_private
3378///
3379/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3380/// auxiliary functions generated by the compiler that operate on
3381/// variables of type 'ReduceData'. They aid the runtime perform
3382/// algorithmic steps in a data agnostic manner.
3383///
3384/// 'shuffleReduceFn' is a pointer to a function that reduces data
3385/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3386/// same warp. It takes the following arguments as input:
3387///
3388/// a. variable of type 'ReduceData' on the calling lane,
3389/// b. its lane_id,
3390/// c. an offset relative to the current lane_id to generate a
3391/// remote_lane_id. The remote lane contains the second
3392/// variable of type 'ReduceData' that is to be reduced.
3393/// d. an algorithm version parameter determining which reduction
3394/// algorithm to use.
3395///
3396/// 'shuffleReduceFn' retrieves data from the remote lane using
3397/// efficient GPU shuffle intrinsics and reduces, using the
3398/// algorithm specified by the 4th parameter, the two operands
3399/// element-wise. The result is written to the first operand.
3400///
3401/// Different reduction algorithms are implemented in different
3402/// runtime functions, all calling 'shuffleReduceFn' to perform
3403/// the essential reduction step. Therefore, based on the 4th
3404/// parameter, this function behaves slightly differently to
3405/// cooperate with the runtime to ensure correctness under
3406/// different circumstances.
3407///
3408/// 'InterWarpCpyFn' is a pointer to a function that transfers
3409/// reduced variables across warps. It tunnels, through CUDA
3410/// shared memory, the thread-private data of type 'ReduceData'
3411/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003412/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3413/// The last team writes the global reduced value to memory.
3414///
3415/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3416/// reduceData, shuffleReduceFn, interWarpCpyFn,
3417/// scratchpadCopyFn, loadAndReduceFn)
3418///
3419/// 'scratchpadCopyFn' is a helper that stores reduced
3420/// data from the team master to a scratchpad array in
3421/// global memory.
3422///
3423/// 'loadAndReduceFn' is a helper that loads data from
3424/// the scratchpad array and reduces it with the input
3425/// operand.
3426///
3427/// These compiler generated functions hide address
3428/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003429/// 5. if ret == 1:
3430/// The team master of the last team stores the reduced
3431/// result to the globals in memory.
3432/// foo += reduceData.foo; bar *= reduceData.bar
3433///
3434///
3435/// Warp Reduction Algorithms
3436///
3437/// On the warp level, we have three algorithms implemented in the
3438/// OpenMP runtime depending on the number of active lanes:
3439///
3440/// Full Warp Reduction
3441///
3442/// The reduce algorithm within a warp where all lanes are active
3443/// is implemented in the runtime as follows:
3444///
3445/// full_warp_reduce(void *reduce_data,
3446/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3447/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3448/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3449/// }
3450///
3451/// The algorithm completes in log(2, WARPSIZE) steps.
3452///
3453/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3454/// not used therefore we save instructions by not retrieving lane_id
3455/// from the corresponding special registers. The 4th parameter, which
3456/// represents the version of the algorithm being used, is set to 0 to
3457/// signify full warp reduction.
3458///
3459/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3460///
3461/// #reduce_elem refers to an element in the local lane's data structure
3462/// #remote_elem is retrieved from a remote lane
3463/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3464/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3465///
3466/// Contiguous Partial Warp Reduction
3467///
3468/// This reduce algorithm is used within a warp where only the first
3469/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3470/// number of OpenMP threads in a parallel region is not a multiple of
3471/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3472///
3473/// void
3474/// contiguous_partial_reduce(void *reduce_data,
3475/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3476/// int size, int lane_id) {
3477/// int curr_size;
3478/// int offset;
3479/// curr_size = size;
3480/// mask = curr_size/2;
3481/// while (offset>0) {
3482/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3483/// curr_size = (curr_size+1)/2;
3484/// offset = curr_size/2;
3485/// }
3486/// }
3487///
3488/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3489///
3490/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3491/// if (lane_id < offset)
3492/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3493/// else
3494/// reduce_elem = remote_elem
3495///
3496/// This algorithm assumes that the data to be reduced are located in a
3497/// contiguous subset of lanes starting from the first. When there is
3498/// an odd number of active lanes, the data in the last lane is not
3499/// aggregated with any other lane's dat but is instead copied over.
3500///
3501/// Dispersed Partial Warp Reduction
3502///
3503/// This algorithm is used within a warp when any discontiguous subset of
3504/// lanes are active. It is used to implement the reduction operation
3505/// across lanes in an OpenMP simd region or in a nested parallel region.
3506///
3507/// void
3508/// dispersed_partial_reduce(void *reduce_data,
3509/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3510/// int size, remote_id;
3511/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3512/// do {
3513/// remote_id = next_active_lane_id_right_after_me();
3514/// # the above function returns 0 of no active lane
3515/// # is present right after the current lane.
3516/// size = number_of_active_lanes_in_this_warp();
3517/// logical_lane_id /= 2;
3518/// ShuffleReduceFn(reduce_data, logical_lane_id,
3519/// remote_id-1-threadIdx.x, 2);
3520/// } while (logical_lane_id % 2 == 0 && size > 1);
3521/// }
3522///
3523/// There is no assumption made about the initial state of the reduction.
3524/// Any number of lanes (>=1) could be active at any position. The reduction
3525/// result is returned in the first active lane.
3526///
3527/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3528///
3529/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3530/// if (lane_id % 2 == 0 && offset > 0)
3531/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3532/// else
3533/// reduce_elem = remote_elem
3534///
3535///
3536/// Intra-Team Reduction
3537///
3538/// This function, as implemented in the runtime call
3539/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3540/// threads in a team. It first reduces within a warp using the
3541/// aforementioned algorithms. We then proceed to gather all such
3542/// reduced values at the first warp.
3543///
3544/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3545/// data from each of the "warp master" (zeroth lane of each warp, where
3546/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3547/// a mathematical sense) the problem of reduction across warp masters in
3548/// a block to the problem of warp reduction.
3549///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003550///
3551/// Inter-Team Reduction
3552///
3553/// Once a team has reduced its data to a single value, it is stored in
3554/// a global scratchpad array. Since each team has a distinct slot, this
3555/// can be done without locking.
3556///
3557/// The last team to write to the scratchpad array proceeds to reduce the
3558/// scratchpad array. One or more workers in the last team use the helper
3559/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3560/// the k'th worker reduces every k'th element.
3561///
3562/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3563/// reduce across workers and compute a globally reduced value.
3564///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003565void CGOpenMPRuntimeNVPTX::emitReduction(
3566 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3567 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3568 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3569 if (!CGF.HaveInsertPoint())
3570 return;
3571
3572 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003573 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003574 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3575 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003576 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003577
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003578 if (Options.SimpleReduction) {
3579 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3580 ReductionOps, Options);
3581 return;
3582 }
3583
Alexey Bataev9ff80832018-04-16 20:16:21 +00003584 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003585
3586 // 1. Build a list of reduction variables.
3587 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3588 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003589 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003590 if (E->getType()->isVariablyModifiedType())
3591 // Reserve place for array size.
3592 ++Size;
3593 }
3594 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3595 QualType ReductionArrayTy =
3596 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3597 /*IndexTypeQuals=*/0);
3598 Address ReductionList =
3599 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3600 auto IPriv = Privates.begin();
3601 unsigned Idx = 0;
3602 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3603 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3604 CGF.getPointerSize());
3605 CGF.Builder.CreateStore(
3606 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3607 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3608 Elem);
3609 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3610 // Store array size.
3611 ++Idx;
3612 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3613 CGF.getPointerSize());
3614 llvm::Value *Size = CGF.Builder.CreateIntCast(
3615 CGF.getVLASize(
3616 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003617 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003618 CGF.SizeTy, /*isSigned=*/false);
3619 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3620 Elem);
3621 }
3622 }
3623
3624 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003625 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003626 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3627 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003628
3629 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3630 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003631 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3632 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3633 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003634 ReductionList.getPointer(), CGF.VoidPtrTy);
3635
Alexey Bataev9ff80832018-04-16 20:16:21 +00003636 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003637 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003638 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003639 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003640
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003641 llvm::Value *Args[] = {ThreadId,
3642 CGF.Builder.getInt32(RHSExprs.size()),
3643 ReductionArrayTySize,
3644 RL,
3645 ShuffleAndReduceFn,
3646 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003647
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003648 llvm::Value *Res = nullptr;
3649 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003650 Res = CGF.EmitRuntimeCall(
3651 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3652 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003653 else if (SimdReduction)
3654 Res = CGF.EmitRuntimeCall(
3655 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3656 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003657
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003658 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003659 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003660 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003661 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003662 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003663
3664 llvm::Value *Args[] = {ThreadId,
3665 CGF.Builder.getInt32(RHSExprs.size()),
3666 ReductionArrayTySize,
3667 RL,
3668 ShuffleAndReduceFn,
3669 InterWarpCopyFn,
3670 ScratchPadCopyFn,
3671 LoadAndReduceFn};
3672 Res = CGF.EmitRuntimeCall(
3673 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3674 Args);
3675 }
3676
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003677 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003678 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3679 llvm::SwitchInst *SwInst =
3680 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003681
3682 // 6. Build case 1: where we have reduced values in the master
3683 // thread in each team.
3684 // __kmpc_end_reduce{_nowait}(<gtid>);
3685 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003686 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003687 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3688 CGF.EmitBlock(Case1BB);
3689
3690 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3691 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003692 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003693 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3694 auto IPriv = Privates.begin();
3695 auto ILHS = LHSExprs.begin();
3696 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003697 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003698 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3699 cast<DeclRefExpr>(*IRHS));
3700 ++IPriv;
3701 ++ILHS;
3702 ++IRHS;
3703 }
3704 };
3705 RegionCodeGenTy RCG(CodeGen);
3706 NVPTXActionTy Action(
3707 nullptr, llvm::None,
3708 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3709 EndArgs);
3710 RCG.setAction(Action);
3711 RCG(CGF);
3712 CGF.EmitBranch(DefaultBB);
3713 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3714}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003715
3716const VarDecl *
3717CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3718 const VarDecl *NativeParam) const {
3719 if (!NativeParam->getType()->isReferenceType())
3720 return NativeParam;
3721 QualType ArgType = NativeParam->getType();
3722 QualifierCollector QC;
3723 const Type *NonQualTy = QC.strip(ArgType);
3724 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3725 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3726 if (Attr->getCaptureKind() == OMPC_map) {
3727 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3728 LangAS::opencl_global);
3729 }
3730 }
3731 ArgType = CGM.getContext().getPointerType(PointeeTy);
3732 QC.addRestrict();
3733 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003734 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003735 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003736 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003737 return ImplicitParamDecl::Create(
3738 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3739 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003740 return ParmVarDecl::Create(
3741 CGM.getContext(),
3742 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003743 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003744 NativeParam->getIdentifier(), ArgType,
3745 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003746}
3747
3748Address
3749CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3750 const VarDecl *NativeParam,
3751 const VarDecl *TargetParam) const {
3752 assert(NativeParam != TargetParam &&
3753 NativeParam->getType()->isReferenceType() &&
3754 "Native arg must not be the same as target arg.");
3755 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3756 QualType NativeParamType = NativeParam->getType();
3757 QualifierCollector QC;
3758 const Type *NonQualTy = QC.strip(NativeParamType);
3759 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3760 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003761 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003762 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003763 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003764 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003765 // First cast to generic.
3766 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3767 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3768 /*AddrSpace=*/0));
3769 // Cast from generic to native address space.
3770 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3771 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3772 NativePointeeAddrSpace));
3773 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3774 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003775 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003776 return NativeParamAddr;
3777}
3778
3779void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003780 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003781 ArrayRef<llvm::Value *> Args) const {
3782 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003783 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003784 auto *FnType =
3785 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3786 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003787 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3788 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3789 break;
3790 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003791 llvm::Type *TargetType = FnType->getParamType(I);
3792 llvm::Value *NativeArg = Args[I];
3793 if (!TargetType->isPointerTy()) {
3794 TargetArgs.emplace_back(NativeArg);
3795 continue;
3796 }
3797 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003798 NativeArg,
3799 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003800 TargetArgs.emplace_back(
3801 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3802 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003803 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003804}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003805
3806/// Emit function which wraps the outline parallel region
3807/// and controls the arguments which are passed to this function.
3808/// The wrapper ensures that the outlined function is called
3809/// with the correct arguments when data is shared.
3810llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3811 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3812 ASTContext &Ctx = CGM.getContext();
3813 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3814
3815 // Create a function that takes as argument the source thread.
3816 FunctionArgList WrapperArgs;
3817 QualType Int16QTy =
3818 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3819 QualType Int32QTy =
3820 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003821 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003822 /*Id=*/nullptr, Int16QTy,
3823 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003824 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003825 /*Id=*/nullptr, Int32QTy,
3826 ImplicitParamDecl::Other);
3827 WrapperArgs.emplace_back(&ParallelLevelArg);
3828 WrapperArgs.emplace_back(&WrapperArg);
3829
Alexey Bataev9ff80832018-04-16 20:16:21 +00003830 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003831 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3832
3833 auto *Fn = llvm::Function::Create(
3834 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003835 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003836 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003837 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003838 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003839
3840 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3841 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003842 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003843
3844 const auto *RD = CS.getCapturedRecordDecl();
3845 auto CurField = RD->field_begin();
3846
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003847 Address ZeroAddr = CGF.CreateMemTemp(
3848 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3849 /*Name*/ ".zero.addr");
3850 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003851 // Get the array of arguments.
3852 SmallVector<llvm::Value *, 8> Args;
3853
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003854 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3855 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003856
3857 CGBuilderTy &Bld = CGF.Builder;
3858 auto CI = CS.capture_begin();
3859
3860 // Use global memory for data sharing.
3861 // Handle passing of global args to workers.
3862 Address GlobalArgs =
3863 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3864 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3865 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3866 CGF.EmitRuntimeCall(
3867 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3868 DataSharingArgs);
3869
3870 // Retrieve the shared variables from the list of references returned
3871 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003872 Address SharedArgListAddress = Address::invalid();
3873 if (CS.capture_size() > 0 ||
3874 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3875 SharedArgListAddress = CGF.EmitLoadOfPointer(
3876 GlobalArgs, CGF.getContext()
3877 .getPointerType(CGF.getContext().getPointerType(
3878 CGF.getContext().VoidPtrTy))
3879 .castAs<PointerType>());
3880 }
3881 unsigned Idx = 0;
3882 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3883 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3884 CGF.getPointerSize());
3885 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3886 Src, CGF.SizeTy->getPointerTo());
3887 llvm::Value *LB = CGF.EmitLoadOfScalar(
3888 TypedAddress,
3889 /*Volatile=*/false,
3890 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3891 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3892 Args.emplace_back(LB);
3893 ++Idx;
3894 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3895 CGF.getPointerSize());
3896 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3897 Src, CGF.SizeTy->getPointerTo());
3898 llvm::Value *UB = CGF.EmitLoadOfScalar(
3899 TypedAddress,
3900 /*Volatile=*/false,
3901 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3902 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3903 Args.emplace_back(UB);
3904 ++Idx;
3905 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003906 if (CS.capture_size() > 0) {
3907 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003908 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3909 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003910 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3911 CGF.getPointerSize());
3912 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003913 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3914 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3915 /*Volatile=*/false,
3916 CGFContext.getPointerType(ElemTy),
3917 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003918 if (CI->capturesVariableByCopy() &&
3919 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003920 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3921 CI->getLocation());
3922 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003923 Args.emplace_back(Arg);
3924 }
3925 }
3926
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003927 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003928 CGF.FinishFunction();
3929 return Fn;
3930}
3931
3932void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
3933 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003934 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3935 return;
3936
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003937 assert(D && "Expected function or captured|block decl.");
3938 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3939 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003940 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003941 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003942 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3943 Body = FD->getBody();
3944 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3945 Body = BD->getBody();
3946 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3947 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003948 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003949 }
3950 if (!Body)
3951 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003952 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003953 VarChecker.Visit(Body);
3954 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003955 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3956 VarChecker.getEscapedVariableLengthDecls();
3957 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003958 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00003959 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3960 I->getSecond().MappedParams =
3961 llvm::make_unique<CodeGenFunction::OMPMapVars>();
3962 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
3963 I->getSecond().EscapedParameters.insert(
3964 VarChecker.getEscapedParameters().begin(),
3965 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003966 I->getSecond().EscapedVariableLengthDecls.append(
3967 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003968 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003969 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003970 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003971 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00003972 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
3973 }
3974 if (!NeedToDelayGlobalization) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003975 emitGenericVarsProlog(CGF, D->getBeginLoc());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003976 struct GlobalizationScope final : EHScopeStack::Cleanup {
3977 GlobalizationScope() = default;
3978
3979 void Emit(CodeGenFunction &CGF, Flags flags) override {
3980 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
3981 .emitGenericVarsEpilog(CGF);
3982 }
3983 };
3984 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003985 }
3986}
3987
3988Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
3989 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003990 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
3991 return Address::invalid();
3992
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003993 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003994 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3995 if (I == FunctionGlobalizedDecls.end())
3996 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00003997 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00003998 if (VDI != I->getSecond().LocalVarData.end())
3999 return VDI->second.second;
4000 if (VD->hasAttrs()) {
4001 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4002 E(VD->attr_end());
4003 IT != E; ++IT) {
4004 auto VDI = I->getSecond().LocalVarData.find(
4005 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4006 ->getCanonicalDecl());
4007 if (VDI != I->getSecond().LocalVarData.end())
4008 return VDI->second.second;
4009 }
4010 }
4011 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004012}
4013
4014void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004015 FunctionGlobalizedDecls.erase(CGF.CurFn);
4016 CGOpenMPRuntime::functionFinished(CGF);
4017}