blob: a923232e8173d43931a543789a8ee7ffc0016810 [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
Alexey Bataev2adecff2018-09-21 14:22:53 +0000182typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
183static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
184 return P1.first > P2.first;
185}
186
187static RecordDecl *buildRecordForGlobalizedVars(
188 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
189 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
190 &MappedDeclsFields) {
191 if (EscapedDecls.empty())
192 return nullptr;
193 SmallVector<VarsDataTy, 4> GlobalizedVars;
194 for (const ValueDecl *D : EscapedDecls)
195 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
196 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
197 stable_sort_comparator);
198 // Build struct _globalized_locals_ty {
199 // /* globalized vars */
200 // };
201 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
202 GlobalizedRD->startDefinition();
203 for (const auto &Pair : GlobalizedVars) {
204 const ValueDecl *VD = Pair.second;
205 QualType Type = VD->getType();
206 if (Type->isLValueReferenceType())
207 Type = C.getPointerType(Type.getNonReferenceType());
208 else
209 Type = Type.getNonReferenceType();
210 SourceLocation Loc = VD->getLocation();
211 auto *Field =
212 FieldDecl::Create(C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
213 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
214 /*BW=*/nullptr, /*Mutable=*/false,
215 /*InitStyle=*/ICIS_NoInit);
216 Field->setAccess(AS_public);
217 GlobalizedRD->addDecl(Field);
218 if (VD->hasAttrs()) {
219 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
220 E(VD->getAttrs().end());
221 I != E; ++I)
222 Field->addAttr(*I);
223 }
224 MappedDeclsFields.try_emplace(VD, Field);
225 }
226 GlobalizedRD->completeDefinition();
227 return GlobalizedRD;
228}
229
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000230/// Get the list of variables that can escape their declaration context.
231class CheckVarsEscapingDeclContext final
232 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
233 CodeGenFunction &CGF;
234 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000235 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000236 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000237 RecordDecl *GlobalizedRD = nullptr;
238 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000239 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000240 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000241
242 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000243 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000244 if (!isa<VarDecl>(VD) ||
245 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000246 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000247 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000248 // Variables captured by value must be globalized.
249 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000250 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000251 // Check if need to capture the variable that was already captured by
252 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000253 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000254 if (!FD->hasAttrs())
255 return;
256 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
257 if (!Attr)
258 return;
259 if (!isOpenMPPrivate(
260 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
261 Attr->getCaptureKind() == OMPC_map)
262 return;
263 }
264 if (!FD->getType()->isReferenceType()) {
265 assert(!VD->getType()->isVariablyModifiedType() &&
266 "Parameter captured by value with variably modified type");
267 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000268 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000269 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000270 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000271 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000272 }
273 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000274 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000275 VD->getType()->isReferenceType())
276 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000277 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000278 if (VD->getType()->isVariablyModifiedType())
279 EscapedVariableLengthDecls.insert(VD);
280 else
281 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000282 }
283
284 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000285 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000286 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000287 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
288 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
289 const bool SavedAllEscaped = AllEscaped;
290 AllEscaped = VD->getType()->isLValueReferenceType();
291 Visit(VarD->getInit());
292 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000293 }
294 }
295 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000296 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
297 ArrayRef<OMPClause *> Clauses,
298 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000299 if (!S)
300 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000301 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000302 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
303 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000304 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
305 if (IsCombinedParallelRegion) {
306 // Check if the variable is privatized in the combined construct and
307 // those private copies must be shared in the inner parallel
308 // directive.
309 IsForCombinedParallelRegion = false;
310 for (const OMPClause *C : Clauses) {
311 if (!isOpenMPPrivate(C->getClauseKind()) ||
312 C->getClauseKind() == OMPC_reduction ||
313 C->getClauseKind() == OMPC_linear ||
314 C->getClauseKind() == OMPC_private)
315 continue;
316 ArrayRef<const Expr *> Vars;
317 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
318 Vars = PC->getVarRefs();
319 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
320 Vars = PC->getVarRefs();
321 else
322 llvm_unreachable("Unexpected clause.");
323 for (const auto *E : Vars) {
324 const Decl *D =
325 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
326 if (D == VD->getCanonicalDecl()) {
327 IsForCombinedParallelRegion = true;
328 break;
329 }
330 }
331 if (IsForCombinedParallelRegion)
332 break;
333 }
334 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000335 markAsEscaped(VD);
336 if (isa<OMPCapturedExprDecl>(VD))
337 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000338 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000339 }
340 }
341 }
342
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000343 void buildRecordForGlobalizedVars() {
344 assert(!GlobalizedRD &&
345 "Record for globalized variables is built already.");
Alexey Bataev2adecff2018-09-21 14:22:53 +0000346 GlobalizedRD = ::buildRecordForGlobalizedVars(
347 CGF.getContext(), EscapedDecls.getArrayRef(), MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000348 }
349
350public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000351 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000352 virtual ~CheckVarsEscapingDeclContext() = default;
353 void VisitDeclStmt(const DeclStmt *S) {
354 if (!S)
355 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000356 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000357 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
358 VisitValueDecl(VD);
359 }
360 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
361 if (!D)
362 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000363 if (!D->hasAssociatedStmt())
364 return;
365 if (const auto *S =
366 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
367 // Do not analyze directives that do not actually require capturing,
368 // like `omp for` or `omp simd` directives.
369 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
370 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
371 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
372 VisitStmt(S->getCapturedStmt());
373 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000374 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000375 VisitOpenMPCapturedStmt(
376 S, D->clauses(),
377 CaptureRegions.back() == OMPD_parallel &&
378 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000379 }
380 }
381 void VisitCapturedStmt(const CapturedStmt *S) {
382 if (!S)
383 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000384 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
386 const ValueDecl *VD = C.getCapturedVar();
387 markAsEscaped(VD);
388 if (isa<OMPCapturedExprDecl>(VD))
389 VisitValueDecl(VD);
390 }
391 }
392 }
393 void VisitLambdaExpr(const LambdaExpr *E) {
394 if (!E)
395 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000396 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000397 if (C.capturesVariable()) {
398 if (C.getCaptureKind() == LCK_ByRef) {
399 const ValueDecl *VD = C.getCapturedVar();
400 markAsEscaped(VD);
401 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
402 VisitValueDecl(VD);
403 }
404 }
405 }
406 }
407 void VisitBlockExpr(const BlockExpr *E) {
408 if (!E)
409 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000410 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000411 if (C.isByRef()) {
412 const VarDecl *VD = C.getVariable();
413 markAsEscaped(VD);
414 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
415 VisitValueDecl(VD);
416 }
417 }
418 }
419 void VisitCallExpr(const CallExpr *E) {
420 if (!E)
421 return;
422 for (const Expr *Arg : E->arguments()) {
423 if (!Arg)
424 continue;
425 if (Arg->isLValue()) {
426 const bool SavedAllEscaped = AllEscaped;
427 AllEscaped = true;
428 Visit(Arg);
429 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000430 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000432 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000433 }
434 Visit(E->getCallee());
435 }
436 void VisitDeclRefExpr(const DeclRefExpr *E) {
437 if (!E)
438 return;
439 const ValueDecl *VD = E->getDecl();
440 if (AllEscaped)
441 markAsEscaped(VD);
442 if (isa<OMPCapturedExprDecl>(VD))
443 VisitValueDecl(VD);
444 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
445 if (VarD->isInitCapture())
446 VisitValueDecl(VD);
447 }
448 void VisitUnaryOperator(const UnaryOperator *E) {
449 if (!E)
450 return;
451 if (E->getOpcode() == UO_AddrOf) {
452 const bool SavedAllEscaped = AllEscaped;
453 AllEscaped = true;
454 Visit(E->getSubExpr());
455 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000456 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000457 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000458 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000459 }
460 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
461 if (!E)
462 return;
463 if (E->getCastKind() == CK_ArrayToPointerDecay) {
464 const bool SavedAllEscaped = AllEscaped;
465 AllEscaped = true;
466 Visit(E->getSubExpr());
467 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000468 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000469 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000470 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 }
472 void VisitExpr(const Expr *E) {
473 if (!E)
474 return;
475 bool SavedAllEscaped = AllEscaped;
476 if (!E->isLValue())
477 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000478 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000479 if (Child)
480 Visit(Child);
481 AllEscaped = SavedAllEscaped;
482 }
483 void VisitStmt(const Stmt *S) {
484 if (!S)
485 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000486 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000487 if (Child)
488 Visit(Child);
489 }
490
Alexey Bataevc99042b2018-03-15 18:10:54 +0000491 /// Returns the record that handles all the escaped local variables and used
492 /// instead of their original storage.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000493 const RecordDecl *getGlobalizedRecord() {
494 if (!GlobalizedRD)
495 buildRecordForGlobalizedVars();
496 return GlobalizedRD;
497 }
498
Alexey Bataevc99042b2018-03-15 18:10:54 +0000499 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000500 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
501 assert(GlobalizedRD &&
502 "Record for globalized variables must be generated already.");
503 auto I = MappedDeclsFields.find(VD);
504 if (I == MappedDeclsFields.end())
505 return nullptr;
506 return I->getSecond();
507 }
508
Alexey Bataevc99042b2018-03-15 18:10:54 +0000509 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000510 ArrayRef<const ValueDecl *> getEscapedDecls() const {
511 return EscapedDecls.getArrayRef();
512 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000513
514 /// Checks if the escaped local variable is actually a parameter passed by
515 /// value.
516 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
517 return EscapedParameters;
518 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000519
520 /// Returns the list of the escaped variables with the variably modified
521 /// types.
522 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
523 return EscapedVariableLengthDecls.getArrayRef();
524 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000525};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000526} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000527
528/// Get the GPU warp size.
529static llvm::Value *getNVPTXWarpSize(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_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000533 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000534}
535
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000536/// Get the id of the current thread on the GPU.
537static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000538 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000539 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000540 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000541 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000542}
543
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000544/// Get the id of the warp in the block.
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 *getNVPTXWarpID(CodeGenFunction &CGF) {
548 CGBuilderTy &Bld = CGF.Builder;
549 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
550}
551
552/// Get the id of the current lane in the Warp.
553/// We assume that the warp size is 32, which is always the case
554/// on the NVPTX device, to generate more efficient code.
555static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
556 CGBuilderTy &Bld = CGF.Builder;
557 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
558 "nvptx_lane_id");
559}
560
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000561/// Get the maximum number of threads in a block of the GPU.
562static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000563 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000564 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000565 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000566 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000567}
568
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000569/// Get barrier to synchronize all threads in a block.
570static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000571 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000572 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000573}
574
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000575/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
576/// a CTA.
577static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
578 llvm::Value *NumThreads) {
579 CGBuilderTy &Bld = CGF.Builder;
580 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000581 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
582 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
583 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000584}
585
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000586/// Synchronize all GPU threads in a block.
587static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000588
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000589/// Synchronize worker threads in a parallel region.
590static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
591 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
592}
593
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000594/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000595/// For the 'generic' execution mode, the runtime encodes thread_limit in
596/// the launch parameters, always starting thread_limit+warpSize threads per
597/// CTA. The threads in the last warp are reserved for master execution.
598/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
599static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000600 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000601 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000602 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000603 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000604 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
605 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000606}
607
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000608/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000609/// The master thread id is the first thread (lane) of the last warp in the
610/// GPU block. Warp size is assumed to be some power of 2.
611/// Thread id is 0 indexed.
612/// E.g: If NumThreads is 33, master id is 32.
613/// If NumThreads is 64, master id is 32.
614/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000615static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000616 CGBuilderTy &Bld = CGF.Builder;
617 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
618
619 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000620 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000621
Alexey Bataeve290ec02018-04-06 16:03:36 +0000622 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000623 Bld.CreateNot(Mask), "master_tid");
624}
625
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000627 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000628 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
629 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000630 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000631}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000632
633void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
634 CodeGenModule &CGM) {
635 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000636
637 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000638 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000639 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000640 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000641 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000642}
643
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000644CGOpenMPRuntimeNVPTX::ExecutionMode
645CGOpenMPRuntimeNVPTX::getExecutionMode() const {
646 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000647}
648
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000649static CGOpenMPRuntimeNVPTX::DataSharingMode
650getDataSharingMode(CodeGenModule &CGM) {
651 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
652 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000653}
654
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000655/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
656/// iff there is only one.
657static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000658 if (const auto *C = dyn_cast<CompoundStmt>(Body))
659 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000660 return C->body_front();
661 return Body;
662}
663
664/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000665/// false condition. Also, check if the number of threads is strictly specified
666/// and run those directives in non-SPMD mode.
667static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
668 const OMPExecutableDirective &D) {
669 if (D.hasClausesOfKind<OMPNumThreadsClause>())
670 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000671 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
672 OpenMPDirectiveKind NameModifier = C->getNameModifier();
673 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
674 continue;
675 const Expr *Cond = C->getCondition();
676 bool Result;
677 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
678 return true;
679 }
680 return false;
681}
682
683/// Check for inner (nested) SPMD construct, if any
684static bool hasNestedSPMDDirective(ASTContext &Ctx,
685 const OMPExecutableDirective &D) {
686 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000687 const auto *Body =
688 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000689 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000690
691 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
692 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000693 switch (D.getDirectiveKind()) {
694 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000695 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000696 !hasParallelIfNumThreadsClause(Ctx, *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 Bataev2adecff2018-09-21 14:22:53 +0000707 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000708 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000709 }
710 }
711 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000712 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000713 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000714 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000715 case OMPD_target_simd:
716 case OMPD_target_parallel:
717 case OMPD_target_parallel_for:
718 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000719 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000720 case OMPD_target_teams_distribute_simd:
721 case OMPD_target_teams_distribute_parallel_for:
722 case OMPD_target_teams_distribute_parallel_for_simd:
723 case OMPD_parallel:
724 case OMPD_for:
725 case OMPD_parallel_for:
726 case OMPD_parallel_sections:
727 case OMPD_for_simd:
728 case OMPD_parallel_for_simd:
729 case OMPD_cancel:
730 case OMPD_cancellation_point:
731 case OMPD_ordered:
732 case OMPD_threadprivate:
733 case OMPD_task:
734 case OMPD_simd:
735 case OMPD_sections:
736 case OMPD_section:
737 case OMPD_single:
738 case OMPD_master:
739 case OMPD_critical:
740 case OMPD_taskyield:
741 case OMPD_barrier:
742 case OMPD_taskwait:
743 case OMPD_taskgroup:
744 case OMPD_atomic:
745 case OMPD_flush:
746 case OMPD_teams:
747 case OMPD_target_data:
748 case OMPD_target_exit_data:
749 case OMPD_target_enter_data:
750 case OMPD_distribute:
751 case OMPD_distribute_simd:
752 case OMPD_distribute_parallel_for:
753 case OMPD_distribute_parallel_for_simd:
754 case OMPD_teams_distribute:
755 case OMPD_teams_distribute_simd:
756 case OMPD_teams_distribute_parallel_for:
757 case OMPD_teams_distribute_parallel_for_simd:
758 case OMPD_target_update:
759 case OMPD_declare_simd:
760 case OMPD_declare_target:
761 case OMPD_end_declare_target:
762 case OMPD_declare_reduction:
763 case OMPD_taskloop:
764 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000765 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000766 case OMPD_unknown:
767 llvm_unreachable("Unexpected directive.");
768 }
769 }
770
771 return false;
772}
773
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000774static bool supportsSPMDExecutionMode(ASTContext &Ctx,
775 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000776 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
777 switch (DirectiveKind) {
778 case OMPD_target:
779 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000780 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000781 case OMPD_target_parallel:
782 case OMPD_target_parallel_for:
783 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000784 case OMPD_target_teams_distribute_parallel_for:
785 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000786 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000787 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000788 case OMPD_target_teams_distribute:
789 case OMPD_target_teams_distribute_simd:
790 return false;
791 case OMPD_parallel:
792 case OMPD_for:
793 case OMPD_parallel_for:
794 case OMPD_parallel_sections:
795 case OMPD_for_simd:
796 case OMPD_parallel_for_simd:
797 case OMPD_cancel:
798 case OMPD_cancellation_point:
799 case OMPD_ordered:
800 case OMPD_threadprivate:
801 case OMPD_task:
802 case OMPD_simd:
803 case OMPD_sections:
804 case OMPD_section:
805 case OMPD_single:
806 case OMPD_master:
807 case OMPD_critical:
808 case OMPD_taskyield:
809 case OMPD_barrier:
810 case OMPD_taskwait:
811 case OMPD_taskgroup:
812 case OMPD_atomic:
813 case OMPD_flush:
814 case OMPD_teams:
815 case OMPD_target_data:
816 case OMPD_target_exit_data:
817 case OMPD_target_enter_data:
818 case OMPD_distribute:
819 case OMPD_distribute_simd:
820 case OMPD_distribute_parallel_for:
821 case OMPD_distribute_parallel_for_simd:
822 case OMPD_teams_distribute:
823 case OMPD_teams_distribute_simd:
824 case OMPD_teams_distribute_parallel_for:
825 case OMPD_teams_distribute_parallel_for_simd:
826 case OMPD_target_update:
827 case OMPD_declare_simd:
828 case OMPD_declare_target:
829 case OMPD_end_declare_target:
830 case OMPD_declare_reduction:
831 case OMPD_taskloop:
832 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000833 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000834 case OMPD_unknown:
835 break;
836 }
837 llvm_unreachable(
838 "Unknown programming model for OpenMP directive on NVPTX target.");
839}
840
841/// Check if the directive is loops based and has schedule clause at all or has
842/// static scheduling.
843static bool hasStaticScheduling(const OMPExecutableDirective &D) {
844 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
845 isOpenMPLoopDirective(D.getDirectiveKind()) &&
846 "Expected loop-based directive.");
847 return !D.hasClausesOfKind<OMPOrderedClause>() &&
848 (!D.hasClausesOfKind<OMPScheduleClause>() ||
849 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
850 [](const OMPScheduleClause *C) {
851 return C->getScheduleKind() == OMPC_SCHEDULE_static;
852 }));
853}
854
855/// Check for inner (nested) lightweight runtime construct, if any
856static bool hasNestedLightweightDirective(ASTContext &Ctx,
857 const OMPExecutableDirective &D) {
858 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
859 const auto *CS = D.getInnermostCapturedStmt();
860 const auto *Body =
861 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
862 const Stmt *ChildStmt = getSingleCompoundChild(Body);
863
864 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
865 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
866 switch (D.getDirectiveKind()) {
867 case OMPD_target:
868 if (isOpenMPParallelDirective(DKind) &&
869 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
870 hasStaticScheduling(*NestedDir))
871 return true;
872 if (DKind == OMPD_parallel) {
873 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
874 /*IgnoreCaptured=*/true);
875 if (!Body)
876 return false;
877 ChildStmt = getSingleCompoundChild(Body);
878 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
879 DKind = NND->getDirectiveKind();
880 if (isOpenMPWorksharingDirective(DKind) &&
881 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
882 return true;
883 }
884 } else if (DKind == OMPD_teams) {
885 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
886 /*IgnoreCaptured=*/true);
887 if (!Body)
888 return false;
889 ChildStmt = getSingleCompoundChild(Body);
890 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
891 DKind = NND->getDirectiveKind();
892 if (isOpenMPParallelDirective(DKind) &&
893 isOpenMPWorksharingDirective(DKind) &&
894 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
895 return true;
896 if (DKind == OMPD_parallel) {
897 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
898 /*IgnoreCaptured=*/true);
899 if (!Body)
900 return false;
901 ChildStmt = getSingleCompoundChild(Body);
902 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
903 DKind = NND->getDirectiveKind();
904 if (isOpenMPWorksharingDirective(DKind) &&
905 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
906 return true;
907 }
908 }
909 }
910 }
911 return false;
912 case OMPD_target_teams:
913 if (isOpenMPParallelDirective(DKind) &&
914 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
915 hasStaticScheduling(*NestedDir))
916 return true;
917 if (DKind == OMPD_parallel) {
918 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
919 /*IgnoreCaptured=*/true);
920 if (!Body)
921 return false;
922 ChildStmt = getSingleCompoundChild(Body);
923 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
924 DKind = NND->getDirectiveKind();
925 if (isOpenMPWorksharingDirective(DKind) &&
926 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
927 return true;
928 }
929 }
930 return false;
931 case OMPD_target_parallel:
932 return isOpenMPWorksharingDirective(DKind) &&
933 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
934 case OMPD_target_teams_distribute:
935 case OMPD_target_simd:
936 case OMPD_target_parallel_for:
937 case OMPD_target_parallel_for_simd:
938 case OMPD_target_teams_distribute_simd:
939 case OMPD_target_teams_distribute_parallel_for:
940 case OMPD_target_teams_distribute_parallel_for_simd:
941 case OMPD_parallel:
942 case OMPD_for:
943 case OMPD_parallel_for:
944 case OMPD_parallel_sections:
945 case OMPD_for_simd:
946 case OMPD_parallel_for_simd:
947 case OMPD_cancel:
948 case OMPD_cancellation_point:
949 case OMPD_ordered:
950 case OMPD_threadprivate:
951 case OMPD_task:
952 case OMPD_simd:
953 case OMPD_sections:
954 case OMPD_section:
955 case OMPD_single:
956 case OMPD_master:
957 case OMPD_critical:
958 case OMPD_taskyield:
959 case OMPD_barrier:
960 case OMPD_taskwait:
961 case OMPD_taskgroup:
962 case OMPD_atomic:
963 case OMPD_flush:
964 case OMPD_teams:
965 case OMPD_target_data:
966 case OMPD_target_exit_data:
967 case OMPD_target_enter_data:
968 case OMPD_distribute:
969 case OMPD_distribute_simd:
970 case OMPD_distribute_parallel_for:
971 case OMPD_distribute_parallel_for_simd:
972 case OMPD_teams_distribute:
973 case OMPD_teams_distribute_simd:
974 case OMPD_teams_distribute_parallel_for:
975 case OMPD_teams_distribute_parallel_for_simd:
976 case OMPD_target_update:
977 case OMPD_declare_simd:
978 case OMPD_declare_target:
979 case OMPD_end_declare_target:
980 case OMPD_declare_reduction:
981 case OMPD_taskloop:
982 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000983 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000984 case OMPD_unknown:
985 llvm_unreachable("Unexpected directive.");
986 }
987 }
988
989 return false;
990}
991
992/// Checks if the construct supports lightweight runtime. It must be SPMD
993/// construct + inner loop-based construct with static scheduling.
994static bool supportsLightweightRuntime(ASTContext &Ctx,
995 const OMPExecutableDirective &D) {
996 if (!supportsSPMDExecutionMode(Ctx, D))
997 return false;
998 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
999 switch (DirectiveKind) {
1000 case OMPD_target:
1001 case OMPD_target_teams:
1002 case OMPD_target_parallel:
1003 return hasNestedLightweightDirective(Ctx, D);
1004 case OMPD_target_parallel_for:
1005 case OMPD_target_parallel_for_simd:
1006 case OMPD_target_teams_distribute_parallel_for:
1007 case OMPD_target_teams_distribute_parallel_for_simd:
1008 // (Last|First)-privates must be shared in parallel region.
1009 return hasStaticScheduling(D);
1010 case OMPD_target_simd:
1011 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001012 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001013 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001014 case OMPD_parallel:
1015 case OMPD_for:
1016 case OMPD_parallel_for:
1017 case OMPD_parallel_sections:
1018 case OMPD_for_simd:
1019 case OMPD_parallel_for_simd:
1020 case OMPD_cancel:
1021 case OMPD_cancellation_point:
1022 case OMPD_ordered:
1023 case OMPD_threadprivate:
1024 case OMPD_task:
1025 case OMPD_simd:
1026 case OMPD_sections:
1027 case OMPD_section:
1028 case OMPD_single:
1029 case OMPD_master:
1030 case OMPD_critical:
1031 case OMPD_taskyield:
1032 case OMPD_barrier:
1033 case OMPD_taskwait:
1034 case OMPD_taskgroup:
1035 case OMPD_atomic:
1036 case OMPD_flush:
1037 case OMPD_teams:
1038 case OMPD_target_data:
1039 case OMPD_target_exit_data:
1040 case OMPD_target_enter_data:
1041 case OMPD_distribute:
1042 case OMPD_distribute_simd:
1043 case OMPD_distribute_parallel_for:
1044 case OMPD_distribute_parallel_for_simd:
1045 case OMPD_teams_distribute:
1046 case OMPD_teams_distribute_simd:
1047 case OMPD_teams_distribute_parallel_for:
1048 case OMPD_teams_distribute_parallel_for_simd:
1049 case OMPD_target_update:
1050 case OMPD_declare_simd:
1051 case OMPD_declare_target:
1052 case OMPD_end_declare_target:
1053 case OMPD_declare_reduction:
1054 case OMPD_taskloop:
1055 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001056 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001057 case OMPD_unknown:
1058 break;
1059 }
1060 llvm_unreachable(
1061 "Unknown programming model for OpenMP directive on NVPTX target.");
1062}
1063
1064void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001065 StringRef ParentName,
1066 llvm::Function *&OutlinedFn,
1067 llvm::Constant *&OutlinedFnID,
1068 bool IsOffloadEntry,
1069 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001070 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001071 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001072 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001073 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001074 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001075
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001076 // Emit target region as a standalone region.
1077 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001078 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1079 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001080
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001081 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001082 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001083 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001084 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001085 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001086 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001087 .emitNonSPMDEntryHeader(CGF, EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001088 }
1089 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001090 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001091 .emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001092 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001093 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001094 CodeGen.setAction(Action);
1095 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1096 IsOffloadEntry, CodeGen);
1097
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001098 // Now change the name of the worker function to correspond to this target
1099 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001100 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001101
1102 // Create the worker function
1103 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001104}
1105
1106// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001107void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001108 EntryFunctionState &EST,
1109 WorkerFunctionState &WST) {
1110 CGBuilderTy &Bld = CGF.Builder;
1111
1112 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1113 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1114 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1115 EST.ExitBB = CGF.createBasicBlock(".exit");
1116
Alexey Bataev9ff80832018-04-16 20:16:21 +00001117 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001118 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1119 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1120
1121 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001122 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001123 CGF.EmitBranch(EST.ExitBB);
1124
1125 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001126 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1128 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1129
1130 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001131 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001132 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 // First action in sequential region:
1134 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001135 // TODO: Optimize runtime initialization and pass in correct value.
1136 llvm::Value *Args[] = {getThreadLimit(CGF),
1137 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138 CGF.EmitRuntimeCall(
1139 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001140
1141 // For data sharing, we need to initialize the stack.
1142 CGF.EmitRuntimeCall(
1143 createNVPTXRuntimeFunction(
1144 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1145
Alexey Bataevc99042b2018-03-15 18:10:54 +00001146 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001147}
1148
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001149void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001150 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001151 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001152 if (!CGF.HaveInsertPoint())
1153 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001154
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001155 emitGenericVarsEpilog(CGF);
1156
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001157 if (!EST.ExitBB)
1158 EST.ExitBB = CGF.createBasicBlock(".exit");
1159
1160 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1161 CGF.EmitBranch(TerminateBB);
1162
1163 CGF.EmitBlock(TerminateBB);
1164 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001165 // TODO: Optimize runtime initialization and pass in correct value.
1166 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001168 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 // Barrier to terminate worker threads.
1170 syncCTAThreads(CGF);
1171 // Master thread jumps to exit point.
1172 CGF.EmitBranch(EST.ExitBB);
1173
1174 CGF.EmitBlock(EST.ExitBB);
1175 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001176}
1177
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001178void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001179 StringRef ParentName,
1180 llvm::Function *&OutlinedFn,
1181 llvm::Constant *&OutlinedFnID,
1182 bool IsOffloadEntry,
1183 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001184 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001185 EntryFunctionState EST;
1186
1187 // Emit target region as a standalone region.
1188 class NVPTXPrePostActionTy : public PrePostActionTy {
1189 CGOpenMPRuntimeNVPTX &RT;
1190 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1191 const OMPExecutableDirective &D;
1192
1193 public:
1194 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1195 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1196 const OMPExecutableDirective &D)
1197 : RT(RT), EST(EST), D(D) {}
1198 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001199 RT.emitSPMDEntryHeader(CGF, EST, D);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001200 }
1201 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001202 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001203 }
1204 } Action(*this, EST, D);
1205 CodeGen.setAction(Action);
1206 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1207 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001208}
1209
Alexey Bataeve79451a2018-10-01 16:20:57 +00001210static void
1211getDistributeLastprivateVars(const OMPExecutableDirective &D,
1212 llvm::SmallVectorImpl<const ValueDecl *> &Vars);
1213
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001214void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001215 CodeGenFunction &CGF, EntryFunctionState &EST,
1216 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001217 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001218
1219 // Setup BBs in entry function.
1220 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1221 EST.ExitBB = CGF.createBasicBlock(".exit");
1222
1223 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev80a9a612018-08-30 14:45:24 +00001224 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1225 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataeve79451a2018-10-01 16:20:57 +00001226 // Check if we have inner distribute + lastprivate|reduction clauses.
1227 bool RequiresDatasharing = RequiresFullRuntime;
1228 if (!RequiresDatasharing) {
1229 const OMPExecutableDirective *TD = &D;
1230 if (!isOpenMPTeamsDirective(TD->getDirectiveKind()) &&
1231 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1232 const Stmt *S = getSingleCompoundChild(
1233 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1234 /*IgnoreCaptured=*/true));
1235 TD = cast<OMPExecutableDirective>(S);
1236 }
1237 if (!isOpenMPDistributeDirective(TD->getDirectiveKind()) &&
1238 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1239 const Stmt *S = getSingleCompoundChild(
1240 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1241 /*IgnoreCaptured=*/true));
1242 TD = cast<OMPExecutableDirective>(S);
1243 }
1244 if (isOpenMPDistributeDirective(TD->getDirectiveKind()))
1245 RequiresDatasharing = TD->hasClausesOfKind<OMPLastprivateClause>() ||
1246 TD->hasClausesOfKind<OMPReductionClause>();
1247 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001248 llvm::Value *Args[] = {
1249 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1250 /*RequiresOMPRuntime=*/
1251 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
Alexey Bataeve79451a2018-10-01 16:20:57 +00001252 /*RequiresDataSharing=*/Bld.getInt16(RequiresDatasharing ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001253 CGF.EmitRuntimeCall(
1254 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001255
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001256 if (RequiresFullRuntime) {
1257 // For data sharing, we need to initialize the stack.
1258 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1259 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1260 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001261
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001262 CGF.EmitBranch(ExecuteBB);
1263
1264 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001265
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001266 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001267}
1268
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001269void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001270 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001271 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001272 if (!CGF.HaveInsertPoint())
1273 return;
1274
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001275 if (!EST.ExitBB)
1276 EST.ExitBB = CGF.createBasicBlock(".exit");
1277
1278 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1279 CGF.EmitBranch(OMPDeInitBB);
1280
1281 CGF.EmitBlock(OMPDeInitBB);
1282 // DeInitialize the OMP state in the runtime; called by all active threads.
1283 CGF.EmitRuntimeCall(
1284 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1285 CGF.EmitBranch(EST.ExitBB);
1286
1287 CGF.EmitBlock(EST.ExitBB);
1288 EST.ExitBB = nullptr;
1289}
1290
1291// Create a unique global variable to indicate the execution mode of this target
1292// region. The execution mode is either 'generic', or 'spmd' depending on the
1293// target directive. This variable is picked up by the offload library to setup
1294// the device appropriately before kernel launch. If the execution mode is
1295// 'generic', the runtime reserves one warp for the master, otherwise, all
1296// warps participate in parallel work.
1297static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001298 bool Mode) {
1299 auto *GVMode =
1300 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1301 llvm::GlobalValue::WeakAnyLinkage,
1302 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1303 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001304 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001305}
1306
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001307void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001308 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001309
1310 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001311 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001312 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001313 emitWorkerLoop(CGF, WST);
1314 CGF.FinishFunction();
1315}
1316
1317void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1318 WorkerFunctionState &WST) {
1319 //
1320 // The workers enter this loop and wait for parallel work from the master.
1321 // When the master encounters a parallel region it sets up the work + variable
1322 // arguments, and wakes up the workers. The workers first check to see if
1323 // they are required for the parallel region, i.e., within the # of requested
1324 // parallel threads. The activated workers load the variable arguments and
1325 // execute the parallel work.
1326 //
1327
1328 CGBuilderTy &Bld = CGF.Builder;
1329
1330 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1331 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1332 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1333 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1334 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1335 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1336
1337 CGF.EmitBranch(AwaitBB);
1338
1339 // Workers wait for work from master.
1340 CGF.EmitBlock(AwaitBB);
1341 // Wait for parallel work
1342 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001343
1344 Address WorkFn =
1345 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1346 Address ExecStatus =
1347 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1348 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1349 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1350
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001351 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001352 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001353 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001354 llvm::Value *Ret = CGF.EmitRuntimeCall(
1355 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1356 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001357
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001358 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001359 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1360 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001361 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1362
1363 // Activate requested workers.
1364 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001365 llvm::Value *IsActive =
1366 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1367 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001368
1369 // Signal start of parallel region.
1370 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001371
1372 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001373 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001374 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001375 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001376
1377 llvm::Value *WorkFnMatch =
1378 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1379
1380 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1381 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1382 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1383
1384 // Execute this outlined function.
1385 CGF.EmitBlock(ExecuteFNBB);
1386
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001387 // Insert call to work function via shared wrapper. The shared
1388 // wrapper takes two arguments:
1389 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001390 // - the thread ID;
1391 emitCall(CGF, WST.Loc, W,
1392 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001393
1394 // Go to end of parallel region.
1395 CGF.EmitBranch(TerminateBB);
1396
1397 CGF.EmitBlock(CheckNextBB);
1398 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001399 // Default case: call to outlined function through pointer if the target
1400 // region makes a declare target call that may contain an orphaned parallel
1401 // directive.
1402 auto *ParallelFnTy =
1403 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1404 /*isVarArg=*/false)
1405 ->getPointerTo();
1406 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1407 // Insert call to work function via shared wrapper. The shared
1408 // wrapper takes two arguments:
1409 // - the parallelism level;
1410 // - the thread ID;
1411 emitCall(CGF, WST.Loc, WorkFnCast,
1412 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1413 // Go to end of parallel region.
1414 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001415
1416 // Signal end of parallel region.
1417 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001418 CGF.EmitRuntimeCall(
1419 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1420 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001421 CGF.EmitBranch(BarrierBB);
1422
1423 // All active and inactive workers wait at a barrier after parallel region.
1424 CGF.EmitBlock(BarrierBB);
1425 // Barrier after parallel region.
1426 syncCTAThreads(CGF);
1427 CGF.EmitBranch(AwaitBB);
1428
1429 // Exit target region.
1430 CGF.EmitBlock(ExitBB);
1431}
1432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001433/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001434/// implementation. Specialized for the NVPTX device.
1435/// \param Function OpenMP runtime function.
1436/// \return Specified function.
1437llvm::Constant *
1438CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1439 llvm::Constant *RTLFn = nullptr;
1440 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1441 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001442 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1443 // RequiresOMPRuntime);
1444 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001445 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001446 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1447 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1448 break;
1449 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001450 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001451 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1452 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001453 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001454 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001455 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1456 break;
1457 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001458 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1459 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001460 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001461 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001462 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001463 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1464 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1465 break;
1466 }
1467 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1468 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001469 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001470 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1471 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1472 break;
1473 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001474 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1475 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001476 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001477 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001478 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001479 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1480 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1481 break;
1482 }
1483 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001484 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1485 /// int16_t IsOMPRuntimeInitialized);
1486 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001487 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001488 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001489 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1491 break;
1492 }
1493 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1494 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001495 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001496 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1497 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1498 break;
1499 }
1500 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1501 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1502 // global_tid);
1503 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001504 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001505 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1506 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1507 break;
1508 }
1509 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1510 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1511 // global_tid);
1512 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001513 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1515 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1516 break;
1517 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001518 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1519 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1520 // int16_t lane_offset, int16_t warp_size);
1521 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001522 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001523 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1524 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1525 break;
1526 }
1527 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1528 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1529 // int16_t lane_offset, int16_t warp_size);
1530 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001531 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001532 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1533 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1534 break;
1535 }
1536 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1537 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1538 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1539 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1540 // lane_offset, int16_t Algorithm Version),
1541 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1542 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1543 CGM.Int16Ty, CGM.Int16Ty};
1544 auto *ShuffleReduceFnTy =
1545 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1546 /*isVarArg=*/false);
1547 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1548 auto *InterWarpCopyFnTy =
1549 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1550 /*isVarArg=*/false);
1551 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1552 CGM.Int32Ty,
1553 CGM.SizeTy,
1554 CGM.VoidPtrTy,
1555 ShuffleReduceFnTy->getPointerTo(),
1556 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001557 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001558 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1559 RTLFn = CGM.CreateRuntimeFunction(
1560 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1561 break;
1562 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001563 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1564 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1565 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1566 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1567 // lane_offset, int16_t Algorithm Version),
1568 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1569 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1570 CGM.Int16Ty, CGM.Int16Ty};
1571 auto *ShuffleReduceFnTy =
1572 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1573 /*isVarArg=*/false);
1574 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1575 auto *InterWarpCopyFnTy =
1576 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1577 /*isVarArg=*/false);
1578 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1579 CGM.Int32Ty,
1580 CGM.SizeTy,
1581 CGM.VoidPtrTy,
1582 ShuffleReduceFnTy->getPointerTo(),
1583 InterWarpCopyFnTy->getPointerTo()};
1584 auto *FnTy =
1585 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1586 RTLFn = CGM.CreateRuntimeFunction(
1587 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1588 break;
1589 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001590 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1591 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1592 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1593 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1594 // lane_offset, int16_t shortCircuit),
1595 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1596 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1597 // int32_t index, int32_t width),
1598 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1599 // int32_t index, int32_t width, int32_t reduce))
1600 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1601 CGM.Int16Ty, CGM.Int16Ty};
1602 auto *ShuffleReduceFnTy =
1603 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1604 /*isVarArg=*/false);
1605 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1606 auto *InterWarpCopyFnTy =
1607 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1608 /*isVarArg=*/false);
1609 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1610 CGM.Int32Ty, CGM.Int32Ty};
1611 auto *CopyToScratchpadFnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1613 /*isVarArg=*/false);
1614 llvm::Type *LoadReduceTypeParams[] = {
1615 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1616 auto *LoadReduceFnTy =
1617 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1618 /*isVarArg=*/false);
1619 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1620 CGM.Int32Ty,
1621 CGM.SizeTy,
1622 CGM.VoidPtrTy,
1623 ShuffleReduceFnTy->getPointerTo(),
1624 InterWarpCopyFnTy->getPointerTo(),
1625 CopyToScratchpadFnTy->getPointerTo(),
1626 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001627 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001628 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1629 RTLFn = CGM.CreateRuntimeFunction(
1630 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1631 break;
1632 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001633 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1634 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1635 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001636 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001637 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1638 RTLFn = CGM.CreateRuntimeFunction(
1639 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1640 break;
1641 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001642 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1643 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001644 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001645 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1646 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1647 break;
1648 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001649 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1650 /// Build void __kmpc_data_sharing_init_stack_spmd();
1651 auto *FnTy =
1652 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001653 RTLFn =
1654 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001655 break;
1656 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001657 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1658 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1659 // int16_t UseSharedMemory);
1660 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001661 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001662 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1663 RTLFn = CGM.CreateRuntimeFunction(
1664 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1665 break;
1666 }
1667 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1668 // Build void __kmpc_data_sharing_pop_stack(void *a);
1669 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
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,
1673 /*Name=*/"__kmpc_data_sharing_pop_stack");
1674 break;
1675 }
1676 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1677 /// Build void __kmpc_begin_sharing_variables(void ***args,
1678 /// size_t n_args);
1679 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001680 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001681 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1682 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1683 break;
1684 }
1685 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1686 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001687 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001688 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1689 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1690 break;
1691 }
1692 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1693 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1694 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001695 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001696 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1697 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1698 break;
1699 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001700 case OMPRTL_NVPTX__kmpc_parallel_level: {
1701 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1702 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1703 auto *FnTy =
1704 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1705 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1706 break;
1707 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001708 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1709 // Build int8_t __kmpc_is_spmd_exec_mode();
1710 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1712 break;
1713 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001714 }
1715 return RTLFn;
1716}
1717
1718void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1719 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001720 uint64_t Size, int32_t,
1721 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001722 // TODO: Add support for global variables on the device after declare target
1723 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001724 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001725 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001726 llvm::Module &M = CGM.getModule();
1727 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001728
1729 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001730 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001731
1732 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001733 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001734 llvm::ConstantAsMetadata::get(
1735 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1736 // Append metadata to nvvm.annotations
1737 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1738}
1739
1740void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1741 const OMPExecutableDirective &D, StringRef ParentName,
1742 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001743 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001744 if (!IsOffloadEntry) // Nothing to do.
1745 return;
1746
1747 assert(!ParentName.empty() && "Invalid target region parent name!");
1748
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001749 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001750 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001751 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001752 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001753 else
1754 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1755 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001756
1757 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001758}
1759
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001760CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001761 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001762 if (!CGM.getLangOpts().OpenMPIsDevice)
1763 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001764}
Carlo Bertollic6872252016-04-04 15:55:02 +00001765
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001766void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1767 OpenMPProcBindClauseKind ProcBind,
1768 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001769 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001770 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001771 return;
1772
1773 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1774}
1775
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001776void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1777 llvm::Value *NumThreads,
1778 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001779 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001780 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001781 return;
1782
1783 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1784}
1785
Carlo Bertollic6872252016-04-04 15:55:02 +00001786void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1787 const Expr *NumTeams,
1788 const Expr *ThreadLimit,
1789 SourceLocation Loc) {}
1790
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001791llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1792 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1793 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001794 // Emit target region as a standalone region.
1795 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001796 bool &IsInParallelRegion;
1797 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001798
1799 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001800 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1801 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001802 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001803 PrevIsInParallelRegion = IsInParallelRegion;
1804 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001805 }
1806 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001807 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001808 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001809 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001810 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001811 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1812 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001813 auto *OutlinedFun =
1814 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1815 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001816 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001817 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1818 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001819 llvm::Function *WrapperFun =
1820 createParallelDataSharingWrapper(OutlinedFun, D);
1821 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1822 }
1823
1824 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001825}
1826
Alexey Bataev2adecff2018-09-21 14:22:53 +00001827/// Get list of lastprivate variables from the teams distribute ... or
1828/// teams {distribute ...} directives.
1829static void
1830getDistributeLastprivateVars(const OMPExecutableDirective &D,
1831 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1832 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1833 "expected teams directive.");
1834 const OMPExecutableDirective *Dir = &D;
1835 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1836 if (const Stmt *S = getSingleCompoundChild(
1837 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1838 /*IgnoreCaptured=*/true))) {
1839 Dir = dyn_cast<OMPExecutableDirective>(S);
1840 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1841 Dir = nullptr;
1842 }
1843 }
1844 if (!Dir)
1845 return;
1846 for (const OMPLastprivateClause *C :
1847 Dir->getClausesOfKind<OMPLastprivateClause>()) {
1848 for (const Expr *E : C->getVarRefs()) {
1849 const auto *DE = cast<DeclRefExpr>(E->IgnoreParens());
1850 Vars.push_back(cast<ValueDecl>(DE->getDecl()->getCanonicalDecl()));
1851 }
1852 }
1853}
1854
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001855llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001856 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1857 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001858 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001859
Alexey Bataev2adecff2018-09-21 14:22:53 +00001860 const RecordDecl *GlobalizedRD = nullptr;
1861 llvm::SmallVector<const ValueDecl *, 4> LastPrivates;
1862 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1863 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
1864 getDistributeLastprivateVars(D, LastPrivates);
1865 if (!LastPrivates.empty())
1866 GlobalizedRD = buildRecordForGlobalizedVars(
1867 CGM.getContext(), LastPrivates, MappedDeclsFields);
1868 }
1869
Alexey Bataevc99042b2018-03-15 18:10:54 +00001870 // Emit target region as a standalone region.
1871 class NVPTXPrePostActionTy : public PrePostActionTy {
1872 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001873 const RecordDecl *GlobalizedRD;
1874 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1875 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001876
1877 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00001878 NVPTXPrePostActionTy(
1879 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1880 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1881 &MappedDeclsFields)
1882 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1883 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001884 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001885 auto &Rt =
1886 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1887 if (GlobalizedRD) {
1888 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1889 I->getSecond().GlobalRecord = GlobalizedRD;
1890 I->getSecond().MappedParams =
1891 llvm::make_unique<CodeGenFunction::OMPMapVars>();
1892 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1893 for (const auto &Pair : MappedDeclsFields) {
1894 assert(Pair.getFirst()->isCanonicalDecl() &&
1895 "Expected canonical declaration");
1896 Data.insert(std::make_pair(
1897 Pair.getFirst(),
1898 std::make_pair(Pair.getSecond(), Address::invalid())));
1899 }
1900 }
1901 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001902 }
1903 void Exit(CodeGenFunction &CGF) override {
1904 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1905 .emitGenericVarsEpilog(CGF);
1906 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00001907 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1908 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001909 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1910 D, ThreadIDVar, InnermostKind, CodeGen);
1911 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1912 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001913 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001914 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001915
1916 return OutlinedFun;
1917}
1918
Alexey Bataevc99042b2018-03-15 18:10:54 +00001919void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001920 SourceLocation Loc,
1921 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001922 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
1923 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001924 return;
1925
Alexey Bataevc99042b2018-03-15 18:10:54 +00001926 CGBuilderTy &Bld = CGF.Builder;
1927
1928 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1929 if (I == FunctionGlobalizedDecls.end())
1930 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001931 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1932 QualType RecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001933
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001934 // 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.
1938 unsigned Alignment =
1939 CGM.getContext().getTypeAlignInChars(RecTy).getQuantity();
1940 unsigned GlobalRecordSize =
1941 CGM.getContext().getTypeSizeInChars(RecTy).getQuantity();
1942 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001943
1944 llvm::Value *GlobalRecCastAddr;
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001945 if (WithSPMDCheck ||
1946 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001947 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1948 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1949 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1950 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1951 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1952 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1953 // There is no need to emit line number for unconditional branch.
1954 (void)ApplyDebugLocation::CreateEmpty(CGF);
1955 CGF.EmitBlock(SPMDBB);
1956 Address RecPtr = CGF.CreateMemTemp(RecTy, "_local_stack");
1957 CGF.EmitBranch(ExitBB);
1958 // There is no need to emit line number for unconditional branch.
1959 (void)ApplyDebugLocation::CreateEmpty(CGF);
1960 CGF.EmitBlock(NonSPMDBB);
1961 // TODO: allow the usage of shared memory to be controlled by
1962 // the user, for now, default to global.
1963 llvm::Value *GlobalRecordSizeArg[] = {
1964 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1965 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1966 llvm::Value *GlobalRecValue =
1967 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1968 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1969 GlobalRecordSizeArg);
1970 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1971 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1972 CGF.EmitBlock(ExitBB);
1973 auto *Phi = Bld.CreatePHI(GlobalRecCastAddr->getType(),
1974 /*NumReservedValues=*/2, "_select_stack");
1975 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
1976 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
1977 GlobalRecCastAddr = Phi;
1978 I->getSecond().GlobalRecordAddr = Phi;
1979 I->getSecond().IsInSPMDModeFlag = IsSPMD;
1980 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001981 // TODO: allow the usage of shared memory to be controlled by
1982 // the user, for now, default to global.
1983 llvm::Value *GlobalRecordSizeArg[] = {
1984 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1985 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1986 llvm::Value *GlobalRecValue =
1987 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1988 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
1989 GlobalRecordSizeArg);
1990 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1991 GlobalRecValue, CGF.ConvertTypeForMem(RecTy)->getPointerTo());
1992 I->getSecond().GlobalRecordAddr = GlobalRecValue;
1993 I->getSecond().IsInSPMDModeFlag = nullptr;
1994 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001995 LValue Base =
1996 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, RecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001997
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001998 // Emit the "global alloca" which is a GEP from the global declaration
1999 // record using the pointer returned by the runtime.
2000 for (auto &Rec : I->getSecond().LocalVarData) {
2001 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2002 llvm::Value *ParValue;
2003 if (EscapedParam) {
2004 const auto *VD = cast<VarDecl>(Rec.first);
2005 LValue ParLVal =
2006 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2007 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2008 }
2009 const FieldDecl *FD = Rec.second.first;
2010 LValue VarAddr = CGF.EmitLValueForField(Base, FD);
2011 Rec.second.second = VarAddr.getAddress();
2012 if (EscapedParam) {
2013 const auto *VD = cast<VarDecl>(Rec.first);
2014 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2015 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2016 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002017 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002018 }
2019 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2020 // Recover pointer to this function's global record. The runtime will
2021 // handle the specifics of the allocation of the memory.
2022 // Use actual memory size of the record including the padding
2023 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002024 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002025 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2026 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2027 Size = Bld.CreateNUWAdd(
2028 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2029 llvm::Value *AlignVal =
2030 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2031 Size = Bld.CreateUDiv(Size, AlignVal);
2032 Size = Bld.CreateNUWMul(Size, AlignVal);
2033 // TODO: allow the usage of shared memory to be controlled by
2034 // the user, for now, default to global.
2035 llvm::Value *GlobalRecordSizeArg[] = {
2036 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2037 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2038 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2039 GlobalRecordSizeArg);
2040 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2041 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2042 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2043 CGM.getContext().getDeclAlign(VD),
2044 AlignmentSource::Decl);
2045 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2046 Base.getAddress());
2047 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002048 }
2049 I->getSecond().MappedParams->apply(CGF);
2050}
2051
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002052void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2053 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002054 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2055 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002056 return;
2057
Alexey Bataevc99042b2018-03-15 18:10:54 +00002058 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002059 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002060 I->getSecond().MappedParams->restore(CGF);
2061 if (!CGF.HaveInsertPoint())
2062 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002063 for (llvm::Value *Addr :
2064 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2065 CGF.EmitRuntimeCall(
2066 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2067 Addr);
2068 }
2069 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002070 if (WithSPMDCheck ||
2071 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002072 CGBuilderTy &Bld = CGF.Builder;
2073 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2074 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2075 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2076 // There is no need to emit line number for unconditional branch.
2077 (void)ApplyDebugLocation::CreateEmpty(CGF);
2078 CGF.EmitBlock(NonSPMDBB);
2079 CGF.EmitRuntimeCall(
2080 createNVPTXRuntimeFunction(
2081 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2082 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2083 CGF.EmitBlock(ExitBB);
2084 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002085 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2086 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2087 I->getSecond().GlobalRecordAddr);
2088 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002089 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002090 }
2091}
2092
Carlo Bertollic6872252016-04-04 15:55:02 +00002093void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2094 const OMPExecutableDirective &D,
2095 SourceLocation Loc,
2096 llvm::Value *OutlinedFn,
2097 ArrayRef<llvm::Value *> CapturedVars) {
2098 if (!CGF.HaveInsertPoint())
2099 return;
2100
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002101 Address ZeroAddr = CGF.CreateMemTemp(
2102 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2103 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002104 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2105 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002106 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002107 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2108 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002109 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002110}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002111
2112void CGOpenMPRuntimeNVPTX::emitParallelCall(
2113 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2114 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2115 if (!CGF.HaveInsertPoint())
2116 return;
2117
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002118 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002119 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002120 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002121 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002122}
2123
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002124void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002125 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2126 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2127 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002128
2129 // Force inline this outlined function at its call site.
2130 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2131
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002132 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2133 /*DestWidth=*/32, /*Signed=*/1),
2134 ".zero.addr");
2135 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002136 // ThreadId for serialized parallels is 0.
2137 Address ThreadIDAddr = ZeroAddr;
2138 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002139 CodeGenFunction &CGF, PrePostActionTy &Action) {
2140 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002141
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002142 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2143 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2144 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2145 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2146 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2147 };
2148 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2149 PrePostActionTy &) {
2150
2151 RegionCodeGenTy RCG(CodeGen);
2152 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2153 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2154 llvm::Value *Args[] = {RTLoc, ThreadID};
2155
2156 NVPTXActionTy Action(
2157 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2158 Args,
2159 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2160 Args);
2161 RCG.setAction(Action);
2162 RCG(CGF);
2163 };
2164
2165 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2166 PrePostActionTy &Action) {
2167 CGBuilderTy &Bld = CGF.Builder;
2168 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2169 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002170 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2171
2172 // Prepare for parallel region. Indicate the outlined function.
2173 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002174 CGF.EmitRuntimeCall(
2175 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2176 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002177
2178 // Create a private scope that will globalize the arguments
2179 // passed from the outside of the target region.
2180 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2181
2182 // There's somehting to share.
2183 if (!CapturedVars.empty()) {
2184 // Prepare for parallel region. Indicate the outlined function.
2185 Address SharedArgs =
2186 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2187 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2188
2189 llvm::Value *DataSharingArgs[] = {
2190 SharedArgsPtr,
2191 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2192 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2193 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2194 DataSharingArgs);
2195
2196 // Store variable address in a list of references to pass to workers.
2197 unsigned Idx = 0;
2198 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002199 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2200 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2201 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002202 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002203 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2204 CGF.getPointerSize());
2205 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002206 if (V->getType()->isIntegerTy())
2207 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2208 else
2209 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002210 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2211 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002212 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002213 }
2214 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002215
2216 // Activate workers. This barrier is used by the master to signal
2217 // work for the workers.
2218 syncCTAThreads(CGF);
2219
2220 // OpenMP [2.5, Parallel Construct, p.49]
2221 // There is an implied barrier at the end of a parallel region. After the
2222 // end of a parallel region, only the master thread of the team resumes
2223 // execution of the enclosing task region.
2224 //
2225 // The master waits at this barrier until all workers are done.
2226 syncCTAThreads(CGF);
2227
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002228 if (!CapturedVars.empty())
2229 CGF.EmitRuntimeCall(
2230 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2231
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002232 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002233 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002234 };
2235
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002236 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2237 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002238 if (IsInParallelRegion) {
2239 SeqGen(CGF, Action);
2240 } else if (IsInTargetMasterThreadRegion) {
2241 L0ParallelGen(CGF, Action);
2242 } else {
2243 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002244 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002245 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002246 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002247 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002248 // }
2249 CGBuilderTy &Bld = CGF.Builder;
2250 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002251 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2252 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002253 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002254 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2255 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002256 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002257 // There is no need to emit line number for unconditional branch.
2258 (void)ApplyDebugLocation::CreateEmpty(CGF);
2259 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002260 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2261 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2262 llvm::Value *PL = CGF.EmitRuntimeCall(
2263 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2264 {RTLoc, ThreadID});
2265 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002266 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002267 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002268 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002269 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002270 // There is no need to emit line number for unconditional branch.
2271 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002272 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002273 L0ParallelGen(CGF, Action);
2274 CGF.EmitBranch(ExitBB);
2275 // There is no need to emit line number for unconditional branch.
2276 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002277 // Emit the continuation block for code after the if.
2278 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2279 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002280 };
2281
Alexey Bataev9ff80832018-04-16 20:16:21 +00002282 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002283 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002284 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002285 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002286 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002287 ThenRCG(CGF);
2288 }
2289}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002290
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002291void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002292 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2293 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2294 // Just call the outlined function to execute the parallel region.
2295 // OutlinedFn(&GTid, &zero, CapturedStruct);
2296 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002297 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002298
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002299 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2300 /*DestWidth=*/32, /*Signed=*/1),
2301 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002302 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002303 // ThreadId for serialized parallels is 0.
2304 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002305 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002306 &ThreadIDAddr](CodeGenFunction &CGF,
2307 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002308 Action.Enter(CGF);
2309
2310 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2311 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2312 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2313 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2314 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2315 };
2316 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2317 PrePostActionTy &) {
2318
2319 RegionCodeGenTy RCG(CodeGen);
2320 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2321 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2322 llvm::Value *Args[] = {RTLoc, ThreadID};
2323
2324 NVPTXActionTy Action(
2325 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2326 Args,
2327 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2328 Args);
2329 RCG.setAction(Action);
2330 RCG(CGF);
2331 };
2332
2333 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002334 // In the worker need to use the real thread id.
2335 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002336 RegionCodeGenTy RCG(CodeGen);
2337 RCG(CGF);
2338 } else {
2339 // If we are not in the target region, it is definitely L2 parallelism or
2340 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2341 // need to check for orphaned directives.
2342 RegionCodeGenTy RCG(SeqGen);
2343 RCG(CGF);
2344 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002345}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002346
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002347void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2348 CodeGenFunction &CGF, StringRef CriticalName,
2349 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2350 const Expr *Hint) {
2351 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2352 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2353 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2354 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2355 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2356
2357 // Fetch team-local id of the thread.
2358 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2359
2360 // Get the width of the team.
2361 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2362
2363 // Initialize the counter variable for the loop.
2364 QualType Int32Ty =
2365 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2366 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2367 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2368 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2369 /*isInit=*/true);
2370
2371 // Block checks if loop counter exceeds upper bound.
2372 CGF.EmitBlock(LoopBB);
2373 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2374 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2375 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2376
2377 // Block tests which single thread should execute region, and which threads
2378 // should go straight to synchronisation point.
2379 CGF.EmitBlock(TestBB);
2380 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2381 llvm::Value *CmpThreadToCounter =
2382 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2383 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2384
2385 // Block emits the body of the critical region.
2386 CGF.EmitBlock(BodyBB);
2387
2388 // Output the critical statement.
2389 CriticalOpGen(CGF);
2390
2391 // After the body surrounded by the critical region, the single executing
2392 // thread will jump to the synchronisation point.
2393 // Block waits for all threads in current team to finish then increments the
2394 // counter variable and returns to the loop.
2395 CGF.EmitBlock(SyncBB);
2396 getNVPTXCTABarrier(CGF);
2397
2398 llvm::Value *IncCounterVal =
2399 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2400 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2401 CGF.EmitBranch(LoopBB);
2402
2403 // Block that is reached when all threads in the team complete the region.
2404 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2405}
2406
Alexey Bataevb2575932018-01-04 20:18:55 +00002407/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002408static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2409 QualType ValTy, QualType CastTy,
2410 SourceLocation Loc) {
2411 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2412 "Cast type must sized.");
2413 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2414 "Val type must sized.");
2415 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2416 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002417 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002418 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2419 CGF.getContext().getTypeSizeInChars(CastTy))
2420 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2421 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2422 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2423 CastTy->hasSignedIntegerRepresentation());
2424 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002425 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2426 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002427 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2428 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002429}
2430
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002431/// This function creates calls to one of two shuffle functions to copy
2432/// variables between lanes in a warp.
2433static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002434 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002435 QualType ElemType,
2436 llvm::Value *Offset,
2437 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002438 CodeGenModule &CGM = CGF.CGM;
2439 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002440 CGOpenMPRuntimeNVPTX &RT =
2441 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2442
Alexey Bataeva453f362018-03-19 17:53:56 +00002443 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2444 assert(Size.getQuantity() <= 8 &&
2445 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002446
Alexey Bataeva453f362018-03-19 17:53:56 +00002447 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002448 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2449 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2450
2451 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002452 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2453 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2454 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002455 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002456 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002457
Alexey Bataev9ff80832018-04-16 20:16:21 +00002458 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2459 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002460
Alexey Bataeva453f362018-03-19 17:53:56 +00002461 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002462}
2463
Alexey Bataev12c62902018-06-22 19:10:38 +00002464static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2465 Address DestAddr, QualType ElemType,
2466 llvm::Value *Offset, SourceLocation Loc) {
2467 CGBuilderTy &Bld = CGF.Builder;
2468
2469 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2470 // Create the loop over the big sized data.
2471 // ptr = (void*)Elem;
2472 // ptrEnd = (void*) Elem + 1;
2473 // Step = 8;
2474 // while (ptr + Step < ptrEnd)
2475 // shuffle((int64_t)*ptr);
2476 // Step = 4;
2477 // while (ptr + Step < ptrEnd)
2478 // shuffle((int32_t)*ptr);
2479 // ...
2480 Address ElemPtr = DestAddr;
2481 Address Ptr = SrcAddr;
2482 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2483 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2484 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2485 if (Size < CharUnits::fromQuantity(IntSize))
2486 continue;
2487 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2488 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2489 /*Signed=*/1);
2490 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2491 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2492 ElemPtr =
2493 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2494 if (Size.getQuantity() / IntSize > 1) {
2495 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2496 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2497 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2498 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2499 CGF.EmitBlock(PreCondBB);
2500 llvm::PHINode *PhiSrc =
2501 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2502 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2503 llvm::PHINode *PhiDest =
2504 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2505 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2506 Ptr = Address(PhiSrc, Ptr.getAlignment());
2507 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2508 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2509 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2510 Ptr.getPointer(), CGF.VoidPtrTy));
2511 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2512 ThenBB, ExitBB);
2513 CGF.EmitBlock(ThenBB);
2514 llvm::Value *Res = createRuntimeShuffleFunction(
2515 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2516 IntType, Offset, Loc);
2517 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2518 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2519 ElemPtr =
2520 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2521 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2522 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2523 CGF.EmitBranch(PreCondBB);
2524 CGF.EmitBlock(ExitBB);
2525 } else {
2526 llvm::Value *Res = createRuntimeShuffleFunction(
2527 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2528 IntType, Offset, Loc);
2529 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2530 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2531 ElemPtr =
2532 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2533 }
2534 Size = Size % IntSize;
2535 }
2536}
2537
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002538namespace {
2539enum CopyAction : unsigned {
2540 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2541 // the warp using shuffle instructions.
2542 RemoteLaneToThread,
2543 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2544 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002545 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2546 ThreadToScratchpad,
2547 // ScratchpadToThread: Copy from a scratchpad array in global memory
2548 // containing team-reduced data to a thread's stack.
2549 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002550};
2551} // namespace
2552
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002553struct CopyOptionsTy {
2554 llvm::Value *RemoteLaneOffset;
2555 llvm::Value *ScratchpadIndex;
2556 llvm::Value *ScratchpadWidth;
2557};
2558
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002559/// Emit instructions to copy a Reduce list, which contains partially
2560/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002561static void emitReductionListCopy(
2562 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2563 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2564 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002565
Alexey Bataev9ff80832018-04-16 20:16:21 +00002566 CodeGenModule &CGM = CGF.CGM;
2567 ASTContext &C = CGM.getContext();
2568 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002569
Alexey Bataev9ff80832018-04-16 20:16:21 +00002570 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2571 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2572 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002573
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002574 // Iterates, element-by-element, through the source Reduce list and
2575 // make a copy.
2576 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002577 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002578 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002579 Address SrcElementAddr = Address::invalid();
2580 Address DestElementAddr = Address::invalid();
2581 Address DestElementPtrAddr = Address::invalid();
2582 // Should we shuffle in an element from a remote lane?
2583 bool ShuffleInElement = false;
2584 // Set to true to update the pointer in the dest Reduce list to a
2585 // newly created element.
2586 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002587 // Increment the src or dest pointer to the scratchpad, for each
2588 // new element.
2589 bool IncrScratchpadSrc = false;
2590 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002591
2592 switch (Action) {
2593 case RemoteLaneToThread: {
2594 // Step 1.1: Get the address for the src element in the Reduce list.
2595 Address SrcElementPtrAddr =
2596 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002597 SrcElementAddr = CGF.EmitLoadOfPointer(
2598 SrcElementPtrAddr,
2599 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002600
2601 // Step 1.2: Create a temporary to store the element in the destination
2602 // Reduce list.
2603 DestElementPtrAddr =
2604 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2605 DestElementAddr =
2606 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2607 ShuffleInElement = true;
2608 UpdateDestListPtr = true;
2609 break;
2610 }
2611 case ThreadCopy: {
2612 // Step 1.1: Get the address for the src element in the Reduce list.
2613 Address SrcElementPtrAddr =
2614 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002615 SrcElementAddr = CGF.EmitLoadOfPointer(
2616 SrcElementPtrAddr,
2617 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002618
2619 // Step 1.2: Get the address for dest element. The destination
2620 // element has already been created on the thread's stack.
2621 DestElementPtrAddr =
2622 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002623 DestElementAddr = CGF.EmitLoadOfPointer(
2624 DestElementPtrAddr,
2625 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002626 break;
2627 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002628 case ThreadToScratchpad: {
2629 // Step 1.1: Get the address for the src element in the Reduce list.
2630 Address SrcElementPtrAddr =
2631 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002632 SrcElementAddr = CGF.EmitLoadOfPointer(
2633 SrcElementPtrAddr,
2634 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002635
2636 // Step 1.2: Get the address for dest element:
2637 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002638 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002639 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002640 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002641 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002642 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002643 ScratchPadElemAbsolutePtrVal =
2644 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002645 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2646 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002647 IncrScratchpadDest = true;
2648 break;
2649 }
2650 case ScratchpadToThread: {
2651 // Step 1.1: Get the address for the src element in the scratchpad.
2652 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002653 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002654 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002655 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002656 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002657 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002658 ScratchPadElemAbsolutePtrVal =
2659 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2660 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2661 C.getTypeAlignInChars(Private->getType()));
2662 IncrScratchpadSrc = true;
2663
2664 // Step 1.2: Create a temporary to store the element in the destination
2665 // Reduce list.
2666 DestElementPtrAddr =
2667 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2668 DestElementAddr =
2669 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2670 UpdateDestListPtr = true;
2671 break;
2672 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002673 }
2674
2675 // Regardless of src and dest of copy, we emit the load of src
2676 // element as this is required in all directions
2677 SrcElementAddr = Bld.CreateElementBitCast(
2678 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002679 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2680 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002681
2682 // Now that all active lanes have read the element in the
2683 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002684 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002685 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2686 RemoteLaneOffset, Private->getExprLoc());
2687 } else {
2688 if (Private->getType()->isScalarType()) {
2689 llvm::Value *Elem =
2690 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2691 Private->getType(), Private->getExprLoc());
2692 // Store the source element value to the dest element address.
2693 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2694 Private->getType());
2695 } else {
2696 CGF.EmitAggregateCopy(
2697 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2698 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2699 Private->getType(), AggValueSlot::DoesNotOverlap);
2700 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002701 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002702
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002703 // Step 3.1: Modify reference in dest Reduce list as needed.
2704 // Modifying the reference in Reduce list to point to the newly
2705 // created element. The element is live in the current function
2706 // scope and that of functions it invokes (i.e., reduce_function).
2707 // RemoteReduceData[i] = (void*)&RemoteElem
2708 if (UpdateDestListPtr) {
2709 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2710 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2711 DestElementPtrAddr, /*Volatile=*/false,
2712 C.VoidPtrTy);
2713 }
2714
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002715 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2716 // address of the next element in scratchpad memory, unless we're currently
2717 // processing the last one. Memory alignment is also taken care of here.
2718 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2719 llvm::Value *ScratchpadBasePtr =
2720 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002721 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2722 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002723 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002724 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002725
2726 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002727 ScratchpadBasePtr = Bld.CreateNUWSub(
2728 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2729 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002730 ScratchpadBasePtr,
2731 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002732 ScratchpadBasePtr = Bld.CreateNUWAdd(
2733 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2734 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002735 ScratchpadBasePtr,
2736 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2737
2738 if (IncrScratchpadDest)
2739 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2740 else /* IncrScratchpadSrc = true */
2741 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2742 }
2743
Alexey Bataev9ff80832018-04-16 20:16:21 +00002744 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002745 }
2746}
2747
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002748/// This function emits a helper that loads data from the scratchpad array
2749/// and (optionally) reduces it with the input operand.
2750///
2751/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2752/// reduce_data remote;
2753/// for elem in remote:
2754/// remote.elem = Scratchpad[elem_id][index]
2755/// if (should_reduce)
2756/// local = local @ remote
2757/// else
2758/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002759static llvm::Value *emitReduceScratchpadFunction(
2760 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2761 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002762 ASTContext &C = CGM.getContext();
2763 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002764
2765 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002766 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2767 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002768 // Base address of the scratchpad array, with each element storing a
2769 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002770 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2771 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002772 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002773 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2774 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002775 // Row width of an element in the scratchpad array, typically
2776 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002777 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2778 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002779 // If should_reduce == 1, then it's load AND reduce,
2780 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2781 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002782 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2783 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002784
2785 FunctionArgList Args;
2786 Args.push_back(&ReduceListArg);
2787 Args.push_back(&ScratchPadArg);
2788 Args.push_back(&IndexArg);
2789 Args.push_back(&WidthArg);
2790 Args.push_back(&ShouldReduceArg);
2791
Alexey Bataev9ff80832018-04-16 20:16:21 +00002792 const CGFunctionInfo &CGFI =
2793 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002794 auto *Fn = llvm::Function::Create(
2795 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2796 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002797 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002798 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002799 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002800 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002801
Alexey Bataev9ff80832018-04-16 20:16:21 +00002802 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002803
2804 // Get local Reduce list pointer.
2805 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2806 Address ReduceListAddr(
2807 Bld.CreatePointerBitCastOrAddrSpaceCast(
2808 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002809 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002810 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2811 CGF.getPointerAlign());
2812
2813 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2814 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002815 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002816
2817 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002818 llvm::Value *IndexVal = Bld.CreateIntCast(
2819 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2820 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002821
2822 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002823 llvm::Value *WidthVal = Bld.CreateIntCast(
2824 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2825 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002826
2827 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2828 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002829 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002830
2831 // The absolute ptr address to the base addr of the next element to copy.
2832 llvm::Value *CumulativeElemBasePtr =
2833 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2834 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2835
2836 // Create a Remote Reduce list to store the elements read from the
2837 // scratchpad array.
2838 Address RemoteReduceList =
2839 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2840
2841 // Assemble remote Reduce list from scratchpad array.
2842 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2843 SrcDataAddr, RemoteReduceList,
2844 {/*RemoteLaneOffset=*/nullptr,
2845 /*ScratchpadIndex=*/IndexVal,
2846 /*ScratchpadWidth=*/WidthVal});
2847
2848 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2849 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2850 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2851
Alexey Bataev9ff80832018-04-16 20:16:21 +00002852 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002853 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2854
2855 CGF.EmitBlock(ThenBB);
2856 // We should reduce with the local Reduce list.
2857 // reduce_function(LocalReduceList, RemoteReduceList)
2858 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2859 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2860 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2861 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002862 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2863 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002864 Bld.CreateBr(MergeBB);
2865
2866 CGF.EmitBlock(ElseBB);
2867 // No reduction; just copy:
2868 // Local Reduce list = Remote Reduce list.
2869 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2870 RemoteReduceList, ReduceListAddr);
2871 Bld.CreateBr(MergeBB);
2872
2873 CGF.EmitBlock(MergeBB);
2874
2875 CGF.FinishFunction();
2876 return Fn;
2877}
2878
2879/// This function emits a helper that stores reduced data from the team
2880/// master to a scratchpad array in global memory.
2881///
2882/// for elem in Reduce List:
2883/// scratchpad[elem_id][index] = elem
2884///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002885static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2886 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002887 QualType ReductionArrayTy,
2888 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002889
Alexey Bataev9ff80832018-04-16 20:16:21 +00002890 ASTContext &C = CGM.getContext();
2891 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002892
2893 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002894 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2895 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002896 // Base address of the scratchpad array, with each element storing a
2897 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002898 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2899 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002900 // A destination index into the scratchpad array, typically the team
2901 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002902 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2903 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002904 // Row width of an element in the scratchpad array, typically
2905 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002906 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2907 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002908
2909 FunctionArgList Args;
2910 Args.push_back(&ReduceListArg);
2911 Args.push_back(&ScratchPadArg);
2912 Args.push_back(&IndexArg);
2913 Args.push_back(&WidthArg);
2914
Alexey Bataev9ff80832018-04-16 20:16:21 +00002915 const CGFunctionInfo &CGFI =
2916 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002917 auto *Fn = llvm::Function::Create(
2918 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2919 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002920 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002921 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002922 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002923 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002924
Alexey Bataev9ff80832018-04-16 20:16:21 +00002925 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002926
2927 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2928 Address SrcDataAddr(
2929 Bld.CreatePointerBitCastOrAddrSpaceCast(
2930 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002931 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002932 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2933 CGF.getPointerAlign());
2934
2935 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2936 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002937 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002938
2939 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002940 llvm::Value *IndexVal = Bld.CreateIntCast(
2941 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2942 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002943
2944 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
2945 llvm::Value *WidthVal =
2946 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
2947 Int32Ty, SourceLocation()),
2948 CGF.SizeTy, /*isSigned=*/true);
2949
2950 // The absolute ptr address to the base addr of the next element to copy.
2951 llvm::Value *CumulativeElemBasePtr =
2952 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2953 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2954
2955 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
2956 SrcDataAddr, DestDataAddr,
2957 {/*RemoteLaneOffset=*/nullptr,
2958 /*ScratchpadIndex=*/IndexVal,
2959 /*ScratchpadWidth=*/WidthVal});
2960
2961 CGF.FinishFunction();
2962 return Fn;
2963}
2964
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002965/// This function emits a helper that gathers Reduce lists from the first
2966/// lane of every active warp to lanes in the first warp.
2967///
2968/// void inter_warp_copy_func(void* reduce_data, num_warps)
2969/// shared smem[warp_size];
2970/// For all data entries D in reduce_data:
2971/// If (I am the first lane in each warp)
2972/// Copy my local D to smem[warp_id]
2973/// sync
2974/// if (I am the first warp)
2975/// Copy smem[thread_id] to my local D
2976/// sync
2977static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2978 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002979 QualType ReductionArrayTy,
2980 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002981 ASTContext &C = CGM.getContext();
2982 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002983
2984 // ReduceList: thread local Reduce list.
2985 // At the stage of the computation when this function is called, partially
2986 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002987 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2988 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002989 // NumWarps: number of warps active in the parallel region. This could
2990 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002991 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00002992 C.getIntTypeForBitwidth(32, /* Signed */ true),
2993 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002994 FunctionArgList Args;
2995 Args.push_back(&ReduceListArg);
2996 Args.push_back(&NumWarpsArg);
2997
Alexey Bataev9ff80832018-04-16 20:16:21 +00002998 const CGFunctionInfo &CGFI =
2999 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003000 auto *Fn = llvm::Function::Create(
3001 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3002 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003003 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003004 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003005 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003006 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003007
Alexey Bataev9ff80832018-04-16 20:16:21 +00003008 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003009
3010 // This array is used as a medium to transfer, one reduce element at a time,
3011 // the data from the first lane of every warp to lanes in the first warp
3012 // in order to perform the final step of a reduction in a parallel region
3013 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3014 // for reduced latency, as well as to have a distinct copy for concurrently
3015 // executing target regions. The array is declared with common linkage so
3016 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003017 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003018 "__openmp_nvptx_data_transfer_temporary_storage";
3019 llvm::GlobalVariable *TransferMedium =
3020 M.getGlobalVariable(TransferMediumName);
3021 if (!TransferMedium) {
3022 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
3023 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3024 TransferMedium = new llvm::GlobalVariable(
3025 M, Ty,
3026 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3027 llvm::Constant::getNullValue(Ty), TransferMediumName,
3028 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3029 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003030 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003031 }
3032
3033 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003034 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003035 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003036 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003037 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003038 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003039
3040 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3041 Address LocalReduceList(
3042 Bld.CreatePointerBitCastOrAddrSpaceCast(
3043 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3044 C.VoidPtrTy, SourceLocation()),
3045 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3046 CGF.getPointerAlign());
3047
3048 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003049 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003050 //
3051 // Warp master copies reduce element to transfer medium in __shared__
3052 // memory.
3053 //
3054 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3055 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3056 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3057
3058 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003059 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003060 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3061 CGF.EmitBlock(ThenBB);
3062
3063 // Reduce element = LocalReduceList[i]
3064 Address ElemPtrPtrAddr =
3065 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3066 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3067 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3068 // elemptr = (type[i]*)(elemptrptr)
3069 Address ElemPtr =
3070 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3071 ElemPtr = Bld.CreateElementBitCast(
3072 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003073
3074 // Get pointer to location in transfer medium.
3075 // MediumPtr = &medium[warp_id]
3076 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3077 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3078 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3079 // Casting to actual data type.
3080 // MediumPtr = (type[i]*)MediumPtrAddr;
3081 MediumPtr = Bld.CreateElementBitCast(
3082 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3083
Alexey Bataev12c62902018-06-22 19:10:38 +00003084 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003085 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003086 if (Private->getType()->isScalarType()) {
3087 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3088 Private->getType(), Loc);
3089 // Store the source element value to the dest element address.
3090 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3091 Private->getType());
3092 } else {
3093 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3094 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3095 Private->getType(), AggValueSlot::DoesNotOverlap);
3096 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003097
3098 Bld.CreateBr(MergeBB);
3099
3100 CGF.EmitBlock(ElseBB);
3101 Bld.CreateBr(MergeBB);
3102
3103 CGF.EmitBlock(MergeBB);
3104
3105 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3106 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3107 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3108
Alexey Bataev9ff80832018-04-16 20:16:21 +00003109 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003110 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3111 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3112 syncParallelThreads(CGF, NumActiveThreads);
3113
3114 //
3115 // Warp 0 copies reduce element from transfer medium.
3116 //
3117 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3118 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3119 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3120
3121 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003122 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003123 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3124 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3125
3126 CGF.EmitBlock(W0ThenBB);
3127
3128 // SrcMediumPtr = &medium[tid]
3129 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3130 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3131 Address SrcMediumPtr(SrcMediumPtrVal,
3132 C.getTypeAlignInChars(Private->getType()));
3133 // SrcMediumVal = *SrcMediumPtr;
3134 SrcMediumPtr = Bld.CreateElementBitCast(
3135 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003136
3137 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3138 Address TargetElemPtrPtr =
3139 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3140 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3141 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3142 Address TargetElemPtr =
3143 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3144 TargetElemPtr = Bld.CreateElementBitCast(
3145 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3146
3147 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003148 if (Private->getType()->isScalarType()) {
3149 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3150 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3151 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3152 Private->getType());
3153 } else {
3154 CGF.EmitAggregateCopy(
3155 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3156 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3157 Private->getType(), AggValueSlot::DoesNotOverlap);
3158 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003159 Bld.CreateBr(W0MergeBB);
3160
3161 CGF.EmitBlock(W0ElseBB);
3162 Bld.CreateBr(W0MergeBB);
3163
3164 CGF.EmitBlock(W0MergeBB);
3165
3166 // While warp 0 copies values from transfer medium, all other warps must
3167 // wait.
3168 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003169 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170 }
3171
3172 CGF.FinishFunction();
3173 return Fn;
3174}
3175
3176/// Emit a helper that reduces data across two OpenMP threads (lanes)
3177/// in the same warp. It uses shuffle instructions to copy over data from
3178/// a remote lane's stack. The reduction algorithm performed is specified
3179/// by the fourth parameter.
3180///
3181/// Algorithm Versions.
3182/// Full Warp Reduce (argument value 0):
3183/// This algorithm assumes that all 32 lanes are active and gathers
3184/// data from these 32 lanes, producing a single resultant value.
3185/// Contiguous Partial Warp Reduce (argument value 1):
3186/// This algorithm assumes that only a *contiguous* subset of lanes
3187/// are active. This happens for the last warp in a parallel region
3188/// when the user specified num_threads is not an integer multiple of
3189/// 32. This contiguous subset always starts with the zeroth lane.
3190/// Partial Warp Reduce (argument value 2):
3191/// This algorithm gathers data from any number of lanes at any position.
3192/// All reduced values are stored in the lowest possible lane. The set
3193/// of problems every algorithm addresses is a super set of those
3194/// addressable by algorithms with a lower version number. Overhead
3195/// increases as algorithm version increases.
3196///
3197/// Terminology
3198/// Reduce element:
3199/// Reduce element refers to the individual data field with primitive
3200/// data types to be combined and reduced across threads.
3201/// Reduce list:
3202/// Reduce list refers to a collection of local, thread-private
3203/// reduce elements.
3204/// Remote Reduce list:
3205/// Remote Reduce list refers to a collection of remote (relative to
3206/// the current thread) reduce elements.
3207///
3208/// We distinguish between three states of threads that are important to
3209/// the implementation of this function.
3210/// Alive threads:
3211/// Threads in a warp executing the SIMT instruction, as distinguished from
3212/// threads that are inactive due to divergent control flow.
3213/// Active threads:
3214/// The minimal set of threads that has to be alive upon entry to this
3215/// function. The computation is correct iff active threads are alive.
3216/// Some threads are alive but they are not active because they do not
3217/// contribute to the computation in any useful manner. Turning them off
3218/// may introduce control flow overheads without any tangible benefits.
3219/// Effective threads:
3220/// In order to comply with the argument requirements of the shuffle
3221/// function, we must keep all lanes holding data alive. But at most
3222/// half of them perform value aggregation; we refer to this half of
3223/// threads as effective. The other half is simply handing off their
3224/// data.
3225///
3226/// Procedure
3227/// Value shuffle:
3228/// In this step active threads transfer data from higher lane positions
3229/// in the warp to lower lane positions, creating Remote Reduce list.
3230/// Value aggregation:
3231/// In this step, effective threads combine their thread local Reduce list
3232/// with Remote Reduce list and store the result in the thread local
3233/// Reduce list.
3234/// Value copy:
3235/// In this step, we deal with the assumption made by algorithm 2
3236/// (i.e. contiguity assumption). When we have an odd number of lanes
3237/// active, say 2k+1, only k threads will be effective and therefore k
3238/// new values will be produced. However, the Reduce list owned by the
3239/// (2k+1)th thread is ignored in the value aggregation. Therefore
3240/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3241/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003242static llvm::Value *emitShuffleAndReduceFunction(
3243 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3244 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003245 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003246
3247 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003248 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3249 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003251 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3252 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003253 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003254 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3255 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003256 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003257 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3258 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003259 FunctionArgList Args;
3260 Args.push_back(&ReduceListArg);
3261 Args.push_back(&LaneIDArg);
3262 Args.push_back(&RemoteLaneOffsetArg);
3263 Args.push_back(&AlgoVerArg);
3264
Alexey Bataev9ff80832018-04-16 20:16:21 +00003265 const CGFunctionInfo &CGFI =
3266 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267 auto *Fn = llvm::Function::Create(
3268 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3269 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003270 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003271 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003273 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataev9ff80832018-04-16 20:16:21 +00003275 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003276
3277 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3278 Address LocalReduceList(
3279 Bld.CreatePointerBitCastOrAddrSpaceCast(
3280 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3281 C.VoidPtrTy, SourceLocation()),
3282 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3283 CGF.getPointerAlign());
3284
3285 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3286 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3287 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3288
3289 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3290 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3291 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3292
3293 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3294 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3295 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3296
3297 // Create a local thread-private variable to host the Reduce list
3298 // from a remote lane.
3299 Address RemoteReduceList =
3300 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3301
3302 // This loop iterates through the list of reduce elements and copies,
3303 // element by element, from a remote lane in the warp to RemoteReduceList,
3304 // hosted on the thread's stack.
3305 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3306 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003307 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3308 /*ScratchpadIndex=*/nullptr,
3309 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310
3311 // The actions to be performed on the Remote Reduce list is dependent
3312 // on the algorithm version.
3313 //
3314 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3315 // LaneId % 2 == 0 && Offset > 0):
3316 // do the reduction value aggregation
3317 //
3318 // The thread local variable Reduce list is mutated in place to host the
3319 // reduced data, which is the aggregated value produced from local and
3320 // remote lanes.
3321 //
3322 // Note that AlgoVer is expected to be a constant integer known at compile
3323 // time.
3324 // When AlgoVer==0, the first conjunction evaluates to true, making
3325 // the entire predicate true during compile time.
3326 // When AlgoVer==1, the second conjunction has only the second part to be
3327 // evaluated during runtime. Other conjunctions evaluates to false
3328 // during compile time.
3329 // When AlgoVer==2, the third conjunction has only the second part to be
3330 // evaluated during runtime. Other conjunctions evaluates to false
3331 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003332 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003333
Alexey Bataev9ff80832018-04-16 20:16:21 +00003334 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3335 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003336 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3337
Alexey Bataev9ff80832018-04-16 20:16:21 +00003338 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3339 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3340 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003341 CondAlgo2 = Bld.CreateAnd(
3342 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3343
Alexey Bataev9ff80832018-04-16 20:16:21 +00003344 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003345 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3346
3347 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3348 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3349 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3350 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3351
3352 CGF.EmitBlock(ThenBB);
3353 // reduce_function(LocalReduceList, RemoteReduceList)
3354 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3355 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3356 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3357 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003358 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3359 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003360 Bld.CreateBr(MergeBB);
3361
3362 CGF.EmitBlock(ElseBB);
3363 Bld.CreateBr(MergeBB);
3364
3365 CGF.EmitBlock(MergeBB);
3366
3367 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3368 // Reduce list.
3369 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003370 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003371 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3372
3373 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3374 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3375 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3376 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3377
3378 CGF.EmitBlock(CpyThenBB);
3379 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3380 RemoteReduceList, LocalReduceList);
3381 Bld.CreateBr(CpyMergeBB);
3382
3383 CGF.EmitBlock(CpyElseBB);
3384 Bld.CreateBr(CpyMergeBB);
3385
3386 CGF.EmitBlock(CpyMergeBB);
3387
3388 CGF.FinishFunction();
3389 return Fn;
3390}
3391
3392///
3393/// Design of OpenMP reductions on the GPU
3394///
3395/// Consider a typical OpenMP program with one or more reduction
3396/// clauses:
3397///
3398/// float foo;
3399/// double bar;
3400/// #pragma omp target teams distribute parallel for \
3401/// reduction(+:foo) reduction(*:bar)
3402/// for (int i = 0; i < N; i++) {
3403/// foo += A[i]; bar *= B[i];
3404/// }
3405///
3406/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3407/// all teams. In our OpenMP implementation on the NVPTX device an
3408/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3409/// within a team are mapped to CUDA threads within a threadblock.
3410/// Our goal is to efficiently aggregate values across all OpenMP
3411/// threads such that:
3412///
3413/// - the compiler and runtime are logically concise, and
3414/// - the reduction is performed efficiently in a hierarchical
3415/// manner as follows: within OpenMP threads in the same warp,
3416/// across warps in a threadblock, and finally across teams on
3417/// the NVPTX device.
3418///
3419/// Introduction to Decoupling
3420///
3421/// We would like to decouple the compiler and the runtime so that the
3422/// latter is ignorant of the reduction variables (number, data types)
3423/// and the reduction operators. This allows a simpler interface
3424/// and implementation while still attaining good performance.
3425///
3426/// Pseudocode for the aforementioned OpenMP program generated by the
3427/// compiler is as follows:
3428///
3429/// 1. Create private copies of reduction variables on each OpenMP
3430/// thread: 'foo_private', 'bar_private'
3431/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3432/// to it and writes the result in 'foo_private' and 'bar_private'
3433/// respectively.
3434/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3435/// and store the result on the team master:
3436///
3437/// __kmpc_nvptx_parallel_reduce_nowait(...,
3438/// reduceData, shuffleReduceFn, interWarpCpyFn)
3439///
3440/// where:
3441/// struct ReduceData {
3442/// double *foo;
3443/// double *bar;
3444/// } reduceData
3445/// reduceData.foo = &foo_private
3446/// reduceData.bar = &bar_private
3447///
3448/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3449/// auxiliary functions generated by the compiler that operate on
3450/// variables of type 'ReduceData'. They aid the runtime perform
3451/// algorithmic steps in a data agnostic manner.
3452///
3453/// 'shuffleReduceFn' is a pointer to a function that reduces data
3454/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3455/// same warp. It takes the following arguments as input:
3456///
3457/// a. variable of type 'ReduceData' on the calling lane,
3458/// b. its lane_id,
3459/// c. an offset relative to the current lane_id to generate a
3460/// remote_lane_id. The remote lane contains the second
3461/// variable of type 'ReduceData' that is to be reduced.
3462/// d. an algorithm version parameter determining which reduction
3463/// algorithm to use.
3464///
3465/// 'shuffleReduceFn' retrieves data from the remote lane using
3466/// efficient GPU shuffle intrinsics and reduces, using the
3467/// algorithm specified by the 4th parameter, the two operands
3468/// element-wise. The result is written to the first operand.
3469///
3470/// Different reduction algorithms are implemented in different
3471/// runtime functions, all calling 'shuffleReduceFn' to perform
3472/// the essential reduction step. Therefore, based on the 4th
3473/// parameter, this function behaves slightly differently to
3474/// cooperate with the runtime to ensure correctness under
3475/// different circumstances.
3476///
3477/// 'InterWarpCpyFn' is a pointer to a function that transfers
3478/// reduced variables across warps. It tunnels, through CUDA
3479/// shared memory, the thread-private data of type 'ReduceData'
3480/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003481/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3482/// The last team writes the global reduced value to memory.
3483///
3484/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3485/// reduceData, shuffleReduceFn, interWarpCpyFn,
3486/// scratchpadCopyFn, loadAndReduceFn)
3487///
3488/// 'scratchpadCopyFn' is a helper that stores reduced
3489/// data from the team master to a scratchpad array in
3490/// global memory.
3491///
3492/// 'loadAndReduceFn' is a helper that loads data from
3493/// the scratchpad array and reduces it with the input
3494/// operand.
3495///
3496/// These compiler generated functions hide address
3497/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003498/// 5. if ret == 1:
3499/// The team master of the last team stores the reduced
3500/// result to the globals in memory.
3501/// foo += reduceData.foo; bar *= reduceData.bar
3502///
3503///
3504/// Warp Reduction Algorithms
3505///
3506/// On the warp level, we have three algorithms implemented in the
3507/// OpenMP runtime depending on the number of active lanes:
3508///
3509/// Full Warp Reduction
3510///
3511/// The reduce algorithm within a warp where all lanes are active
3512/// is implemented in the runtime as follows:
3513///
3514/// full_warp_reduce(void *reduce_data,
3515/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3516/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3517/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3518/// }
3519///
3520/// The algorithm completes in log(2, WARPSIZE) steps.
3521///
3522/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3523/// not used therefore we save instructions by not retrieving lane_id
3524/// from the corresponding special registers. The 4th parameter, which
3525/// represents the version of the algorithm being used, is set to 0 to
3526/// signify full warp reduction.
3527///
3528/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3529///
3530/// #reduce_elem refers to an element in the local lane's data structure
3531/// #remote_elem is retrieved from a remote lane
3532/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3533/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3534///
3535/// Contiguous Partial Warp Reduction
3536///
3537/// This reduce algorithm is used within a warp where only the first
3538/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3539/// number of OpenMP threads in a parallel region is not a multiple of
3540/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3541///
3542/// void
3543/// contiguous_partial_reduce(void *reduce_data,
3544/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3545/// int size, int lane_id) {
3546/// int curr_size;
3547/// int offset;
3548/// curr_size = size;
3549/// mask = curr_size/2;
3550/// while (offset>0) {
3551/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3552/// curr_size = (curr_size+1)/2;
3553/// offset = curr_size/2;
3554/// }
3555/// }
3556///
3557/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3558///
3559/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3560/// if (lane_id < offset)
3561/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3562/// else
3563/// reduce_elem = remote_elem
3564///
3565/// This algorithm assumes that the data to be reduced are located in a
3566/// contiguous subset of lanes starting from the first. When there is
3567/// an odd number of active lanes, the data in the last lane is not
3568/// aggregated with any other lane's dat but is instead copied over.
3569///
3570/// Dispersed Partial Warp Reduction
3571///
3572/// This algorithm is used within a warp when any discontiguous subset of
3573/// lanes are active. It is used to implement the reduction operation
3574/// across lanes in an OpenMP simd region or in a nested parallel region.
3575///
3576/// void
3577/// dispersed_partial_reduce(void *reduce_data,
3578/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3579/// int size, remote_id;
3580/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3581/// do {
3582/// remote_id = next_active_lane_id_right_after_me();
3583/// # the above function returns 0 of no active lane
3584/// # is present right after the current lane.
3585/// size = number_of_active_lanes_in_this_warp();
3586/// logical_lane_id /= 2;
3587/// ShuffleReduceFn(reduce_data, logical_lane_id,
3588/// remote_id-1-threadIdx.x, 2);
3589/// } while (logical_lane_id % 2 == 0 && size > 1);
3590/// }
3591///
3592/// There is no assumption made about the initial state of the reduction.
3593/// Any number of lanes (>=1) could be active at any position. The reduction
3594/// result is returned in the first active lane.
3595///
3596/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3597///
3598/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3599/// if (lane_id % 2 == 0 && offset > 0)
3600/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3601/// else
3602/// reduce_elem = remote_elem
3603///
3604///
3605/// Intra-Team Reduction
3606///
3607/// This function, as implemented in the runtime call
3608/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3609/// threads in a team. It first reduces within a warp using the
3610/// aforementioned algorithms. We then proceed to gather all such
3611/// reduced values at the first warp.
3612///
3613/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3614/// data from each of the "warp master" (zeroth lane of each warp, where
3615/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3616/// a mathematical sense) the problem of reduction across warp masters in
3617/// a block to the problem of warp reduction.
3618///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003619///
3620/// Inter-Team Reduction
3621///
3622/// Once a team has reduced its data to a single value, it is stored in
3623/// a global scratchpad array. Since each team has a distinct slot, this
3624/// can be done without locking.
3625///
3626/// The last team to write to the scratchpad array proceeds to reduce the
3627/// scratchpad array. One or more workers in the last team use the helper
3628/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3629/// the k'th worker reduces every k'th element.
3630///
3631/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3632/// reduce across workers and compute a globally reduced value.
3633///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003634void CGOpenMPRuntimeNVPTX::emitReduction(
3635 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3636 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3637 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3638 if (!CGF.HaveInsertPoint())
3639 return;
3640
3641 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003642 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003643 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3644 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003645 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003646
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003647 if (Options.SimpleReduction) {
3648 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3649 ReductionOps, Options);
3650 return;
3651 }
3652
Alexey Bataev9ff80832018-04-16 20:16:21 +00003653 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003654
3655 // 1. Build a list of reduction variables.
3656 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3657 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003658 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003659 if (E->getType()->isVariablyModifiedType())
3660 // Reserve place for array size.
3661 ++Size;
3662 }
3663 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3664 QualType ReductionArrayTy =
3665 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3666 /*IndexTypeQuals=*/0);
3667 Address ReductionList =
3668 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3669 auto IPriv = Privates.begin();
3670 unsigned Idx = 0;
3671 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3672 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3673 CGF.getPointerSize());
3674 CGF.Builder.CreateStore(
3675 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3676 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3677 Elem);
3678 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3679 // Store array size.
3680 ++Idx;
3681 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3682 CGF.getPointerSize());
3683 llvm::Value *Size = CGF.Builder.CreateIntCast(
3684 CGF.getVLASize(
3685 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003686 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003687 CGF.SizeTy, /*isSigned=*/false);
3688 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3689 Elem);
3690 }
3691 }
3692
3693 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003694 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003695 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3696 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003697
3698 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3699 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003700 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3701 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3702 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003703 ReductionList.getPointer(), CGF.VoidPtrTy);
3704
Alexey Bataev9ff80832018-04-16 20:16:21 +00003705 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003706 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003707 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003708 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003709
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003710 llvm::Value *Args[] = {ThreadId,
3711 CGF.Builder.getInt32(RHSExprs.size()),
3712 ReductionArrayTySize,
3713 RL,
3714 ShuffleAndReduceFn,
3715 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003716
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003717 llvm::Value *Res = nullptr;
3718 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003719 Res = CGF.EmitRuntimeCall(
3720 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3721 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003722 else if (SimdReduction)
3723 Res = CGF.EmitRuntimeCall(
3724 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3725 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003726
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003727 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003728 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003729 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003730 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003731 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003732
3733 llvm::Value *Args[] = {ThreadId,
3734 CGF.Builder.getInt32(RHSExprs.size()),
3735 ReductionArrayTySize,
3736 RL,
3737 ShuffleAndReduceFn,
3738 InterWarpCopyFn,
3739 ScratchPadCopyFn,
3740 LoadAndReduceFn};
3741 Res = CGF.EmitRuntimeCall(
3742 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3743 Args);
3744 }
3745
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003746 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003747 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3748 llvm::SwitchInst *SwInst =
3749 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003750
3751 // 6. Build case 1: where we have reduced values in the master
3752 // thread in each team.
3753 // __kmpc_end_reduce{_nowait}(<gtid>);
3754 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003755 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003756 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3757 CGF.EmitBlock(Case1BB);
3758
3759 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3760 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003761 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003762 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3763 auto IPriv = Privates.begin();
3764 auto ILHS = LHSExprs.begin();
3765 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003766 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003767 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3768 cast<DeclRefExpr>(*IRHS));
3769 ++IPriv;
3770 ++ILHS;
3771 ++IRHS;
3772 }
3773 };
3774 RegionCodeGenTy RCG(CodeGen);
3775 NVPTXActionTy Action(
3776 nullptr, llvm::None,
3777 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3778 EndArgs);
3779 RCG.setAction(Action);
3780 RCG(CGF);
3781 CGF.EmitBranch(DefaultBB);
3782 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3783}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003784
3785const VarDecl *
3786CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3787 const VarDecl *NativeParam) const {
3788 if (!NativeParam->getType()->isReferenceType())
3789 return NativeParam;
3790 QualType ArgType = NativeParam->getType();
3791 QualifierCollector QC;
3792 const Type *NonQualTy = QC.strip(ArgType);
3793 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3794 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3795 if (Attr->getCaptureKind() == OMPC_map) {
3796 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3797 LangAS::opencl_global);
3798 }
3799 }
3800 ArgType = CGM.getContext().getPointerType(PointeeTy);
3801 QC.addRestrict();
3802 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003803 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003804 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003805 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003806 return ImplicitParamDecl::Create(
3807 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3808 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003809 return ParmVarDecl::Create(
3810 CGM.getContext(),
3811 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003812 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003813 NativeParam->getIdentifier(), ArgType,
3814 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003815}
3816
3817Address
3818CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3819 const VarDecl *NativeParam,
3820 const VarDecl *TargetParam) const {
3821 assert(NativeParam != TargetParam &&
3822 NativeParam->getType()->isReferenceType() &&
3823 "Native arg must not be the same as target arg.");
3824 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3825 QualType NativeParamType = NativeParam->getType();
3826 QualifierCollector QC;
3827 const Type *NonQualTy = QC.strip(NativeParamType);
3828 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3829 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003830 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003831 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003832 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003833 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003834 // First cast to generic.
3835 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3836 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3837 /*AddrSpace=*/0));
3838 // Cast from generic to native address space.
3839 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3840 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3841 NativePointeeAddrSpace));
3842 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3843 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003844 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003845 return NativeParamAddr;
3846}
3847
3848void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003849 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003850 ArrayRef<llvm::Value *> Args) const {
3851 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003852 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003853 auto *FnType =
3854 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3855 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003856 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3857 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3858 break;
3859 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003860 llvm::Type *TargetType = FnType->getParamType(I);
3861 llvm::Value *NativeArg = Args[I];
3862 if (!TargetType->isPointerTy()) {
3863 TargetArgs.emplace_back(NativeArg);
3864 continue;
3865 }
3866 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003867 NativeArg,
3868 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003869 TargetArgs.emplace_back(
3870 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3871 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003872 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003873}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003874
3875/// Emit function which wraps the outline parallel region
3876/// and controls the arguments which are passed to this function.
3877/// The wrapper ensures that the outlined function is called
3878/// with the correct arguments when data is shared.
3879llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3880 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3881 ASTContext &Ctx = CGM.getContext();
3882 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3883
3884 // Create a function that takes as argument the source thread.
3885 FunctionArgList WrapperArgs;
3886 QualType Int16QTy =
3887 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3888 QualType Int32QTy =
3889 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003890 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003891 /*Id=*/nullptr, Int16QTy,
3892 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003893 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003894 /*Id=*/nullptr, Int32QTy,
3895 ImplicitParamDecl::Other);
3896 WrapperArgs.emplace_back(&ParallelLevelArg);
3897 WrapperArgs.emplace_back(&WrapperArg);
3898
Alexey Bataev9ff80832018-04-16 20:16:21 +00003899 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003900 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3901
3902 auto *Fn = llvm::Function::Create(
3903 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003904 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003905 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003906 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003907 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003908
3909 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3910 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003911 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003912
3913 const auto *RD = CS.getCapturedRecordDecl();
3914 auto CurField = RD->field_begin();
3915
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003916 Address ZeroAddr = CGF.CreateMemTemp(
3917 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3918 /*Name*/ ".zero.addr");
3919 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003920 // Get the array of arguments.
3921 SmallVector<llvm::Value *, 8> Args;
3922
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003923 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3924 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003925
3926 CGBuilderTy &Bld = CGF.Builder;
3927 auto CI = CS.capture_begin();
3928
3929 // Use global memory for data sharing.
3930 // Handle passing of global args to workers.
3931 Address GlobalArgs =
3932 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3933 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3934 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3935 CGF.EmitRuntimeCall(
3936 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
3937 DataSharingArgs);
3938
3939 // Retrieve the shared variables from the list of references returned
3940 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00003941 Address SharedArgListAddress = Address::invalid();
3942 if (CS.capture_size() > 0 ||
3943 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3944 SharedArgListAddress = CGF.EmitLoadOfPointer(
3945 GlobalArgs, CGF.getContext()
3946 .getPointerType(CGF.getContext().getPointerType(
3947 CGF.getContext().VoidPtrTy))
3948 .castAs<PointerType>());
3949 }
3950 unsigned Idx = 0;
3951 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3952 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3953 CGF.getPointerSize());
3954 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3955 Src, CGF.SizeTy->getPointerTo());
3956 llvm::Value *LB = CGF.EmitLoadOfScalar(
3957 TypedAddress,
3958 /*Volatile=*/false,
3959 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3960 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3961 Args.emplace_back(LB);
3962 ++Idx;
3963 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
3964 CGF.getPointerSize());
3965 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3966 Src, CGF.SizeTy->getPointerTo());
3967 llvm::Value *UB = CGF.EmitLoadOfScalar(
3968 TypedAddress,
3969 /*Volatile=*/false,
3970 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3971 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3972 Args.emplace_back(UB);
3973 ++Idx;
3974 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003975 if (CS.capture_size() > 0) {
3976 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003977 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3978 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00003979 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
3980 CGF.getPointerSize());
3981 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003982 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3983 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3984 /*Volatile=*/false,
3985 CGFContext.getPointerType(ElemTy),
3986 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00003987 if (CI->capturesVariableByCopy() &&
3988 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00003989 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3990 CI->getLocation());
3991 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003992 Args.emplace_back(Arg);
3993 }
3994 }
3995
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003996 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003997 CGF.FinishFunction();
3998 return Fn;
3999}
4000
4001void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4002 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004003 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4004 return;
4005
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004006 assert(D && "Expected function or captured|block decl.");
4007 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4008 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004009 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004010 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004011 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4012 Body = FD->getBody();
4013 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4014 Body = BD->getBody();
4015 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4016 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004017 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004018 if (NeedToDelayGlobalization &&
4019 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4020 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004021 }
4022 if (!Body)
4023 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004024 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004025 VarChecker.Visit(Body);
4026 const RecordDecl *GlobalizedVarsRecord = VarChecker.getGlobalizedRecord();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004027 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4028 VarChecker.getEscapedVariableLengthDecls();
4029 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004030 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004031 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4032 I->getSecond().MappedParams =
4033 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4034 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4035 I->getSecond().EscapedParameters.insert(
4036 VarChecker.getEscapedParameters().begin(),
4037 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004038 I->getSecond().EscapedVariableLengthDecls.append(
4039 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004040 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004041 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004042 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004043 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004044 Data.insert(std::make_pair(VD, std::make_pair(FD, Address::invalid())));
4045 }
4046 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004047 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004048 struct GlobalizationScope final : EHScopeStack::Cleanup {
4049 GlobalizationScope() = default;
4050
4051 void Emit(CodeGenFunction &CGF, Flags flags) override {
4052 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004053 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004054 }
4055 };
4056 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004057 }
4058}
4059
4060Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4061 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004062 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4063 return Address::invalid();
4064
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004065 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004066 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4067 if (I == FunctionGlobalizedDecls.end())
4068 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004069 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004070 if (VDI != I->getSecond().LocalVarData.end())
4071 return VDI->second.second;
4072 if (VD->hasAttrs()) {
4073 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4074 E(VD->attr_end());
4075 IT != E; ++IT) {
4076 auto VDI = I->getSecond().LocalVarData.find(
4077 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4078 ->getCanonicalDecl());
4079 if (VDI != I->getSecond().LocalVarData.end())
4080 return VDI->second.second;
4081 }
4082 }
4083 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004084}
4085
4086void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004087 FunctionGlobalizedDecls.erase(CGF.CurFn);
4088 CGOpenMPRuntime::functionFinished(CGF);
4089}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004090
4091void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4092 CodeGenFunction &CGF, const OMPLoopDirective &S,
4093 OpenMPDistScheduleClauseKind &ScheduleKind,
4094 llvm::Value *&Chunk) const {
4095 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4096 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4097 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4098 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4099 S.getIterationVariable()->getType(), S.getBeginLoc());
4100 }
4101}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004102
4103void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4104 CodeGenFunction &CGF, const OMPLoopDirective &S,
4105 OpenMPScheduleClauseKind &ScheduleKind,
4106 llvm::Value *&Chunk) const {
4107 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4108 ScheduleKind = OMPC_SCHEDULE_static;
4109 Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
4110 S.getIterationVariable()->getType()), 1);
4111 }
4112}