blob: 944130b1abfd25861f205a5c3c93ab1f1b1832de [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.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000172 GlobalMemoryAlignment = 128,
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,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000189 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000190 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
191 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000192 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000193 return nullptr;
194 SmallVector<VarsDataTy, 4> GlobalizedVars;
195 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000196 GlobalizedVars.emplace_back(
197 CharUnits::fromQuantity(std::max(
198 C.getDeclAlign(D).getQuantity(),
199 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
200 D);
201 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000202 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
203 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
204 stable_sort_comparator);
205 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000206 // /* globalized vars */[WarSize] align (max(decl_align,
207 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000208 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000209 // };
210 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
211 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000212 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
213 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000214 for (const auto &Pair : GlobalizedVars) {
215 const ValueDecl *VD = Pair.second;
216 QualType Type = VD->getType();
217 if (Type->isLValueReferenceType())
218 Type = C.getPointerType(Type.getNonReferenceType());
219 else
220 Type = Type.getNonReferenceType();
221 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000222 FieldDecl *Field;
223 if (SingleEscaped.count(VD)) {
224 Field = FieldDecl::Create(
225 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
226 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
227 /*BW=*/nullptr, /*Mutable=*/false,
228 /*InitStyle=*/ICIS_NoInit);
229 Field->setAccess(AS_public);
230 if (VD->hasAttrs()) {
231 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
232 E(VD->getAttrs().end());
233 I != E; ++I)
234 Field->addAttr(*I);
235 }
236 } else {
237 llvm::APInt ArraySize(32, WarpSize);
238 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
239 Field = FieldDecl::Create(
240 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
241 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
242 /*BW=*/nullptr, /*Mutable=*/false,
243 /*InitStyle=*/ICIS_NoInit);
244 Field->setAccess(AS_public);
245 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
246 static_cast<CharUnits::QuantityType>(
247 GlobalMemoryAlignment)));
248 Field->addAttr(AlignedAttr::CreateImplicit(
249 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
250 IntegerLiteral::Create(C, Align,
251 C.getIntTypeForBitwidth(32, /*Signed=*/0),
252 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000253 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000254 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000255 MappedDeclsFields.try_emplace(VD, Field);
256 }
257 GlobalizedRD->completeDefinition();
258 return GlobalizedRD;
259}
260
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000261/// Get the list of variables that can escape their declaration context.
262class CheckVarsEscapingDeclContext final
263 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
264 CodeGenFunction &CGF;
265 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000266 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000267 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000268 RecordDecl *GlobalizedRD = nullptr;
269 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000270 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000271 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000272
273 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000274 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000275 if (!isa<VarDecl>(VD) ||
276 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000277 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000278 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000279 // Variables captured by value must be globalized.
280 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000281 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000282 // Check if need to capture the variable that was already captured by
283 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000284 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000285 if (!FD->hasAttrs())
286 return;
287 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
288 if (!Attr)
289 return;
290 if (!isOpenMPPrivate(
291 static_cast<OpenMPClauseKind>(Attr->getCaptureKind())) ||
292 Attr->getCaptureKind() == OMPC_map)
293 return;
294 }
295 if (!FD->getType()->isReferenceType()) {
296 assert(!VD->getType()->isVariablyModifiedType() &&
297 "Parameter captured by value with variably modified type");
298 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000299 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000300 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000301 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000302 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000303 }
304 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000305 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000306 VD->getType()->isReferenceType())
307 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000308 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000309 if (VD->getType()->isVariablyModifiedType())
310 EscapedVariableLengthDecls.insert(VD);
311 else
312 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313 }
314
315 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000316 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000317 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000318 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
319 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
320 const bool SavedAllEscaped = AllEscaped;
321 AllEscaped = VD->getType()->isLValueReferenceType();
322 Visit(VarD->getInit());
323 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000324 }
325 }
326 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000327 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
328 ArrayRef<OMPClause *> Clauses,
329 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000330 if (!S)
331 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000332 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000333 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
334 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000335 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
336 if (IsCombinedParallelRegion) {
337 // Check if the variable is privatized in the combined construct and
338 // those private copies must be shared in the inner parallel
339 // directive.
340 IsForCombinedParallelRegion = false;
341 for (const OMPClause *C : Clauses) {
342 if (!isOpenMPPrivate(C->getClauseKind()) ||
343 C->getClauseKind() == OMPC_reduction ||
344 C->getClauseKind() == OMPC_linear ||
345 C->getClauseKind() == OMPC_private)
346 continue;
347 ArrayRef<const Expr *> Vars;
348 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
349 Vars = PC->getVarRefs();
350 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
351 Vars = PC->getVarRefs();
352 else
353 llvm_unreachable("Unexpected clause.");
354 for (const auto *E : Vars) {
355 const Decl *D =
356 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
357 if (D == VD->getCanonicalDecl()) {
358 IsForCombinedParallelRegion = true;
359 break;
360 }
361 }
362 if (IsForCombinedParallelRegion)
363 break;
364 }
365 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000366 markAsEscaped(VD);
367 if (isa<OMPCapturedExprDecl>(VD))
368 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000369 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 }
371 }
372 }
373
Alexey Bataevff23bb62018-10-11 18:30:31 +0000374 void buildRecordForGlobalizedVars(bool IsInTargetMasterThreadRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000375 assert(!GlobalizedRD &&
376 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000377 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
378 if (IsInTargetMasterThreadRegion)
379 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
380 else
381 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000382 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000383 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000384 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 }
386
387public:
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000388 CheckVarsEscapingDeclContext(CodeGenFunction &CGF) : CGF(CGF) {}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000389 virtual ~CheckVarsEscapingDeclContext() = default;
390 void VisitDeclStmt(const DeclStmt *S) {
391 if (!S)
392 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000393 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000394 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
395 VisitValueDecl(VD);
396 }
397 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
398 if (!D)
399 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000400 if (!D->hasAssociatedStmt())
401 return;
402 if (const auto *S =
403 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
404 // Do not analyze directives that do not actually require capturing,
405 // like `omp for` or `omp simd` directives.
406 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
407 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
408 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
409 VisitStmt(S->getCapturedStmt());
410 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000411 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000412 VisitOpenMPCapturedStmt(
413 S, D->clauses(),
414 CaptureRegions.back() == OMPD_parallel &&
415 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 }
417 }
418 void VisitCapturedStmt(const CapturedStmt *S) {
419 if (!S)
420 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000421 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
423 const ValueDecl *VD = C.getCapturedVar();
424 markAsEscaped(VD);
425 if (isa<OMPCapturedExprDecl>(VD))
426 VisitValueDecl(VD);
427 }
428 }
429 }
430 void VisitLambdaExpr(const LambdaExpr *E) {
431 if (!E)
432 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000433 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000434 if (C.capturesVariable()) {
435 if (C.getCaptureKind() == LCK_ByRef) {
436 const ValueDecl *VD = C.getCapturedVar();
437 markAsEscaped(VD);
438 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
439 VisitValueDecl(VD);
440 }
441 }
442 }
443 }
444 void VisitBlockExpr(const BlockExpr *E) {
445 if (!E)
446 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000447 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000448 if (C.isByRef()) {
449 const VarDecl *VD = C.getVariable();
450 markAsEscaped(VD);
451 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
452 VisitValueDecl(VD);
453 }
454 }
455 }
456 void VisitCallExpr(const CallExpr *E) {
457 if (!E)
458 return;
459 for (const Expr *Arg : E->arguments()) {
460 if (!Arg)
461 continue;
462 if (Arg->isLValue()) {
463 const bool SavedAllEscaped = AllEscaped;
464 AllEscaped = true;
465 Visit(Arg);
466 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000467 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000468 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000469 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000470 }
471 Visit(E->getCallee());
472 }
473 void VisitDeclRefExpr(const DeclRefExpr *E) {
474 if (!E)
475 return;
476 const ValueDecl *VD = E->getDecl();
477 if (AllEscaped)
478 markAsEscaped(VD);
479 if (isa<OMPCapturedExprDecl>(VD))
480 VisitValueDecl(VD);
481 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
482 if (VarD->isInitCapture())
483 VisitValueDecl(VD);
484 }
485 void VisitUnaryOperator(const UnaryOperator *E) {
486 if (!E)
487 return;
488 if (E->getOpcode() == UO_AddrOf) {
489 const bool SavedAllEscaped = AllEscaped;
490 AllEscaped = true;
491 Visit(E->getSubExpr());
492 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000493 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000494 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000495 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000496 }
497 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
498 if (!E)
499 return;
500 if (E->getCastKind() == CK_ArrayToPointerDecay) {
501 const bool SavedAllEscaped = AllEscaped;
502 AllEscaped = true;
503 Visit(E->getSubExpr());
504 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000505 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000506 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000507 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000508 }
509 void VisitExpr(const Expr *E) {
510 if (!E)
511 return;
512 bool SavedAllEscaped = AllEscaped;
513 if (!E->isLValue())
514 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000515 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000516 if (Child)
517 Visit(Child);
518 AllEscaped = SavedAllEscaped;
519 }
520 void VisitStmt(const Stmt *S) {
521 if (!S)
522 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000523 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000524 if (Child)
525 Visit(Child);
526 }
527
Alexey Bataevc99042b2018-03-15 18:10:54 +0000528 /// Returns the record that handles all the escaped local variables and used
529 /// instead of their original storage.
Alexey Bataevff23bb62018-10-11 18:30:31 +0000530 const RecordDecl *getGlobalizedRecord(bool IsInTargetMasterThreadRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000531 if (!GlobalizedRD)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000532 buildRecordForGlobalizedVars(IsInTargetMasterThreadRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000533 return GlobalizedRD;
534 }
535
Alexey Bataevc99042b2018-03-15 18:10:54 +0000536 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000537 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
538 assert(GlobalizedRD &&
539 "Record for globalized variables must be generated already.");
540 auto I = MappedDeclsFields.find(VD);
541 if (I == MappedDeclsFields.end())
542 return nullptr;
543 return I->getSecond();
544 }
545
Alexey Bataevc99042b2018-03-15 18:10:54 +0000546 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000547 ArrayRef<const ValueDecl *> getEscapedDecls() const {
548 return EscapedDecls.getArrayRef();
549 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000550
551 /// Checks if the escaped local variable is actually a parameter passed by
552 /// value.
553 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
554 return EscapedParameters;
555 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000556
557 /// Returns the list of the escaped variables with the variably modified
558 /// types.
559 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
560 return EscapedVariableLengthDecls.getArrayRef();
561 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000562};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000563} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000564
565/// Get the GPU warp size.
566static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000567 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000568 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000569 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000570 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000571}
572
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000573/// Get the id of the current thread on the GPU.
574static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000575 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000576 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000577 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000578 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000579}
580
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000581/// Get the id of the warp in the block.
582/// We assume that the warp size is 32, which is always the case
583/// on the NVPTX device, to generate more efficient code.
584static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
585 CGBuilderTy &Bld = CGF.Builder;
586 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
587}
588
589/// Get the id of the current lane in the Warp.
590/// We assume that the warp size is 32, which is always the case
591/// on the NVPTX device, to generate more efficient code.
592static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
593 CGBuilderTy &Bld = CGF.Builder;
594 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
595 "nvptx_lane_id");
596}
597
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000598/// Get the maximum number of threads in a block of the GPU.
599static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000600 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000601 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000602 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000603 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000604}
605
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000606/// Get barrier to synchronize all threads in a block.
607static void getNVPTXCTABarrier(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000608 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000609 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000610}
611
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000612/// Get barrier #ID to synchronize selected (multiple of warp size) threads in
613/// a CTA.
614static void getNVPTXBarrier(CodeGenFunction &CGF, int ID,
615 llvm::Value *NumThreads) {
616 CGBuilderTy &Bld = CGF.Builder;
617 llvm::Value *Args[] = {Bld.getInt32(ID), NumThreads};
Alexey Bataev3c595a62017-08-14 15:01:03 +0000618 CGF.EmitRuntimeCall(llvm::Intrinsic::getDeclaration(
619 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier),
620 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000621}
622
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000623/// Synchronize all GPU threads in a block.
624static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000625
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000626/// Synchronize worker threads in a parallel region.
627static void syncParallelThreads(CodeGenFunction &CGF, llvm::Value *NumThreads) {
628 return getNVPTXBarrier(CGF, NB_Parallel, NumThreads);
629}
630
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000631/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000632/// For the 'generic' execution mode, the runtime encodes thread_limit in
633/// the launch parameters, always starting thread_limit+warpSize threads per
634/// CTA. The threads in the last warp are reserved for master execution.
635/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
636static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000637 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000638 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000639 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000640 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000641 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
642 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000643}
644
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000645/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000646/// The master thread id is the first thread (lane) of the last warp in the
647/// GPU block. Warp size is assumed to be some power of 2.
648/// Thread id is 0 indexed.
649/// E.g: If NumThreads is 33, master id is 32.
650/// If NumThreads is 64, master id is 32.
651/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000652static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000653 CGBuilderTy &Bld = CGF.Builder;
654 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
655
656 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000657 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000658
Alexey Bataeve290ec02018-04-06 16:03:36 +0000659 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000660 Bld.CreateNot(Mask), "master_tid");
661}
662
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000663CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000664 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000665 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
666 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000667 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000668}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000669
670void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
671 CodeGenModule &CGM) {
672 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000673
674 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000675 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000676 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000677 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000678 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000679}
680
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000681CGOpenMPRuntimeNVPTX::ExecutionMode
682CGOpenMPRuntimeNVPTX::getExecutionMode() const {
683 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000684}
685
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000686static CGOpenMPRuntimeNVPTX::DataSharingMode
687getDataSharingMode(CodeGenModule &CGM) {
688 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
689 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000690}
691
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000692/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
693/// iff there is only one.
694static const Stmt *getSingleCompoundChild(const Stmt *Body) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000695 if (const auto *C = dyn_cast<CompoundStmt>(Body))
696 if (C->size() == 1)
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000697 return C->body_front();
698 return Body;
699}
700
701/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000702/// false condition. Also, check if the number of threads is strictly specified
703/// and run those directives in non-SPMD mode.
704static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
705 const OMPExecutableDirective &D) {
706 if (D.hasClausesOfKind<OMPNumThreadsClause>())
707 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000708 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
709 OpenMPDirectiveKind NameModifier = C->getNameModifier();
710 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
711 continue;
712 const Expr *Cond = C->getCondition();
713 bool Result;
714 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
715 return true;
716 }
717 return false;
718}
719
720/// Check for inner (nested) SPMD construct, if any
721static bool hasNestedSPMDDirective(ASTContext &Ctx,
722 const OMPExecutableDirective &D) {
723 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000724 const auto *Body =
725 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000726 const Stmt *ChildStmt = getSingleCompoundChild(Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727
728 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
729 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000730 switch (D.getDirectiveKind()) {
731 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000732 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000733 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000734 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000735 if (DKind == OMPD_teams) {
736 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
737 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000738 if (!Body)
739 return false;
740 ChildStmt = getSingleCompoundChild(Body);
741 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
742 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000743 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000744 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000745 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000746 }
747 }
748 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000749 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000750 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000751 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000752 case OMPD_target_simd:
753 case OMPD_target_parallel:
754 case OMPD_target_parallel_for:
755 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000756 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000757 case OMPD_target_teams_distribute_simd:
758 case OMPD_target_teams_distribute_parallel_for:
759 case OMPD_target_teams_distribute_parallel_for_simd:
760 case OMPD_parallel:
761 case OMPD_for:
762 case OMPD_parallel_for:
763 case OMPD_parallel_sections:
764 case OMPD_for_simd:
765 case OMPD_parallel_for_simd:
766 case OMPD_cancel:
767 case OMPD_cancellation_point:
768 case OMPD_ordered:
769 case OMPD_threadprivate:
770 case OMPD_task:
771 case OMPD_simd:
772 case OMPD_sections:
773 case OMPD_section:
774 case OMPD_single:
775 case OMPD_master:
776 case OMPD_critical:
777 case OMPD_taskyield:
778 case OMPD_barrier:
779 case OMPD_taskwait:
780 case OMPD_taskgroup:
781 case OMPD_atomic:
782 case OMPD_flush:
783 case OMPD_teams:
784 case OMPD_target_data:
785 case OMPD_target_exit_data:
786 case OMPD_target_enter_data:
787 case OMPD_distribute:
788 case OMPD_distribute_simd:
789 case OMPD_distribute_parallel_for:
790 case OMPD_distribute_parallel_for_simd:
791 case OMPD_teams_distribute:
792 case OMPD_teams_distribute_simd:
793 case OMPD_teams_distribute_parallel_for:
794 case OMPD_teams_distribute_parallel_for_simd:
795 case OMPD_target_update:
796 case OMPD_declare_simd:
797 case OMPD_declare_target:
798 case OMPD_end_declare_target:
799 case OMPD_declare_reduction:
800 case OMPD_taskloop:
801 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000802 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000803 case OMPD_unknown:
804 llvm_unreachable("Unexpected directive.");
805 }
806 }
807
808 return false;
809}
810
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000811static bool supportsSPMDExecutionMode(ASTContext &Ctx,
812 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000813 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
814 switch (DirectiveKind) {
815 case OMPD_target:
816 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000817 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_parallel:
819 case OMPD_target_parallel_for:
820 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 case OMPD_target_teams_distribute_parallel_for:
822 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000823 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000824 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000825 case OMPD_target_teams_distribute:
826 case OMPD_target_teams_distribute_simd:
827 return false;
828 case OMPD_parallel:
829 case OMPD_for:
830 case OMPD_parallel_for:
831 case OMPD_parallel_sections:
832 case OMPD_for_simd:
833 case OMPD_parallel_for_simd:
834 case OMPD_cancel:
835 case OMPD_cancellation_point:
836 case OMPD_ordered:
837 case OMPD_threadprivate:
838 case OMPD_task:
839 case OMPD_simd:
840 case OMPD_sections:
841 case OMPD_section:
842 case OMPD_single:
843 case OMPD_master:
844 case OMPD_critical:
845 case OMPD_taskyield:
846 case OMPD_barrier:
847 case OMPD_taskwait:
848 case OMPD_taskgroup:
849 case OMPD_atomic:
850 case OMPD_flush:
851 case OMPD_teams:
852 case OMPD_target_data:
853 case OMPD_target_exit_data:
854 case OMPD_target_enter_data:
855 case OMPD_distribute:
856 case OMPD_distribute_simd:
857 case OMPD_distribute_parallel_for:
858 case OMPD_distribute_parallel_for_simd:
859 case OMPD_teams_distribute:
860 case OMPD_teams_distribute_simd:
861 case OMPD_teams_distribute_parallel_for:
862 case OMPD_teams_distribute_parallel_for_simd:
863 case OMPD_target_update:
864 case OMPD_declare_simd:
865 case OMPD_declare_target:
866 case OMPD_end_declare_target:
867 case OMPD_declare_reduction:
868 case OMPD_taskloop:
869 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000870 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_unknown:
872 break;
873 }
874 llvm_unreachable(
875 "Unknown programming model for OpenMP directive on NVPTX target.");
876}
877
878/// Check if the directive is loops based and has schedule clause at all or has
879/// static scheduling.
880static bool hasStaticScheduling(const OMPExecutableDirective &D) {
881 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
882 isOpenMPLoopDirective(D.getDirectiveKind()) &&
883 "Expected loop-based directive.");
884 return !D.hasClausesOfKind<OMPOrderedClause>() &&
885 (!D.hasClausesOfKind<OMPScheduleClause>() ||
886 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
887 [](const OMPScheduleClause *C) {
888 return C->getScheduleKind() == OMPC_SCHEDULE_static;
889 }));
890}
891
892/// Check for inner (nested) lightweight runtime construct, if any
893static bool hasNestedLightweightDirective(ASTContext &Ctx,
894 const OMPExecutableDirective &D) {
895 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
896 const auto *CS = D.getInnermostCapturedStmt();
897 const auto *Body =
898 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
899 const Stmt *ChildStmt = getSingleCompoundChild(Body);
900
901 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
902 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
903 switch (D.getDirectiveKind()) {
904 case OMPD_target:
905 if (isOpenMPParallelDirective(DKind) &&
906 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
907 hasStaticScheduling(*NestedDir))
908 return true;
909 if (DKind == OMPD_parallel) {
910 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
911 /*IgnoreCaptured=*/true);
912 if (!Body)
913 return false;
914 ChildStmt = getSingleCompoundChild(Body);
915 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
916 DKind = NND->getDirectiveKind();
917 if (isOpenMPWorksharingDirective(DKind) &&
918 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
919 return true;
920 }
921 } else if (DKind == OMPD_teams) {
922 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
923 /*IgnoreCaptured=*/true);
924 if (!Body)
925 return false;
926 ChildStmt = getSingleCompoundChild(Body);
927 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
928 DKind = NND->getDirectiveKind();
929 if (isOpenMPParallelDirective(DKind) &&
930 isOpenMPWorksharingDirective(DKind) &&
931 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
932 return true;
933 if (DKind == OMPD_parallel) {
934 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
935 /*IgnoreCaptured=*/true);
936 if (!Body)
937 return false;
938 ChildStmt = getSingleCompoundChild(Body);
939 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
940 DKind = NND->getDirectiveKind();
941 if (isOpenMPWorksharingDirective(DKind) &&
942 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
943 return true;
944 }
945 }
946 }
947 }
948 return false;
949 case OMPD_target_teams:
950 if (isOpenMPParallelDirective(DKind) &&
951 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
952 hasStaticScheduling(*NestedDir))
953 return true;
954 if (DKind == OMPD_parallel) {
955 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
956 /*IgnoreCaptured=*/true);
957 if (!Body)
958 return false;
959 ChildStmt = getSingleCompoundChild(Body);
960 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
961 DKind = NND->getDirectiveKind();
962 if (isOpenMPWorksharingDirective(DKind) &&
963 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
964 return true;
965 }
966 }
967 return false;
968 case OMPD_target_parallel:
969 return isOpenMPWorksharingDirective(DKind) &&
970 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
971 case OMPD_target_teams_distribute:
972 case OMPD_target_simd:
973 case OMPD_target_parallel_for:
974 case OMPD_target_parallel_for_simd:
975 case OMPD_target_teams_distribute_simd:
976 case OMPD_target_teams_distribute_parallel_for:
977 case OMPD_target_teams_distribute_parallel_for_simd:
978 case OMPD_parallel:
979 case OMPD_for:
980 case OMPD_parallel_for:
981 case OMPD_parallel_sections:
982 case OMPD_for_simd:
983 case OMPD_parallel_for_simd:
984 case OMPD_cancel:
985 case OMPD_cancellation_point:
986 case OMPD_ordered:
987 case OMPD_threadprivate:
988 case OMPD_task:
989 case OMPD_simd:
990 case OMPD_sections:
991 case OMPD_section:
992 case OMPD_single:
993 case OMPD_master:
994 case OMPD_critical:
995 case OMPD_taskyield:
996 case OMPD_barrier:
997 case OMPD_taskwait:
998 case OMPD_taskgroup:
999 case OMPD_atomic:
1000 case OMPD_flush:
1001 case OMPD_teams:
1002 case OMPD_target_data:
1003 case OMPD_target_exit_data:
1004 case OMPD_target_enter_data:
1005 case OMPD_distribute:
1006 case OMPD_distribute_simd:
1007 case OMPD_distribute_parallel_for:
1008 case OMPD_distribute_parallel_for_simd:
1009 case OMPD_teams_distribute:
1010 case OMPD_teams_distribute_simd:
1011 case OMPD_teams_distribute_parallel_for:
1012 case OMPD_teams_distribute_parallel_for_simd:
1013 case OMPD_target_update:
1014 case OMPD_declare_simd:
1015 case OMPD_declare_target:
1016 case OMPD_end_declare_target:
1017 case OMPD_declare_reduction:
1018 case OMPD_taskloop:
1019 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001020 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001021 case OMPD_unknown:
1022 llvm_unreachable("Unexpected directive.");
1023 }
1024 }
1025
1026 return false;
1027}
1028
1029/// Checks if the construct supports lightweight runtime. It must be SPMD
1030/// construct + inner loop-based construct with static scheduling.
1031static bool supportsLightweightRuntime(ASTContext &Ctx,
1032 const OMPExecutableDirective &D) {
1033 if (!supportsSPMDExecutionMode(Ctx, D))
1034 return false;
1035 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1036 switch (DirectiveKind) {
1037 case OMPD_target:
1038 case OMPD_target_teams:
1039 case OMPD_target_parallel:
1040 return hasNestedLightweightDirective(Ctx, D);
1041 case OMPD_target_parallel_for:
1042 case OMPD_target_parallel_for_simd:
1043 case OMPD_target_teams_distribute_parallel_for:
1044 case OMPD_target_teams_distribute_parallel_for_simd:
1045 // (Last|First)-privates must be shared in parallel region.
1046 return hasStaticScheduling(D);
1047 case OMPD_target_simd:
1048 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001049 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001050 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001051 case OMPD_parallel:
1052 case OMPD_for:
1053 case OMPD_parallel_for:
1054 case OMPD_parallel_sections:
1055 case OMPD_for_simd:
1056 case OMPD_parallel_for_simd:
1057 case OMPD_cancel:
1058 case OMPD_cancellation_point:
1059 case OMPD_ordered:
1060 case OMPD_threadprivate:
1061 case OMPD_task:
1062 case OMPD_simd:
1063 case OMPD_sections:
1064 case OMPD_section:
1065 case OMPD_single:
1066 case OMPD_master:
1067 case OMPD_critical:
1068 case OMPD_taskyield:
1069 case OMPD_barrier:
1070 case OMPD_taskwait:
1071 case OMPD_taskgroup:
1072 case OMPD_atomic:
1073 case OMPD_flush:
1074 case OMPD_teams:
1075 case OMPD_target_data:
1076 case OMPD_target_exit_data:
1077 case OMPD_target_enter_data:
1078 case OMPD_distribute:
1079 case OMPD_distribute_simd:
1080 case OMPD_distribute_parallel_for:
1081 case OMPD_distribute_parallel_for_simd:
1082 case OMPD_teams_distribute:
1083 case OMPD_teams_distribute_simd:
1084 case OMPD_teams_distribute_parallel_for:
1085 case OMPD_teams_distribute_parallel_for_simd:
1086 case OMPD_target_update:
1087 case OMPD_declare_simd:
1088 case OMPD_declare_target:
1089 case OMPD_end_declare_target:
1090 case OMPD_declare_reduction:
1091 case OMPD_taskloop:
1092 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001093 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001094 case OMPD_unknown:
1095 break;
1096 }
1097 llvm_unreachable(
1098 "Unknown programming model for OpenMP directive on NVPTX target.");
1099}
1100
1101void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001102 StringRef ParentName,
1103 llvm::Function *&OutlinedFn,
1104 llvm::Constant *&OutlinedFnID,
1105 bool IsOffloadEntry,
1106 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001107 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001108 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001109 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001110 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001111 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001112
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001113 // Emit target region as a standalone region.
1114 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001115 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1116 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001117
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001118 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001119 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001120 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001121 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001122 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001123 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1124 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1125 // Skip target region initialization.
1126 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 }
1128 void Exit(CodeGenFunction &CGF) override {
Alexey Bataev6bc27322018-10-05 15:27:47 +00001129 auto &RT = static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1130 RT.clearLocThreadIdInsertPt(CGF);
1131 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001132 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001133 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001134 CodeGen.setAction(Action);
1135 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1136 IsOffloadEntry, CodeGen);
1137
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138 // Now change the name of the worker function to correspond to this target
1139 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001140 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001141
1142 // Create the worker function
1143 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001144}
1145
1146// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001147void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001148 EntryFunctionState &EST,
1149 WorkerFunctionState &WST) {
1150 CGBuilderTy &Bld = CGF.Builder;
1151
1152 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1153 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1154 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1155 EST.ExitBB = CGF.createBasicBlock(".exit");
1156
Alexey Bataev9ff80832018-04-16 20:16:21 +00001157 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001158 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1159 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1160
1161 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001162 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001163 CGF.EmitBranch(EST.ExitBB);
1164
1165 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001166 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1168 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1169
1170 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001171 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001172 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001173 // First action in sequential region:
1174 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001175 // TODO: Optimize runtime initialization and pass in correct value.
1176 llvm::Value *Args[] = {getThreadLimit(CGF),
1177 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 CGF.EmitRuntimeCall(
1179 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001180
1181 // For data sharing, we need to initialize the stack.
1182 CGF.EmitRuntimeCall(
1183 createNVPTXRuntimeFunction(
1184 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1185
Alexey Bataevc99042b2018-03-15 18:10:54 +00001186 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001187}
1188
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001189void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001190 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001191 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001192 if (!CGF.HaveInsertPoint())
1193 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001194
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001195 emitGenericVarsEpilog(CGF);
1196
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 if (!EST.ExitBB)
1198 EST.ExitBB = CGF.createBasicBlock(".exit");
1199
1200 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1201 CGF.EmitBranch(TerminateBB);
1202
1203 CGF.EmitBlock(TerminateBB);
1204 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001205 // TODO: Optimize runtime initialization and pass in correct value.
1206 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001207 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001208 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 // Barrier to terminate worker threads.
1210 syncCTAThreads(CGF);
1211 // Master thread jumps to exit point.
1212 CGF.EmitBranch(EST.ExitBB);
1213
1214 CGF.EmitBlock(EST.ExitBB);
1215 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001216}
1217
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001218void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001219 StringRef ParentName,
1220 llvm::Function *&OutlinedFn,
1221 llvm::Constant *&OutlinedFnID,
1222 bool IsOffloadEntry,
1223 const RegionCodeGenTy &CodeGen) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001224 ExecutionModeRAII ModeRAII(CurrentExecutionMode, /*IsSPMD=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001225 EntryFunctionState EST;
1226
1227 // Emit target region as a standalone region.
1228 class NVPTXPrePostActionTy : public PrePostActionTy {
1229 CGOpenMPRuntimeNVPTX &RT;
1230 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1231 const OMPExecutableDirective &D;
1232
1233 public:
1234 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1235 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1236 const OMPExecutableDirective &D)
1237 : RT(RT), EST(EST), D(D) {}
1238 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001239 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001240 // Skip target region initialization.
1241 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001242 }
1243 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001244 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001245 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001246 }
1247 } Action(*this, EST, D);
1248 CodeGen.setAction(Action);
1249 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1250 IsOffloadEntry, CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001251}
1252
Alexey Bataeve79451a2018-10-01 16:20:57 +00001253static void
1254getDistributeLastprivateVars(const OMPExecutableDirective &D,
1255 llvm::SmallVectorImpl<const ValueDecl *> &Vars);
1256
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001257void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001258 CodeGenFunction &CGF, EntryFunctionState &EST,
1259 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001260 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001261
1262 // Setup BBs in entry function.
1263 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1264 EST.ExitBB = CGF.createBasicBlock(".exit");
1265
1266 // Initialize the OMP state in the runtime; called by all active threads.
Alexey Bataev80a9a612018-08-30 14:45:24 +00001267 bool RequiresFullRuntime = CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1268 !supportsLightweightRuntime(CGF.getContext(), D);
Alexey Bataeve79451a2018-10-01 16:20:57 +00001269 // Check if we have inner distribute + lastprivate|reduction clauses.
1270 bool RequiresDatasharing = RequiresFullRuntime;
1271 if (!RequiresDatasharing) {
1272 const OMPExecutableDirective *TD = &D;
1273 if (!isOpenMPTeamsDirective(TD->getDirectiveKind()) &&
1274 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1275 const Stmt *S = getSingleCompoundChild(
1276 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1277 /*IgnoreCaptured=*/true));
1278 TD = cast<OMPExecutableDirective>(S);
1279 }
1280 if (!isOpenMPDistributeDirective(TD->getDirectiveKind()) &&
1281 !isOpenMPParallelDirective(TD->getDirectiveKind())) {
1282 const Stmt *S = getSingleCompoundChild(
1283 TD->getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1284 /*IgnoreCaptured=*/true));
1285 TD = cast<OMPExecutableDirective>(S);
1286 }
1287 if (isOpenMPDistributeDirective(TD->getDirectiveKind()))
1288 RequiresDatasharing = TD->hasClausesOfKind<OMPLastprivateClause>() ||
1289 TD->hasClausesOfKind<OMPReductionClause>();
1290 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001291 llvm::Value *Args[] = {
1292 getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1293 /*RequiresOMPRuntime=*/
1294 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
Alexey Bataeve79451a2018-10-01 16:20:57 +00001295 /*RequiresDataSharing=*/Bld.getInt16(RequiresDatasharing ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001296 CGF.EmitRuntimeCall(
1297 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001298
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001299 if (RequiresFullRuntime) {
1300 // For data sharing, we need to initialize the stack.
1301 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1302 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1303 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001304
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001305 CGF.EmitBranch(ExecuteBB);
1306
1307 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001308
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001309 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001310}
1311
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001312void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001313 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001314 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001315 if (!CGF.HaveInsertPoint())
1316 return;
1317
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001318 if (!EST.ExitBB)
1319 EST.ExitBB = CGF.createBasicBlock(".exit");
1320
1321 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1322 CGF.EmitBranch(OMPDeInitBB);
1323
1324 CGF.EmitBlock(OMPDeInitBB);
1325 // DeInitialize the OMP state in the runtime; called by all active threads.
1326 CGF.EmitRuntimeCall(
1327 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None);
1328 CGF.EmitBranch(EST.ExitBB);
1329
1330 CGF.EmitBlock(EST.ExitBB);
1331 EST.ExitBB = nullptr;
1332}
1333
1334// Create a unique global variable to indicate the execution mode of this target
1335// region. The execution mode is either 'generic', or 'spmd' depending on the
1336// target directive. This variable is picked up by the offload library to setup
1337// the device appropriately before kernel launch. If the execution mode is
1338// 'generic', the runtime reserves one warp for the master, otherwise, all
1339// warps participate in parallel work.
1340static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001341 bool Mode) {
1342 auto *GVMode =
1343 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1344 llvm::GlobalValue::WeakAnyLinkage,
1345 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1346 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001347 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348}
1349
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001350void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001351 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001352
1353 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001354 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001355 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001356 emitWorkerLoop(CGF, WST);
1357 CGF.FinishFunction();
1358}
1359
1360void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1361 WorkerFunctionState &WST) {
1362 //
1363 // The workers enter this loop and wait for parallel work from the master.
1364 // When the master encounters a parallel region it sets up the work + variable
1365 // arguments, and wakes up the workers. The workers first check to see if
1366 // they are required for the parallel region, i.e., within the # of requested
1367 // parallel threads. The activated workers load the variable arguments and
1368 // execute the parallel work.
1369 //
1370
1371 CGBuilderTy &Bld = CGF.Builder;
1372
1373 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1374 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1375 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1376 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1377 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1378 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1379
1380 CGF.EmitBranch(AwaitBB);
1381
1382 // Workers wait for work from master.
1383 CGF.EmitBlock(AwaitBB);
1384 // Wait for parallel work
1385 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001386
1387 Address WorkFn =
1388 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1389 Address ExecStatus =
1390 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1391 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1392 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1393
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001394 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001395 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001396 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001397 llvm::Value *Ret = CGF.EmitRuntimeCall(
1398 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1399 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001400
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001401 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001402 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1403 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001404 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1405
1406 // Activate requested workers.
1407 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001408 llvm::Value *IsActive =
1409 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1410 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001411
1412 // Signal start of parallel region.
1413 CGF.EmitBlock(ExecuteBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001414
1415 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001416 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001417 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001418 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001419
1420 llvm::Value *WorkFnMatch =
1421 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1422
1423 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1424 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1425 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1426
1427 // Execute this outlined function.
1428 CGF.EmitBlock(ExecuteFNBB);
1429
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001430 // Insert call to work function via shared wrapper. The shared
1431 // wrapper takes two arguments:
1432 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001433 // - the thread ID;
1434 emitCall(CGF, WST.Loc, W,
1435 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001436
1437 // Go to end of parallel region.
1438 CGF.EmitBranch(TerminateBB);
1439
1440 CGF.EmitBlock(CheckNextBB);
1441 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001442 // Default case: call to outlined function through pointer if the target
1443 // region makes a declare target call that may contain an orphaned parallel
1444 // directive.
1445 auto *ParallelFnTy =
1446 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1447 /*isVarArg=*/false)
1448 ->getPointerTo();
1449 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1450 // Insert call to work function via shared wrapper. The shared
1451 // wrapper takes two arguments:
1452 // - the parallelism level;
1453 // - the thread ID;
1454 emitCall(CGF, WST.Loc, WorkFnCast,
1455 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1456 // Go to end of parallel region.
1457 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001458
1459 // Signal end of parallel region.
1460 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001461 CGF.EmitRuntimeCall(
1462 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1463 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001464 CGF.EmitBranch(BarrierBB);
1465
1466 // All active and inactive workers wait at a barrier after parallel region.
1467 CGF.EmitBlock(BarrierBB);
1468 // Barrier after parallel region.
1469 syncCTAThreads(CGF);
1470 CGF.EmitBranch(AwaitBB);
1471
1472 // Exit target region.
1473 CGF.EmitBlock(ExitBB);
1474}
1475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001476/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001477/// implementation. Specialized for the NVPTX device.
1478/// \param Function OpenMP runtime function.
1479/// \return Specified function.
1480llvm::Constant *
1481CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1482 llvm::Constant *RTLFn = nullptr;
1483 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1484 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001485 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1486 // RequiresOMPRuntime);
1487 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001488 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001489 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1491 break;
1492 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001493 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001494 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1495 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001496 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001497 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001498 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1499 break;
1500 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001501 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1502 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001503 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001504 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001505 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1508 break;
1509 }
1510 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: {
1511 // Build void __kmpc_spmd_kernel_deinit();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001512 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001513 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit");
1515 break;
1516 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001517 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1518 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001519 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001520 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001521 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001522 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1523 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1524 break;
1525 }
1526 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001527 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1528 /// int16_t IsOMPRuntimeInitialized);
1529 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001530 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001531 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001532 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1533 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1534 break;
1535 }
1536 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1537 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001538 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001539 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1540 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1541 break;
1542 }
1543 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1544 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1545 // global_tid);
1546 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001547 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001548 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1549 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1550 break;
1551 }
1552 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1553 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1554 // global_tid);
1555 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001556 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001557 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1558 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1559 break;
1560 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001561 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1562 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1563 // int16_t lane_offset, int16_t warp_size);
1564 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001565 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001566 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1568 break;
1569 }
1570 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1571 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1572 // int16_t lane_offset, int16_t warp_size);
1573 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001574 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001575 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1576 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1577 break;
1578 }
1579 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait: {
1580 // Build int32_t kmpc_nvptx_parallel_reduce_nowait(kmp_int32 global_tid,
1581 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1582 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1583 // lane_offset, int16_t Algorithm Version),
1584 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1585 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1586 CGM.Int16Ty, CGM.Int16Ty};
1587 auto *ShuffleReduceFnTy =
1588 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1589 /*isVarArg=*/false);
1590 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1591 auto *InterWarpCopyFnTy =
1592 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1593 /*isVarArg=*/false);
1594 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1595 CGM.Int32Ty,
1596 CGM.SizeTy,
1597 CGM.VoidPtrTy,
1598 ShuffleReduceFnTy->getPointerTo(),
1599 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001600 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001601 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1602 RTLFn = CGM.CreateRuntimeFunction(
1603 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait");
1604 break;
1605 }
Alexey Bataevfac26cf2018-05-02 20:03:27 +00001606 case OMPRTL_NVPTX__kmpc_simd_reduce_nowait: {
1607 // Build int32_t kmpc_nvptx_simd_reduce_nowait(kmp_int32 global_tid,
1608 // kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
1609 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1610 // lane_offset, int16_t Algorithm Version),
1611 // void (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1612 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1613 CGM.Int16Ty, CGM.Int16Ty};
1614 auto *ShuffleReduceFnTy =
1615 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1616 /*isVarArg=*/false);
1617 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1618 auto *InterWarpCopyFnTy =
1619 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1620 /*isVarArg=*/false);
1621 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1622 CGM.Int32Ty,
1623 CGM.SizeTy,
1624 CGM.VoidPtrTy,
1625 ShuffleReduceFnTy->getPointerTo(),
1626 InterWarpCopyFnTy->getPointerTo()};
1627 auto *FnTy =
1628 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1629 RTLFn = CGM.CreateRuntimeFunction(
1630 FnTy, /*Name=*/"__kmpc_nvptx_simd_reduce_nowait");
1631 break;
1632 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001633 case OMPRTL_NVPTX__kmpc_teams_reduce_nowait: {
1634 // Build int32_t __kmpc_nvptx_teams_reduce_nowait(int32_t global_tid,
1635 // int32_t num_vars, size_t reduce_size, void *reduce_data,
1636 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1637 // lane_offset, int16_t shortCircuit),
1638 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num),
1639 // void (*kmp_CopyToScratchpadFctPtr)(void *reduce_data, void * scratchpad,
1640 // int32_t index, int32_t width),
1641 // void (*kmp_LoadReduceFctPtr)(void *reduce_data, void * scratchpad,
1642 // int32_t index, int32_t width, int32_t reduce))
1643 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1644 CGM.Int16Ty, CGM.Int16Ty};
1645 auto *ShuffleReduceFnTy =
1646 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1647 /*isVarArg=*/false);
1648 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1649 auto *InterWarpCopyFnTy =
1650 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1651 /*isVarArg=*/false);
1652 llvm::Type *CopyToScratchpadTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy,
1653 CGM.Int32Ty, CGM.Int32Ty};
1654 auto *CopyToScratchpadFnTy =
1655 llvm::FunctionType::get(CGM.VoidTy, CopyToScratchpadTypeParams,
1656 /*isVarArg=*/false);
1657 llvm::Type *LoadReduceTypeParams[] = {
1658 CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty};
1659 auto *LoadReduceFnTy =
1660 llvm::FunctionType::get(CGM.VoidTy, LoadReduceTypeParams,
1661 /*isVarArg=*/false);
1662 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1663 CGM.Int32Ty,
1664 CGM.SizeTy,
1665 CGM.VoidPtrTy,
1666 ShuffleReduceFnTy->getPointerTo(),
1667 InterWarpCopyFnTy->getPointerTo(),
1668 CopyToScratchpadFnTy->getPointerTo(),
1669 LoadReduceFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001670 auto *FnTy =
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00001671 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1672 RTLFn = CGM.CreateRuntimeFunction(
1673 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait");
1674 break;
1675 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001676 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1677 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1678 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001679 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001680 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1681 RTLFn = CGM.CreateRuntimeFunction(
1682 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1683 break;
1684 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001685 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1686 /// Build void __kmpc_data_sharing_init_stack();
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_data_sharing_init_stack");
1690 break;
1691 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001692 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1693 /// Build void __kmpc_data_sharing_init_stack_spmd();
1694 auto *FnTy =
1695 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001696 RTLFn =
1697 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001698 break;
1699 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001700 case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1701 // Build void *__kmpc_data_sharing_push_stack(size_t size,
1702 // int16_t UseSharedMemory);
1703 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001704 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001705 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1706 RTLFn = CGM.CreateRuntimeFunction(
1707 FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1708 break;
1709 }
1710 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1711 // Build void __kmpc_data_sharing_pop_stack(void *a);
1712 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001713 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001714 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1715 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1716 /*Name=*/"__kmpc_data_sharing_pop_stack");
1717 break;
1718 }
1719 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1720 /// Build void __kmpc_begin_sharing_variables(void ***args,
1721 /// size_t n_args);
1722 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001723 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001724 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1725 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1726 break;
1727 }
1728 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1729 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001730 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001731 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1732 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1733 break;
1734 }
1735 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1736 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1737 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001738 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001739 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1740 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1741 break;
1742 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001743 case OMPRTL_NVPTX__kmpc_parallel_level: {
1744 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1745 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1746 auto *FnTy =
1747 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1749 break;
1750 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001751 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1752 // Build int8_t __kmpc_is_spmd_exec_mode();
1753 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1754 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1755 break;
1756 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001757 }
1758 return RTLFn;
1759}
1760
1761void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1762 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001763 uint64_t Size, int32_t,
1764 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001765 // TODO: Add support for global variables on the device after declare target
1766 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001767 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001768 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001769 llvm::Module &M = CGM.getModule();
1770 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001771
1772 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001773 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001774
1775 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001776 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001777 llvm::ConstantAsMetadata::get(
1778 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1779 // Append metadata to nvvm.annotations
1780 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1781}
1782
1783void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1784 const OMPExecutableDirective &D, StringRef ParentName,
1785 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001786 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001787 if (!IsOffloadEntry) // Nothing to do.
1788 return;
1789
1790 assert(!ParentName.empty() && "Invalid target region parent name!");
1791
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001792 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001793 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001794 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001795 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001796 else
1797 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1798 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001799
1800 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001801}
1802
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001803CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001804 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001805 if (!CGM.getLangOpts().OpenMPIsDevice)
1806 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001807}
Carlo Bertollic6872252016-04-04 15:55:02 +00001808
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001809void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1810 OpenMPProcBindClauseKind ProcBind,
1811 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001812 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001813 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001814 return;
1815
1816 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1817}
1818
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001819void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1820 llvm::Value *NumThreads,
1821 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001822 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001823 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001824 return;
1825
1826 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1827}
1828
Carlo Bertollic6872252016-04-04 15:55:02 +00001829void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1830 const Expr *NumTeams,
1831 const Expr *ThreadLimit,
1832 SourceLocation Loc) {}
1833
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001834llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1835 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1836 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001837 // Emit target region as a standalone region.
1838 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001839 bool &IsInParallelRegion;
1840 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001841
1842 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001843 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1844 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001845 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001846 PrevIsInParallelRegion = IsInParallelRegion;
1847 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001848 }
1849 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001850 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001851 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001852 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001853 CodeGen.setAction(Action);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001854 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1855 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001856 auto *OutlinedFun =
1857 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1858 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001859 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001860 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1861 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001862 llvm::Function *WrapperFun =
1863 createParallelDataSharingWrapper(OutlinedFun, D);
1864 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1865 }
1866
1867 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001868}
1869
Alexey Bataev2adecff2018-09-21 14:22:53 +00001870/// Get list of lastprivate variables from the teams distribute ... or
1871/// teams {distribute ...} directives.
1872static void
1873getDistributeLastprivateVars(const OMPExecutableDirective &D,
1874 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1875 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1876 "expected teams directive.");
1877 const OMPExecutableDirective *Dir = &D;
1878 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1879 if (const Stmt *S = getSingleCompoundChild(
1880 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1881 /*IgnoreCaptured=*/true))) {
1882 Dir = dyn_cast<OMPExecutableDirective>(S);
1883 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1884 Dir = nullptr;
1885 }
1886 }
1887 if (!Dir)
1888 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001889 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001890 for (const Expr *E : C->getVarRefs()) {
1891 const auto *DE = cast<DeclRefExpr>(E->IgnoreParens());
1892 Vars.push_back(cast<ValueDecl>(DE->getDecl()->getCanonicalDecl()));
1893 }
1894 }
1895}
1896
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001897llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001898 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1899 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001900 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001901
Alexey Bataev2adecff2018-09-21 14:22:53 +00001902 const RecordDecl *GlobalizedRD = nullptr;
1903 llvm::SmallVector<const ValueDecl *, 4> LastPrivates;
1904 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1905 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
1906 getDistributeLastprivateVars(D, LastPrivates);
1907 if (!LastPrivates.empty())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001908 GlobalizedRD = ::buildRecordForGlobalizedVars(
1909 CGM.getContext(), llvm::None, LastPrivates, MappedDeclsFields);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001910 }
1911
Alexey Bataevc99042b2018-03-15 18:10:54 +00001912 // Emit target region as a standalone region.
1913 class NVPTXPrePostActionTy : public PrePostActionTy {
1914 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001915 const RecordDecl *GlobalizedRD;
1916 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1917 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001918
1919 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00001920 NVPTXPrePostActionTy(
1921 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1922 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1923 &MappedDeclsFields)
1924 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1925 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001926 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001927 auto &Rt =
1928 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
1929 if (GlobalizedRD) {
1930 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1931 I->getSecond().GlobalRecord = GlobalizedRD;
1932 I->getSecond().MappedParams =
1933 llvm::make_unique<CodeGenFunction::OMPMapVars>();
1934 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1935 for (const auto &Pair : MappedDeclsFields) {
1936 assert(Pair.getFirst()->isCanonicalDecl() &&
1937 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001938 Data.insert(std::make_pair(Pair.getFirst(),
1939 MappedVarData(Pair.getSecond(),
1940 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001941 }
1942 }
1943 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001944 }
1945 void Exit(CodeGenFunction &CGF) override {
1946 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
1947 .emitGenericVarsEpilog(CGF);
1948 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00001949 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1950 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001951 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1952 D, ThreadIDVar, InnermostKind, CodeGen);
1953 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
1954 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001955 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001956 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00001957
1958 return OutlinedFun;
1959}
1960
Alexey Bataevc99042b2018-03-15 18:10:54 +00001961void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001962 SourceLocation Loc,
1963 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00001964 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
1965 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001966 return;
1967
Alexey Bataevc99042b2018-03-15 18:10:54 +00001968 CGBuilderTy &Bld = CGF.Builder;
1969
1970 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1971 if (I == FunctionGlobalizedDecls.end())
1972 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001973 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001974 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001975
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001976 // Recover pointer to this function's global record. The runtime will
1977 // handle the specifics of the allocation of the memory.
1978 // Use actual memory size of the record including the padding
1979 // for alignment purposes.
1980 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001981 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001982 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001983 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001984 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001985
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001986 llvm::PointerType *GlobalRecPtrTy =
1987 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001988 llvm::Value *GlobalRecCastAddr;
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00001989 if (WithSPMDCheck ||
1990 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001991 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1992 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1993 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1994 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
1995 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
1996 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1997 // There is no need to emit line number for unconditional branch.
1998 (void)ApplyDebugLocation::CreateEmpty(CGF);
1999 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002000 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2001 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002002 CGF.EmitBranch(ExitBB);
2003 // There is no need to emit line number for unconditional branch.
2004 (void)ApplyDebugLocation::CreateEmpty(CGF);
2005 CGF.EmitBlock(NonSPMDBB);
2006 // TODO: allow the usage of shared memory to be controlled by
2007 // the user, for now, default to global.
2008 llvm::Value *GlobalRecordSizeArg[] = {
2009 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2010 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2011 llvm::Value *GlobalRecValue =
2012 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2013 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2014 GlobalRecordSizeArg);
2015 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002016 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002017 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002018 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002019 /*NumReservedValues=*/2, "_select_stack");
2020 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2021 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2022 GlobalRecCastAddr = Phi;
2023 I->getSecond().GlobalRecordAddr = Phi;
2024 I->getSecond().IsInSPMDModeFlag = IsSPMD;
2025 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002026 // TODO: allow the usage of shared memory to be controlled by
2027 // the user, for now, default to global.
2028 llvm::Value *GlobalRecordSizeArg[] = {
2029 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2030 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2031 llvm::Value *GlobalRecValue =
2032 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2033 OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2034 GlobalRecordSizeArg);
2035 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002036 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002037 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2038 I->getSecond().IsInSPMDModeFlag = nullptr;
2039 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002040 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002041 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002042
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002043 // Emit the "global alloca" which is a GEP from the global declaration
2044 // record using the pointer returned by the runtime.
2045 for (auto &Rec : I->getSecond().LocalVarData) {
2046 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2047 llvm::Value *ParValue;
2048 if (EscapedParam) {
2049 const auto *VD = cast<VarDecl>(Rec.first);
2050 LValue ParLVal =
2051 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2052 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2053 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002054 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2055 // Emit VarAddr basing on lane-id if required.
2056 QualType VarTy;
2057 if (Rec.second.IsOnePerTeam) {
2058 Rec.second.PrivateAddr = VarAddr.getAddress();
2059 VarTy = Rec.second.FD->getType();
2060 } else {
2061 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2062 VarAddr.getAddress().getPointer(),
2063 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
2064 Rec.second.PrivateAddr =
2065 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first));
2066 VarTy =
2067 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
2068 VarAddr = CGF.MakeAddrLValue(Rec.second.PrivateAddr, VarTy,
2069 AlignmentSource::Decl);
2070 }
2071 if (WithSPMDCheck ||
2072 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
2073 assert(I->getSecond().IsInSPMDModeFlag &&
2074 "Expected unknown execution mode or required SPMD check.");
2075 Address GlobalPtr = Rec.second.PrivateAddr;
2076 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2077 Rec.second.PrivateAddr = Address(
2078 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2079 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2080 LocalAddr.getAlignment());
2081 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002082 if (EscapedParam) {
2083 const auto *VD = cast<VarDecl>(Rec.first);
2084 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2085 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2086 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002087 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002088 }
2089 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2090 // Recover pointer to this function's global record. The runtime will
2091 // handle the specifics of the allocation of the memory.
2092 // Use actual memory size of the record including the padding
2093 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002094 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002095 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2096 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2097 Size = Bld.CreateNUWAdd(
2098 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2099 llvm::Value *AlignVal =
2100 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2101 Size = Bld.CreateUDiv(Size, AlignVal);
2102 Size = Bld.CreateNUWMul(Size, AlignVal);
2103 // TODO: allow the usage of shared memory to be controlled by
2104 // the user, for now, default to global.
2105 llvm::Value *GlobalRecordSizeArg[] = {
2106 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2107 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2108 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_push_stack),
2109 GlobalRecordSizeArg);
2110 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2111 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2112 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2113 CGM.getContext().getDeclAlign(VD),
2114 AlignmentSource::Decl);
2115 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2116 Base.getAddress());
2117 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002118 }
2119 I->getSecond().MappedParams->apply(CGF);
2120}
2121
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002122void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2123 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002124 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2125 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002126 return;
2127
Alexey Bataevc99042b2018-03-15 18:10:54 +00002128 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002129 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002130 I->getSecond().MappedParams->restore(CGF);
2131 if (!CGF.HaveInsertPoint())
2132 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002133 for (llvm::Value *Addr :
2134 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2135 CGF.EmitRuntimeCall(
2136 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2137 Addr);
2138 }
2139 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002140 if (WithSPMDCheck ||
2141 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002142 CGBuilderTy &Bld = CGF.Builder;
2143 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2144 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2145 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2146 // There is no need to emit line number for unconditional branch.
2147 (void)ApplyDebugLocation::CreateEmpty(CGF);
2148 CGF.EmitBlock(NonSPMDBB);
2149 CGF.EmitRuntimeCall(
2150 createNVPTXRuntimeFunction(
2151 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2152 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2153 CGF.EmitBlock(ExitBB);
2154 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2156 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2157 I->getSecond().GlobalRecordAddr);
2158 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002159 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002160 }
2161}
2162
Carlo Bertollic6872252016-04-04 15:55:02 +00002163void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2164 const OMPExecutableDirective &D,
2165 SourceLocation Loc,
2166 llvm::Value *OutlinedFn,
2167 ArrayRef<llvm::Value *> CapturedVars) {
2168 if (!CGF.HaveInsertPoint())
2169 return;
2170
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002171 Address ZeroAddr = CGF.CreateMemTemp(
2172 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2173 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002174 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2175 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002176 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002177 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2178 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002179 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002180}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002181
2182void CGOpenMPRuntimeNVPTX::emitParallelCall(
2183 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2184 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2185 if (!CGF.HaveInsertPoint())
2186 return;
2187
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002188 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002189 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002190 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002191 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002192}
2193
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002194void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002195 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2196 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2197 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002198
2199 // Force inline this outlined function at its call site.
2200 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2201
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002202 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2203 /*DestWidth=*/32, /*Signed=*/1),
2204 ".zero.addr");
2205 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002206 // ThreadId for serialized parallels is 0.
2207 Address ThreadIDAddr = ZeroAddr;
2208 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002209 CodeGenFunction &CGF, PrePostActionTy &Action) {
2210 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002211
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002212 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2213 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2214 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2215 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2216 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2217 };
2218 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2219 PrePostActionTy &) {
2220
2221 RegionCodeGenTy RCG(CodeGen);
2222 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2223 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2224 llvm::Value *Args[] = {RTLoc, ThreadID};
2225
2226 NVPTXActionTy Action(
2227 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2228 Args,
2229 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2230 Args);
2231 RCG.setAction(Action);
2232 RCG(CGF);
2233 };
2234
2235 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2236 PrePostActionTy &Action) {
2237 CGBuilderTy &Bld = CGF.Builder;
2238 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2239 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002240 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2241
2242 // Prepare for parallel region. Indicate the outlined function.
2243 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002244 CGF.EmitRuntimeCall(
2245 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2246 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002247
2248 // Create a private scope that will globalize the arguments
2249 // passed from the outside of the target region.
2250 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2251
2252 // There's somehting to share.
2253 if (!CapturedVars.empty()) {
2254 // Prepare for parallel region. Indicate the outlined function.
2255 Address SharedArgs =
2256 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2257 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2258
2259 llvm::Value *DataSharingArgs[] = {
2260 SharedArgsPtr,
2261 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2262 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2263 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2264 DataSharingArgs);
2265
2266 // Store variable address in a list of references to pass to workers.
2267 unsigned Idx = 0;
2268 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002269 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2270 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2271 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002272 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002273 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2274 CGF.getPointerSize());
2275 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002276 if (V->getType()->isIntegerTy())
2277 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2278 else
2279 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002280 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2281 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002282 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002283 }
2284 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002285
2286 // Activate workers. This barrier is used by the master to signal
2287 // work for the workers.
2288 syncCTAThreads(CGF);
2289
2290 // OpenMP [2.5, Parallel Construct, p.49]
2291 // There is an implied barrier at the end of a parallel region. After the
2292 // end of a parallel region, only the master thread of the team resumes
2293 // execution of the enclosing task region.
2294 //
2295 // The master waits at this barrier until all workers are done.
2296 syncCTAThreads(CGF);
2297
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002298 if (!CapturedVars.empty())
2299 CGF.EmitRuntimeCall(
2300 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2301
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002302 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002303 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002304 };
2305
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002306 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2307 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002308 if (IsInParallelRegion) {
2309 SeqGen(CGF, Action);
2310 } else if (IsInTargetMasterThreadRegion) {
2311 L0ParallelGen(CGF, Action);
2312 } else {
2313 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002314 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002315 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002316 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002317 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002318 // }
2319 CGBuilderTy &Bld = CGF.Builder;
2320 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002321 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2322 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002323 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002324 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2325 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002326 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002327 // There is no need to emit line number for unconditional branch.
2328 (void)ApplyDebugLocation::CreateEmpty(CGF);
2329 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002330 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2331 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2332 llvm::Value *PL = CGF.EmitRuntimeCall(
2333 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2334 {RTLoc, ThreadID});
2335 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002336 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002337 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002338 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002339 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002340 // There is no need to emit line number for unconditional branch.
2341 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002342 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002343 L0ParallelGen(CGF, Action);
2344 CGF.EmitBranch(ExitBB);
2345 // There is no need to emit line number for unconditional branch.
2346 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002347 // Emit the continuation block for code after the if.
2348 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2349 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002350 };
2351
Alexey Bataev9ff80832018-04-16 20:16:21 +00002352 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002353 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002354 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002355 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002356 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002357 ThenRCG(CGF);
2358 }
2359}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002360
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002361void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002362 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2363 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2364 // Just call the outlined function to execute the parallel region.
2365 // OutlinedFn(&GTid, &zero, CapturedStruct);
2366 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002367 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002368
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002369 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2370 /*DestWidth=*/32, /*Signed=*/1),
2371 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002372 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002373 // ThreadId for serialized parallels is 0.
2374 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002375 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002376 &ThreadIDAddr](CodeGenFunction &CGF,
2377 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002378 Action.Enter(CGF);
2379
2380 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2381 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2382 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2383 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2384 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2385 };
2386 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2387 PrePostActionTy &) {
2388
2389 RegionCodeGenTy RCG(CodeGen);
2390 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2391 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2392 llvm::Value *Args[] = {RTLoc, ThreadID};
2393
2394 NVPTXActionTy Action(
2395 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2396 Args,
2397 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2398 Args);
2399 RCG.setAction(Action);
2400 RCG(CGF);
2401 };
2402
2403 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002404 // In the worker need to use the real thread id.
2405 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002406 RegionCodeGenTy RCG(CodeGen);
2407 RCG(CGF);
2408 } else {
2409 // If we are not in the target region, it is definitely L2 parallelism or
2410 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2411 // need to check for orphaned directives.
2412 RegionCodeGenTy RCG(SeqGen);
2413 RCG(CGF);
2414 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002415}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002416
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002417void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2418 CodeGenFunction &CGF, StringRef CriticalName,
2419 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2420 const Expr *Hint) {
2421 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2422 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2423 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2424 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2425 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2426
2427 // Fetch team-local id of the thread.
2428 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2429
2430 // Get the width of the team.
2431 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2432
2433 // Initialize the counter variable for the loop.
2434 QualType Int32Ty =
2435 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2436 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2437 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2438 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2439 /*isInit=*/true);
2440
2441 // Block checks if loop counter exceeds upper bound.
2442 CGF.EmitBlock(LoopBB);
2443 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2444 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2445 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2446
2447 // Block tests which single thread should execute region, and which threads
2448 // should go straight to synchronisation point.
2449 CGF.EmitBlock(TestBB);
2450 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2451 llvm::Value *CmpThreadToCounter =
2452 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2453 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2454
2455 // Block emits the body of the critical region.
2456 CGF.EmitBlock(BodyBB);
2457
2458 // Output the critical statement.
2459 CriticalOpGen(CGF);
2460
2461 // After the body surrounded by the critical region, the single executing
2462 // thread will jump to the synchronisation point.
2463 // Block waits for all threads in current team to finish then increments the
2464 // counter variable and returns to the loop.
2465 CGF.EmitBlock(SyncBB);
2466 getNVPTXCTABarrier(CGF);
2467
2468 llvm::Value *IncCounterVal =
2469 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2470 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2471 CGF.EmitBranch(LoopBB);
2472
2473 // Block that is reached when all threads in the team complete the region.
2474 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2475}
2476
Alexey Bataevb2575932018-01-04 20:18:55 +00002477/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002478static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2479 QualType ValTy, QualType CastTy,
2480 SourceLocation Loc) {
2481 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2482 "Cast type must sized.");
2483 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2484 "Val type must sized.");
2485 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2486 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002487 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002488 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2489 CGF.getContext().getTypeSizeInChars(CastTy))
2490 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2491 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2492 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2493 CastTy->hasSignedIntegerRepresentation());
2494 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002495 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2496 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002497 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2498 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002499}
2500
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002501/// This function creates calls to one of two shuffle functions to copy
2502/// variables between lanes in a warp.
2503static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002504 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002505 QualType ElemType,
2506 llvm::Value *Offset,
2507 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002508 CodeGenModule &CGM = CGF.CGM;
2509 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002510 CGOpenMPRuntimeNVPTX &RT =
2511 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2512
Alexey Bataeva453f362018-03-19 17:53:56 +00002513 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2514 assert(Size.getQuantity() <= 8 &&
2515 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002516
Alexey Bataeva453f362018-03-19 17:53:56 +00002517 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002518 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2519 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2520
2521 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002522 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2523 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2524 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002525 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002526 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002527
Alexey Bataev9ff80832018-04-16 20:16:21 +00002528 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2529 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002530
Alexey Bataeva453f362018-03-19 17:53:56 +00002531 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002532}
2533
Alexey Bataev12c62902018-06-22 19:10:38 +00002534static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2535 Address DestAddr, QualType ElemType,
2536 llvm::Value *Offset, SourceLocation Loc) {
2537 CGBuilderTy &Bld = CGF.Builder;
2538
2539 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2540 // Create the loop over the big sized data.
2541 // ptr = (void*)Elem;
2542 // ptrEnd = (void*) Elem + 1;
2543 // Step = 8;
2544 // while (ptr + Step < ptrEnd)
2545 // shuffle((int64_t)*ptr);
2546 // Step = 4;
2547 // while (ptr + Step < ptrEnd)
2548 // shuffle((int32_t)*ptr);
2549 // ...
2550 Address ElemPtr = DestAddr;
2551 Address Ptr = SrcAddr;
2552 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2553 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2554 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2555 if (Size < CharUnits::fromQuantity(IntSize))
2556 continue;
2557 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2558 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2559 /*Signed=*/1);
2560 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2561 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2562 ElemPtr =
2563 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2564 if (Size.getQuantity() / IntSize > 1) {
2565 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2566 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2567 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2568 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2569 CGF.EmitBlock(PreCondBB);
2570 llvm::PHINode *PhiSrc =
2571 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2572 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2573 llvm::PHINode *PhiDest =
2574 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2575 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2576 Ptr = Address(PhiSrc, Ptr.getAlignment());
2577 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2578 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2579 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2580 Ptr.getPointer(), CGF.VoidPtrTy));
2581 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2582 ThenBB, ExitBB);
2583 CGF.EmitBlock(ThenBB);
2584 llvm::Value *Res = createRuntimeShuffleFunction(
2585 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2586 IntType, Offset, Loc);
2587 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2588 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2589 ElemPtr =
2590 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2591 PhiSrc->addIncoming(Ptr.getPointer(), ThenBB);
2592 PhiDest->addIncoming(ElemPtr.getPointer(), ThenBB);
2593 CGF.EmitBranch(PreCondBB);
2594 CGF.EmitBlock(ExitBB);
2595 } else {
2596 llvm::Value *Res = createRuntimeShuffleFunction(
2597 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2598 IntType, Offset, Loc);
2599 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2600 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2601 ElemPtr =
2602 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2603 }
2604 Size = Size % IntSize;
2605 }
2606}
2607
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002608namespace {
2609enum CopyAction : unsigned {
2610 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2611 // the warp using shuffle instructions.
2612 RemoteLaneToThread,
2613 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2614 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002615 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2616 ThreadToScratchpad,
2617 // ScratchpadToThread: Copy from a scratchpad array in global memory
2618 // containing team-reduced data to a thread's stack.
2619 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002620};
2621} // namespace
2622
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002623struct CopyOptionsTy {
2624 llvm::Value *RemoteLaneOffset;
2625 llvm::Value *ScratchpadIndex;
2626 llvm::Value *ScratchpadWidth;
2627};
2628
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002629/// Emit instructions to copy a Reduce list, which contains partially
2630/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002631static void emitReductionListCopy(
2632 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2633 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2634 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002635
Alexey Bataev9ff80832018-04-16 20:16:21 +00002636 CodeGenModule &CGM = CGF.CGM;
2637 ASTContext &C = CGM.getContext();
2638 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002639
Alexey Bataev9ff80832018-04-16 20:16:21 +00002640 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2641 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2642 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002643
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002644 // Iterates, element-by-element, through the source Reduce list and
2645 // make a copy.
2646 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002647 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002648 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002649 Address SrcElementAddr = Address::invalid();
2650 Address DestElementAddr = Address::invalid();
2651 Address DestElementPtrAddr = Address::invalid();
2652 // Should we shuffle in an element from a remote lane?
2653 bool ShuffleInElement = false;
2654 // Set to true to update the pointer in the dest Reduce list to a
2655 // newly created element.
2656 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002657 // Increment the src or dest pointer to the scratchpad, for each
2658 // new element.
2659 bool IncrScratchpadSrc = false;
2660 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002661
2662 switch (Action) {
2663 case RemoteLaneToThread: {
2664 // Step 1.1: Get the address for the src element in the Reduce list.
2665 Address SrcElementPtrAddr =
2666 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002667 SrcElementAddr = CGF.EmitLoadOfPointer(
2668 SrcElementPtrAddr,
2669 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002670
2671 // Step 1.2: Create a temporary to store the element in the destination
2672 // Reduce list.
2673 DestElementPtrAddr =
2674 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2675 DestElementAddr =
2676 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2677 ShuffleInElement = true;
2678 UpdateDestListPtr = true;
2679 break;
2680 }
2681 case ThreadCopy: {
2682 // Step 1.1: Get the address for the src element in the Reduce list.
2683 Address SrcElementPtrAddr =
2684 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002685 SrcElementAddr = CGF.EmitLoadOfPointer(
2686 SrcElementPtrAddr,
2687 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002688
2689 // Step 1.2: Get the address for dest element. The destination
2690 // element has already been created on the thread's stack.
2691 DestElementPtrAddr =
2692 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002693 DestElementAddr = CGF.EmitLoadOfPointer(
2694 DestElementPtrAddr,
2695 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002696 break;
2697 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002698 case ThreadToScratchpad: {
2699 // Step 1.1: Get the address for the src element in the Reduce list.
2700 Address SrcElementPtrAddr =
2701 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002702 SrcElementAddr = CGF.EmitLoadOfPointer(
2703 SrcElementPtrAddr,
2704 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002705
2706 // Step 1.2: Get the address for dest element:
2707 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002708 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002709 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002710 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002711 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002712 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002713 ScratchPadElemAbsolutePtrVal =
2714 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002715 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2716 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002717 IncrScratchpadDest = true;
2718 break;
2719 }
2720 case ScratchpadToThread: {
2721 // Step 1.1: Get the address for the src element in the scratchpad.
2722 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002723 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002724 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002725 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002726 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002727 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002728 ScratchPadElemAbsolutePtrVal =
2729 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2730 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2731 C.getTypeAlignInChars(Private->getType()));
2732 IncrScratchpadSrc = true;
2733
2734 // Step 1.2: Create a temporary to store the element in the destination
2735 // Reduce list.
2736 DestElementPtrAddr =
2737 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2738 DestElementAddr =
2739 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2740 UpdateDestListPtr = true;
2741 break;
2742 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002743 }
2744
2745 // Regardless of src and dest of copy, we emit the load of src
2746 // element as this is required in all directions
2747 SrcElementAddr = Bld.CreateElementBitCast(
2748 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00002749 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2750 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002751
2752 // Now that all active lanes have read the element in the
2753 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00002754 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00002755 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2756 RemoteLaneOffset, Private->getExprLoc());
2757 } else {
2758 if (Private->getType()->isScalarType()) {
2759 llvm::Value *Elem =
2760 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
2761 Private->getType(), Private->getExprLoc());
2762 // Store the source element value to the dest element address.
2763 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
2764 Private->getType());
2765 } else {
2766 CGF.EmitAggregateCopy(
2767 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2768 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2769 Private->getType(), AggValueSlot::DoesNotOverlap);
2770 }
Alexey Bataeva453f362018-03-19 17:53:56 +00002771 }
Alexey Bataevb2575932018-01-04 20:18:55 +00002772
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002773 // Step 3.1: Modify reference in dest Reduce list as needed.
2774 // Modifying the reference in Reduce list to point to the newly
2775 // created element. The element is live in the current function
2776 // scope and that of functions it invokes (i.e., reduce_function).
2777 // RemoteReduceData[i] = (void*)&RemoteElem
2778 if (UpdateDestListPtr) {
2779 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2780 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2781 DestElementPtrAddr, /*Volatile=*/false,
2782 C.VoidPtrTy);
2783 }
2784
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002785 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2786 // address of the next element in scratchpad memory, unless we're currently
2787 // processing the last one. Memory alignment is also taken care of here.
2788 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2789 llvm::Value *ScratchpadBasePtr =
2790 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00002791 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2792 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002793 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00002794 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002795
2796 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00002797 ScratchpadBasePtr = Bld.CreateNUWSub(
2798 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2799 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002800 ScratchpadBasePtr,
2801 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00002802 ScratchpadBasePtr = Bld.CreateNUWAdd(
2803 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2804 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002805 ScratchpadBasePtr,
2806 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2807
2808 if (IncrScratchpadDest)
2809 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2810 else /* IncrScratchpadSrc = true */
2811 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2812 }
2813
Alexey Bataev9ff80832018-04-16 20:16:21 +00002814 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002815 }
2816}
2817
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002818/// This function emits a helper that loads data from the scratchpad array
2819/// and (optionally) reduces it with the input operand.
2820///
2821/// load_and_reduce(local, scratchpad, index, width, should_reduce)
2822/// reduce_data remote;
2823/// for elem in remote:
2824/// remote.elem = Scratchpad[elem_id][index]
2825/// if (should_reduce)
2826/// local = local @ remote
2827/// else
2828/// local = remote
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002829static llvm::Value *emitReduceScratchpadFunction(
2830 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2831 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002832 ASTContext &C = CGM.getContext();
2833 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002834
2835 // Destination of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002836 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2837 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002838 // Base address of the scratchpad array, with each element storing a
2839 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002840 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2841 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002842 // A source index into the scratchpad array.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002843 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2844 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002845 // Row width of an element in the scratchpad array, typically
2846 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002847 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2848 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002849 // If should_reduce == 1, then it's load AND reduce,
2850 // If should_reduce == 0 (or otherwise), then it only loads (+ copy).
2851 // The latter case is used for initialization.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002852 ImplicitParamDecl ShouldReduceArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2853 Int32Ty, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002854
2855 FunctionArgList Args;
2856 Args.push_back(&ReduceListArg);
2857 Args.push_back(&ScratchPadArg);
2858 Args.push_back(&IndexArg);
2859 Args.push_back(&WidthArg);
2860 Args.push_back(&ShouldReduceArg);
2861
Alexey Bataev9ff80832018-04-16 20:16:21 +00002862 const CGFunctionInfo &CGFI =
2863 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002864 auto *Fn = llvm::Function::Create(
2865 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2866 "_omp_reduction_load_and_reduce", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002867 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002868 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002869 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002870 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002871
Alexey Bataev9ff80832018-04-16 20:16:21 +00002872 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002873
2874 // Get local Reduce list pointer.
2875 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2876 Address ReduceListAddr(
2877 Bld.CreatePointerBitCastOrAddrSpaceCast(
2878 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002879 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002880 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2881 CGF.getPointerAlign());
2882
2883 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
2884 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002885 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002886
2887 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002888 llvm::Value *IndexVal = Bld.CreateIntCast(
2889 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
2890 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002891
2892 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002893 llvm::Value *WidthVal = Bld.CreateIntCast(
2894 CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false, Int32Ty, Loc),
2895 CGM.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002896
2897 Address AddrShouldReduceArg = CGF.GetAddrOfLocalVar(&ShouldReduceArg);
2898 llvm::Value *ShouldReduceVal = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00002899 AddrShouldReduceArg, /*Volatile=*/false, Int32Ty, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002900
2901 // The absolute ptr address to the base addr of the next element to copy.
2902 llvm::Value *CumulativeElemBasePtr =
2903 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
2904 Address SrcDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
2905
2906 // Create a Remote Reduce list to store the elements read from the
2907 // scratchpad array.
2908 Address RemoteReduceList =
2909 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_red_list");
2910
2911 // Assemble remote Reduce list from scratchpad array.
2912 emitReductionListCopy(ScratchpadToThread, CGF, ReductionArrayTy, Privates,
2913 SrcDataAddr, RemoteReduceList,
2914 {/*RemoteLaneOffset=*/nullptr,
2915 /*ScratchpadIndex=*/IndexVal,
2916 /*ScratchpadWidth=*/WidthVal});
2917
2918 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2919 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2920 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2921
Alexey Bataev9ff80832018-04-16 20:16:21 +00002922 llvm::Value *CondReduce = Bld.CreateIsNotNull(ShouldReduceVal);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002923 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2924
2925 CGF.EmitBlock(ThenBB);
2926 // We should reduce with the local Reduce list.
2927 // reduce_function(LocalReduceList, RemoteReduceList)
2928 llvm::Value *LocalDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2929 ReduceListAddr.getPointer(), CGF.VoidPtrTy);
2930 llvm::Value *RemoteDataPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2931 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002932 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2933 CGF, Loc, ReduceFn, {LocalDataPtr, RemoteDataPtr});
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002934 Bld.CreateBr(MergeBB);
2935
2936 CGF.EmitBlock(ElseBB);
2937 // No reduction; just copy:
2938 // Local Reduce list = Remote Reduce list.
2939 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2940 RemoteReduceList, ReduceListAddr);
2941 Bld.CreateBr(MergeBB);
2942
2943 CGF.EmitBlock(MergeBB);
2944
2945 CGF.FinishFunction();
2946 return Fn;
2947}
2948
2949/// This function emits a helper that stores reduced data from the team
2950/// master to a scratchpad array in global memory.
2951///
2952/// for elem in Reduce List:
2953/// scratchpad[elem_id][index] = elem
2954///
Benjamin Kramer674d5792017-05-26 20:08:24 +00002955static llvm::Value *emitCopyToScratchpad(CodeGenModule &CGM,
2956 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002957 QualType ReductionArrayTy,
2958 SourceLocation Loc) {
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002959
Alexey Bataev9ff80832018-04-16 20:16:21 +00002960 ASTContext &C = CGM.getContext();
2961 QualType Int32Ty = C.getIntTypeForBitwidth(32, /*Signed=*/1);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002962
2963 // Source of the copy.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002964 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2965 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002966 // Base address of the scratchpad array, with each element storing a
2967 // Reduce list per team.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002968 ImplicitParamDecl ScratchPadArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2969 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002970 // A destination index into the scratchpad array, typically the team
2971 // identifier.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002972 ImplicitParamDecl IndexArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2973 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002974 // Row width of an element in the scratchpad array, typically
2975 // the number of teams.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002976 ImplicitParamDecl WidthArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int32Ty,
2977 ImplicitParamDecl::Other);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002978
2979 FunctionArgList Args;
2980 Args.push_back(&ReduceListArg);
2981 Args.push_back(&ScratchPadArg);
2982 Args.push_back(&IndexArg);
2983 Args.push_back(&WidthArg);
2984
Alexey Bataev9ff80832018-04-16 20:16:21 +00002985 const CGFunctionInfo &CGFI =
2986 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002987 auto *Fn = llvm::Function::Create(
2988 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2989 "_omp_reduction_copy_to_scratchpad", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002990 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002991 Fn->setDoesNotRecurse();
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002992 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002993 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002994
Alexey Bataev9ff80832018-04-16 20:16:21 +00002995 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002996
2997 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2998 Address SrcDataAddr(
2999 Bld.CreatePointerBitCastOrAddrSpaceCast(
3000 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003001 C.VoidPtrTy, Loc),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003002 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3003 CGF.getPointerAlign());
3004
3005 Address AddrScratchPadArg = CGF.GetAddrOfLocalVar(&ScratchPadArg);
3006 llvm::Value *ScratchPadBase = CGF.EmitLoadOfScalar(
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003007 AddrScratchPadArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003008
3009 Address AddrIndexArg = CGF.GetAddrOfLocalVar(&IndexArg);
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00003010 llvm::Value *IndexVal = Bld.CreateIntCast(
3011 CGF.EmitLoadOfScalar(AddrIndexArg, /*Volatile=*/false, Int32Ty, Loc),
3012 CGF.SizeTy, /*isSigned=*/true);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003013
3014 Address AddrWidthArg = CGF.GetAddrOfLocalVar(&WidthArg);
3015 llvm::Value *WidthVal =
3016 Bld.CreateIntCast(CGF.EmitLoadOfScalar(AddrWidthArg, /*Volatile=*/false,
3017 Int32Ty, SourceLocation()),
3018 CGF.SizeTy, /*isSigned=*/true);
3019
3020 // The absolute ptr address to the base addr of the next element to copy.
3021 llvm::Value *CumulativeElemBasePtr =
3022 Bld.CreatePtrToInt(ScratchPadBase, CGM.SizeTy);
3023 Address DestDataAddr(CumulativeElemBasePtr, CGF.getPointerAlign());
3024
3025 emitReductionListCopy(ThreadToScratchpad, CGF, ReductionArrayTy, Privates,
3026 SrcDataAddr, DestDataAddr,
3027 {/*RemoteLaneOffset=*/nullptr,
3028 /*ScratchpadIndex=*/IndexVal,
3029 /*ScratchpadWidth=*/WidthVal});
3030
3031 CGF.FinishFunction();
3032 return Fn;
3033}
3034
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003035/// This function emits a helper that gathers Reduce lists from the first
3036/// lane of every active warp to lanes in the first warp.
3037///
3038/// void inter_warp_copy_func(void* reduce_data, num_warps)
3039/// shared smem[warp_size];
3040/// For all data entries D in reduce_data:
3041/// If (I am the first lane in each warp)
3042/// Copy my local D to smem[warp_id]
3043/// sync
3044/// if (I am the first warp)
3045/// Copy smem[thread_id] to my local D
3046/// sync
3047static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3048 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003049 QualType ReductionArrayTy,
3050 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003051 ASTContext &C = CGM.getContext();
3052 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003053
3054 // ReduceList: thread local Reduce list.
3055 // At the stage of the computation when this function is called, partially
3056 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003057 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3058 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003059 // NumWarps: number of warps active in the parallel region. This could
3060 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003061 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003062 C.getIntTypeForBitwidth(32, /* Signed */ true),
3063 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003064 FunctionArgList Args;
3065 Args.push_back(&ReduceListArg);
3066 Args.push_back(&NumWarpsArg);
3067
Alexey Bataev9ff80832018-04-16 20:16:21 +00003068 const CGFunctionInfo &CGFI =
3069 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003070 auto *Fn = llvm::Function::Create(
3071 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3072 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003073 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003074 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003075 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003076 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003077
Alexey Bataev9ff80832018-04-16 20:16:21 +00003078 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003079
3080 // This array is used as a medium to transfer, one reduce element at a time,
3081 // the data from the first lane of every warp to lanes in the first warp
3082 // in order to perform the final step of a reduction in a parallel region
3083 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3084 // for reduced latency, as well as to have a distinct copy for concurrently
3085 // executing target regions. The array is declared with common linkage so
3086 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003087 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003088 "__openmp_nvptx_data_transfer_temporary_storage";
3089 llvm::GlobalVariable *TransferMedium =
3090 M.getGlobalVariable(TransferMediumName);
3091 if (!TransferMedium) {
3092 auto *Ty = llvm::ArrayType::get(CGM.Int64Ty, WarpSize);
3093 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3094 TransferMedium = new llvm::GlobalVariable(
3095 M, Ty,
3096 /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3097 llvm::Constant::getNullValue(Ty), TransferMediumName,
3098 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3099 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003100 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003101 }
3102
3103 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003104 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003105 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003106 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003107 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003108 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109
3110 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3111 Address LocalReduceList(
3112 Bld.CreatePointerBitCastOrAddrSpaceCast(
3113 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3114 C.VoidPtrTy, SourceLocation()),
3115 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3116 CGF.getPointerAlign());
3117
3118 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003119 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003120 //
3121 // Warp master copies reduce element to transfer medium in __shared__
3122 // memory.
3123 //
3124 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3125 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3126 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3127
3128 // if (lane_id == 0)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003129 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003130 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3131 CGF.EmitBlock(ThenBB);
3132
3133 // Reduce element = LocalReduceList[i]
3134 Address ElemPtrPtrAddr =
3135 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3136 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3137 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3138 // elemptr = (type[i]*)(elemptrptr)
3139 Address ElemPtr =
3140 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3141 ElemPtr = Bld.CreateElementBitCast(
3142 ElemPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143
3144 // Get pointer to location in transfer medium.
3145 // MediumPtr = &medium[warp_id]
3146 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3147 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3148 Address MediumPtr(MediumPtrVal, C.getTypeAlignInChars(Private->getType()));
3149 // Casting to actual data type.
3150 // MediumPtr = (type[i]*)MediumPtrAddr;
3151 MediumPtr = Bld.CreateElementBitCast(
3152 MediumPtr, CGF.ConvertTypeForMem(Private->getType()));
3153
Alexey Bataev12c62902018-06-22 19:10:38 +00003154 // elem = *elemptr
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003155 //*MediumPtr = elem
Alexey Bataev12c62902018-06-22 19:10:38 +00003156 if (Private->getType()->isScalarType()) {
3157 llvm::Value *Elem = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3158 Private->getType(), Loc);
3159 // Store the source element value to the dest element address.
3160 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/false,
3161 Private->getType());
3162 } else {
3163 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3164 CGF.MakeAddrLValue(MediumPtr, Private->getType()),
3165 Private->getType(), AggValueSlot::DoesNotOverlap);
3166 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167
3168 Bld.CreateBr(MergeBB);
3169
3170 CGF.EmitBlock(ElseBB);
3171 Bld.CreateBr(MergeBB);
3172
3173 CGF.EmitBlock(MergeBB);
3174
3175 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3176 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3177 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, SourceLocation());
3178
Alexey Bataev9ff80832018-04-16 20:16:21 +00003179 llvm::Value *NumActiveThreads = Bld.CreateNSWMul(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180 NumWarpsVal, getNVPTXWarpSize(CGF), "num_active_threads");
3181 // named_barrier_sync(ParallelBarrierID, num_active_threads)
3182 syncParallelThreads(CGF, NumActiveThreads);
3183
3184 //
3185 // Warp 0 copies reduce element from transfer medium.
3186 //
3187 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3188 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3189 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3190
3191 // Up to 32 threads in warp 0 are active.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003192 llvm::Value *IsActiveThread =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003193 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3194 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3195
3196 CGF.EmitBlock(W0ThenBB);
3197
3198 // SrcMediumPtr = &medium[tid]
3199 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3200 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3201 Address SrcMediumPtr(SrcMediumPtrVal,
3202 C.getTypeAlignInChars(Private->getType()));
3203 // SrcMediumVal = *SrcMediumPtr;
3204 SrcMediumPtr = Bld.CreateElementBitCast(
3205 SrcMediumPtr, CGF.ConvertTypeForMem(Private->getType()));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003206
3207 // TargetElemPtr = (type[i]*)(SrcDataAddr[i])
3208 Address TargetElemPtrPtr =
3209 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3210 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3211 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3212 Address TargetElemPtr =
3213 Address(TargetElemPtrVal, C.getTypeAlignInChars(Private->getType()));
3214 TargetElemPtr = Bld.CreateElementBitCast(
3215 TargetElemPtr, CGF.ConvertTypeForMem(Private->getType()));
3216
3217 // *TargetElemPtr = SrcMediumVal;
Alexey Bataev12c62902018-06-22 19:10:38 +00003218 if (Private->getType()->isScalarType()) {
3219 llvm::Value *SrcMediumValue = CGF.EmitLoadOfScalar(
3220 SrcMediumPtr, /*Volatile=*/false, Private->getType(), Loc);
3221 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3222 Private->getType());
3223 } else {
3224 CGF.EmitAggregateCopy(
3225 CGF.MakeAddrLValue(SrcMediumPtr, Private->getType()),
3226 CGF.MakeAddrLValue(TargetElemPtr, Private->getType()),
3227 Private->getType(), AggValueSlot::DoesNotOverlap);
3228 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003229 Bld.CreateBr(W0MergeBB);
3230
3231 CGF.EmitBlock(W0ElseBB);
3232 Bld.CreateBr(W0MergeBB);
3233
3234 CGF.EmitBlock(W0MergeBB);
3235
3236 // While warp 0 copies values from transfer medium, all other warps must
3237 // wait.
3238 syncParallelThreads(CGF, NumActiveThreads);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003239 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003240 }
3241
3242 CGF.FinishFunction();
3243 return Fn;
3244}
3245
3246/// Emit a helper that reduces data across two OpenMP threads (lanes)
3247/// in the same warp. It uses shuffle instructions to copy over data from
3248/// a remote lane's stack. The reduction algorithm performed is specified
3249/// by the fourth parameter.
3250///
3251/// Algorithm Versions.
3252/// Full Warp Reduce (argument value 0):
3253/// This algorithm assumes that all 32 lanes are active and gathers
3254/// data from these 32 lanes, producing a single resultant value.
3255/// Contiguous Partial Warp Reduce (argument value 1):
3256/// This algorithm assumes that only a *contiguous* subset of lanes
3257/// are active. This happens for the last warp in a parallel region
3258/// when the user specified num_threads is not an integer multiple of
3259/// 32. This contiguous subset always starts with the zeroth lane.
3260/// Partial Warp Reduce (argument value 2):
3261/// This algorithm gathers data from any number of lanes at any position.
3262/// All reduced values are stored in the lowest possible lane. The set
3263/// of problems every algorithm addresses is a super set of those
3264/// addressable by algorithms with a lower version number. Overhead
3265/// increases as algorithm version increases.
3266///
3267/// Terminology
3268/// Reduce element:
3269/// Reduce element refers to the individual data field with primitive
3270/// data types to be combined and reduced across threads.
3271/// Reduce list:
3272/// Reduce list refers to a collection of local, thread-private
3273/// reduce elements.
3274/// Remote Reduce list:
3275/// Remote Reduce list refers to a collection of remote (relative to
3276/// the current thread) reduce elements.
3277///
3278/// We distinguish between three states of threads that are important to
3279/// the implementation of this function.
3280/// Alive threads:
3281/// Threads in a warp executing the SIMT instruction, as distinguished from
3282/// threads that are inactive due to divergent control flow.
3283/// Active threads:
3284/// The minimal set of threads that has to be alive upon entry to this
3285/// function. The computation is correct iff active threads are alive.
3286/// Some threads are alive but they are not active because they do not
3287/// contribute to the computation in any useful manner. Turning them off
3288/// may introduce control flow overheads without any tangible benefits.
3289/// Effective threads:
3290/// In order to comply with the argument requirements of the shuffle
3291/// function, we must keep all lanes holding data alive. But at most
3292/// half of them perform value aggregation; we refer to this half of
3293/// threads as effective. The other half is simply handing off their
3294/// data.
3295///
3296/// Procedure
3297/// Value shuffle:
3298/// In this step active threads transfer data from higher lane positions
3299/// in the warp to lower lane positions, creating Remote Reduce list.
3300/// Value aggregation:
3301/// In this step, effective threads combine their thread local Reduce list
3302/// with Remote Reduce list and store the result in the thread local
3303/// Reduce list.
3304/// Value copy:
3305/// In this step, we deal with the assumption made by algorithm 2
3306/// (i.e. contiguity assumption). When we have an odd number of lanes
3307/// active, say 2k+1, only k threads will be effective and therefore k
3308/// new values will be produced. However, the Reduce list owned by the
3309/// (2k+1)th thread is ignored in the value aggregation. Therefore
3310/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3311/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003312static llvm::Value *emitShuffleAndReduceFunction(
3313 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3314 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003315 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003316
3317 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003318 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3319 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003320 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003321 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3322 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003323 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003324 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3325 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003326 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003327 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3328 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003329 FunctionArgList Args;
3330 Args.push_back(&ReduceListArg);
3331 Args.push_back(&LaneIDArg);
3332 Args.push_back(&RemoteLaneOffsetArg);
3333 Args.push_back(&AlgoVerArg);
3334
Alexey Bataev9ff80832018-04-16 20:16:21 +00003335 const CGFunctionInfo &CGFI =
3336 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003337 auto *Fn = llvm::Function::Create(
3338 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3339 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003340 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003341 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003342 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003343 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003344
Alexey Bataev9ff80832018-04-16 20:16:21 +00003345 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003346
3347 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3348 Address LocalReduceList(
3349 Bld.CreatePointerBitCastOrAddrSpaceCast(
3350 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3351 C.VoidPtrTy, SourceLocation()),
3352 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3353 CGF.getPointerAlign());
3354
3355 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3356 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3357 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3358
3359 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3360 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3361 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3362
3363 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3364 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3365 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3366
3367 // Create a local thread-private variable to host the Reduce list
3368 // from a remote lane.
3369 Address RemoteReduceList =
3370 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3371
3372 // This loop iterates through the list of reduce elements and copies,
3373 // element by element, from a remote lane in the warp to RemoteReduceList,
3374 // hosted on the thread's stack.
3375 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3376 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003377 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3378 /*ScratchpadIndex=*/nullptr,
3379 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003380
3381 // The actions to be performed on the Remote Reduce list is dependent
3382 // on the algorithm version.
3383 //
3384 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3385 // LaneId % 2 == 0 && Offset > 0):
3386 // do the reduction value aggregation
3387 //
3388 // The thread local variable Reduce list is mutated in place to host the
3389 // reduced data, which is the aggregated value produced from local and
3390 // remote lanes.
3391 //
3392 // Note that AlgoVer is expected to be a constant integer known at compile
3393 // time.
3394 // When AlgoVer==0, the first conjunction evaluates to true, making
3395 // the entire predicate true during compile time.
3396 // When AlgoVer==1, the second conjunction has only the second part to be
3397 // evaluated during runtime. Other conjunctions evaluates to false
3398 // during compile time.
3399 // When AlgoVer==2, the third conjunction has only the second part to be
3400 // evaluated during runtime. Other conjunctions evaluates to false
3401 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003402 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003403
Alexey Bataev9ff80832018-04-16 20:16:21 +00003404 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3405 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003406 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3407
Alexey Bataev9ff80832018-04-16 20:16:21 +00003408 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3409 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3410 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003411 CondAlgo2 = Bld.CreateAnd(
3412 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3413
Alexey Bataev9ff80832018-04-16 20:16:21 +00003414 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003415 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3416
3417 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3418 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3419 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3420 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3421
3422 CGF.EmitBlock(ThenBB);
3423 // reduce_function(LocalReduceList, RemoteReduceList)
3424 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3425 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3426 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3427 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003428 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3429 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430 Bld.CreateBr(MergeBB);
3431
3432 CGF.EmitBlock(ElseBB);
3433 Bld.CreateBr(MergeBB);
3434
3435 CGF.EmitBlock(MergeBB);
3436
3437 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3438 // Reduce list.
3439 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003440 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3442
3443 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3444 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3445 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3446 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3447
3448 CGF.EmitBlock(CpyThenBB);
3449 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3450 RemoteReduceList, LocalReduceList);
3451 Bld.CreateBr(CpyMergeBB);
3452
3453 CGF.EmitBlock(CpyElseBB);
3454 Bld.CreateBr(CpyMergeBB);
3455
3456 CGF.EmitBlock(CpyMergeBB);
3457
3458 CGF.FinishFunction();
3459 return Fn;
3460}
3461
3462///
3463/// Design of OpenMP reductions on the GPU
3464///
3465/// Consider a typical OpenMP program with one or more reduction
3466/// clauses:
3467///
3468/// float foo;
3469/// double bar;
3470/// #pragma omp target teams distribute parallel for \
3471/// reduction(+:foo) reduction(*:bar)
3472/// for (int i = 0; i < N; i++) {
3473/// foo += A[i]; bar *= B[i];
3474/// }
3475///
3476/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3477/// all teams. In our OpenMP implementation on the NVPTX device an
3478/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3479/// within a team are mapped to CUDA threads within a threadblock.
3480/// Our goal is to efficiently aggregate values across all OpenMP
3481/// threads such that:
3482///
3483/// - the compiler and runtime are logically concise, and
3484/// - the reduction is performed efficiently in a hierarchical
3485/// manner as follows: within OpenMP threads in the same warp,
3486/// across warps in a threadblock, and finally across teams on
3487/// the NVPTX device.
3488///
3489/// Introduction to Decoupling
3490///
3491/// We would like to decouple the compiler and the runtime so that the
3492/// latter is ignorant of the reduction variables (number, data types)
3493/// and the reduction operators. This allows a simpler interface
3494/// and implementation while still attaining good performance.
3495///
3496/// Pseudocode for the aforementioned OpenMP program generated by the
3497/// compiler is as follows:
3498///
3499/// 1. Create private copies of reduction variables on each OpenMP
3500/// thread: 'foo_private', 'bar_private'
3501/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3502/// to it and writes the result in 'foo_private' and 'bar_private'
3503/// respectively.
3504/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3505/// and store the result on the team master:
3506///
3507/// __kmpc_nvptx_parallel_reduce_nowait(...,
3508/// reduceData, shuffleReduceFn, interWarpCpyFn)
3509///
3510/// where:
3511/// struct ReduceData {
3512/// double *foo;
3513/// double *bar;
3514/// } reduceData
3515/// reduceData.foo = &foo_private
3516/// reduceData.bar = &bar_private
3517///
3518/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3519/// auxiliary functions generated by the compiler that operate on
3520/// variables of type 'ReduceData'. They aid the runtime perform
3521/// algorithmic steps in a data agnostic manner.
3522///
3523/// 'shuffleReduceFn' is a pointer to a function that reduces data
3524/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3525/// same warp. It takes the following arguments as input:
3526///
3527/// a. variable of type 'ReduceData' on the calling lane,
3528/// b. its lane_id,
3529/// c. an offset relative to the current lane_id to generate a
3530/// remote_lane_id. The remote lane contains the second
3531/// variable of type 'ReduceData' that is to be reduced.
3532/// d. an algorithm version parameter determining which reduction
3533/// algorithm to use.
3534///
3535/// 'shuffleReduceFn' retrieves data from the remote lane using
3536/// efficient GPU shuffle intrinsics and reduces, using the
3537/// algorithm specified by the 4th parameter, the two operands
3538/// element-wise. The result is written to the first operand.
3539///
3540/// Different reduction algorithms are implemented in different
3541/// runtime functions, all calling 'shuffleReduceFn' to perform
3542/// the essential reduction step. Therefore, based on the 4th
3543/// parameter, this function behaves slightly differently to
3544/// cooperate with the runtime to ensure correctness under
3545/// different circumstances.
3546///
3547/// 'InterWarpCpyFn' is a pointer to a function that transfers
3548/// reduced variables across warps. It tunnels, through CUDA
3549/// shared memory, the thread-private data of type 'ReduceData'
3550/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003551/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3552/// The last team writes the global reduced value to memory.
3553///
3554/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3555/// reduceData, shuffleReduceFn, interWarpCpyFn,
3556/// scratchpadCopyFn, loadAndReduceFn)
3557///
3558/// 'scratchpadCopyFn' is a helper that stores reduced
3559/// data from the team master to a scratchpad array in
3560/// global memory.
3561///
3562/// 'loadAndReduceFn' is a helper that loads data from
3563/// the scratchpad array and reduces it with the input
3564/// operand.
3565///
3566/// These compiler generated functions hide address
3567/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003568/// 5. if ret == 1:
3569/// The team master of the last team stores the reduced
3570/// result to the globals in memory.
3571/// foo += reduceData.foo; bar *= reduceData.bar
3572///
3573///
3574/// Warp Reduction Algorithms
3575///
3576/// On the warp level, we have three algorithms implemented in the
3577/// OpenMP runtime depending on the number of active lanes:
3578///
3579/// Full Warp Reduction
3580///
3581/// The reduce algorithm within a warp where all lanes are active
3582/// is implemented in the runtime as follows:
3583///
3584/// full_warp_reduce(void *reduce_data,
3585/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3586/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3587/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3588/// }
3589///
3590/// The algorithm completes in log(2, WARPSIZE) steps.
3591///
3592/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3593/// not used therefore we save instructions by not retrieving lane_id
3594/// from the corresponding special registers. The 4th parameter, which
3595/// represents the version of the algorithm being used, is set to 0 to
3596/// signify full warp reduction.
3597///
3598/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3599///
3600/// #reduce_elem refers to an element in the local lane's data structure
3601/// #remote_elem is retrieved from a remote lane
3602/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3603/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3604///
3605/// Contiguous Partial Warp Reduction
3606///
3607/// This reduce algorithm is used within a warp where only the first
3608/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3609/// number of OpenMP threads in a parallel region is not a multiple of
3610/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3611///
3612/// void
3613/// contiguous_partial_reduce(void *reduce_data,
3614/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3615/// int size, int lane_id) {
3616/// int curr_size;
3617/// int offset;
3618/// curr_size = size;
3619/// mask = curr_size/2;
3620/// while (offset>0) {
3621/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3622/// curr_size = (curr_size+1)/2;
3623/// offset = curr_size/2;
3624/// }
3625/// }
3626///
3627/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3628///
3629/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3630/// if (lane_id < offset)
3631/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3632/// else
3633/// reduce_elem = remote_elem
3634///
3635/// This algorithm assumes that the data to be reduced are located in a
3636/// contiguous subset of lanes starting from the first. When there is
3637/// an odd number of active lanes, the data in the last lane is not
3638/// aggregated with any other lane's dat but is instead copied over.
3639///
3640/// Dispersed Partial Warp Reduction
3641///
3642/// This algorithm is used within a warp when any discontiguous subset of
3643/// lanes are active. It is used to implement the reduction operation
3644/// across lanes in an OpenMP simd region or in a nested parallel region.
3645///
3646/// void
3647/// dispersed_partial_reduce(void *reduce_data,
3648/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3649/// int size, remote_id;
3650/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3651/// do {
3652/// remote_id = next_active_lane_id_right_after_me();
3653/// # the above function returns 0 of no active lane
3654/// # is present right after the current lane.
3655/// size = number_of_active_lanes_in_this_warp();
3656/// logical_lane_id /= 2;
3657/// ShuffleReduceFn(reduce_data, logical_lane_id,
3658/// remote_id-1-threadIdx.x, 2);
3659/// } while (logical_lane_id % 2 == 0 && size > 1);
3660/// }
3661///
3662/// There is no assumption made about the initial state of the reduction.
3663/// Any number of lanes (>=1) could be active at any position. The reduction
3664/// result is returned in the first active lane.
3665///
3666/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3667///
3668/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3669/// if (lane_id % 2 == 0 && offset > 0)
3670/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3671/// else
3672/// reduce_elem = remote_elem
3673///
3674///
3675/// Intra-Team Reduction
3676///
3677/// This function, as implemented in the runtime call
3678/// '__kmpc_nvptx_parallel_reduce_nowait', aggregates data across OpenMP
3679/// threads in a team. It first reduces within a warp using the
3680/// aforementioned algorithms. We then proceed to gather all such
3681/// reduced values at the first warp.
3682///
3683/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3684/// data from each of the "warp master" (zeroth lane of each warp, where
3685/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3686/// a mathematical sense) the problem of reduction across warp masters in
3687/// a block to the problem of warp reduction.
3688///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003689///
3690/// Inter-Team Reduction
3691///
3692/// Once a team has reduced its data to a single value, it is stored in
3693/// a global scratchpad array. Since each team has a distinct slot, this
3694/// can be done without locking.
3695///
3696/// The last team to write to the scratchpad array proceeds to reduce the
3697/// scratchpad array. One or more workers in the last team use the helper
3698/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3699/// the k'th worker reduces every k'th element.
3700///
3701/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait' to
3702/// reduce across workers and compute a globally reduced value.
3703///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003704void CGOpenMPRuntimeNVPTX::emitReduction(
3705 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3706 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3707 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3708 if (!CGF.HaveInsertPoint())
3709 return;
3710
3711 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003712 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003713 bool SimdReduction = isOpenMPSimdDirective(Options.ReductionKind);
3714 assert((TeamsReduction || ParallelReduction || SimdReduction) &&
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003715 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003716
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003717 if (Options.SimpleReduction) {
3718 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3719 ReductionOps, Options);
3720 return;
3721 }
3722
Alexey Bataev9ff80832018-04-16 20:16:21 +00003723 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003724
3725 // 1. Build a list of reduction variables.
3726 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3727 auto Size = RHSExprs.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003728 for (const Expr *E : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003729 if (E->getType()->isVariablyModifiedType())
3730 // Reserve place for array size.
3731 ++Size;
3732 }
3733 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3734 QualType ReductionArrayTy =
3735 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3736 /*IndexTypeQuals=*/0);
3737 Address ReductionList =
3738 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3739 auto IPriv = Privates.begin();
3740 unsigned Idx = 0;
3741 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3742 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3743 CGF.getPointerSize());
3744 CGF.Builder.CreateStore(
3745 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3746 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3747 Elem);
3748 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3749 // Store array size.
3750 ++Idx;
3751 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3752 CGF.getPointerSize());
3753 llvm::Value *Size = CGF.Builder.CreateIntCast(
3754 CGF.getVLASize(
3755 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00003756 .NumElts,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003757 CGF.SizeTy, /*isSigned=*/false);
3758 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3759 Elem);
3760 }
3761 }
3762
3763 // 2. Emit reduce_func().
Alexey Bataev9ff80832018-04-16 20:16:21 +00003764 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003765 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3766 Privates, LHSExprs, RHSExprs, ReductionOps);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003767
3768 // 4. Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3769 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003770 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3771 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3772 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003773 ReductionList.getPointer(), CGF.VoidPtrTy);
3774
Alexey Bataev9ff80832018-04-16 20:16:21 +00003775 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003776 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003777 llvm::Value *InterWarpCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003778 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003779
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003780 llvm::Value *Args[] = {ThreadId,
3781 CGF.Builder.getInt32(RHSExprs.size()),
3782 ReductionArrayTySize,
3783 RL,
3784 ShuffleAndReduceFn,
3785 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003786
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003787 llvm::Value *Res = nullptr;
3788 if (ParallelReduction)
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003789 Res = CGF.EmitRuntimeCall(
3790 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_reduce_nowait),
3791 Args);
Alexey Bataevfac26cf2018-05-02 20:03:27 +00003792 else if (SimdReduction)
3793 Res = CGF.EmitRuntimeCall(
3794 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_simd_reduce_nowait),
3795 Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003796
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003797 if (TeamsReduction) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003798 llvm::Value *ScratchPadCopyFn =
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003799 emitCopyToScratchpad(CGM, Privates, ReductionArrayTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003800 llvm::Value *LoadAndReduceFn = emitReduceScratchpadFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003801 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003802
3803 llvm::Value *Args[] = {ThreadId,
3804 CGF.Builder.getInt32(RHSExprs.size()),
3805 ReductionArrayTySize,
3806 RL,
3807 ShuffleAndReduceFn,
3808 InterWarpCopyFn,
3809 ScratchPadCopyFn,
3810 LoadAndReduceFn};
3811 Res = CGF.EmitRuntimeCall(
3812 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_teams_reduce_nowait),
3813 Args);
3814 }
3815
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003816 // 5. Build switch(res)
Alexey Bataev9ff80832018-04-16 20:16:21 +00003817 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3818 llvm::SwitchInst *SwInst =
3819 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003820
3821 // 6. Build case 1: where we have reduced values in the master
3822 // thread in each team.
3823 // __kmpc_end_reduce{_nowait}(<gtid>);
3824 // break;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003825 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003826 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3827 CGF.EmitBlock(Case1BB);
3828
3829 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3830 llvm::Value *EndArgs[] = {ThreadId};
Alexey Bataev9ff80832018-04-16 20:16:21 +00003831 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003832 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3833 auto IPriv = Privates.begin();
3834 auto ILHS = LHSExprs.begin();
3835 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003836 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003837 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3838 cast<DeclRefExpr>(*IRHS));
3839 ++IPriv;
3840 ++ILHS;
3841 ++IRHS;
3842 }
3843 };
3844 RegionCodeGenTy RCG(CodeGen);
3845 NVPTXActionTy Action(
3846 nullptr, llvm::None,
3847 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3848 EndArgs);
3849 RCG.setAction(Action);
3850 RCG(CGF);
3851 CGF.EmitBranch(DefaultBB);
3852 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
3853}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003854
3855const VarDecl *
3856CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3857 const VarDecl *NativeParam) const {
3858 if (!NativeParam->getType()->isReferenceType())
3859 return NativeParam;
3860 QualType ArgType = NativeParam->getType();
3861 QualifierCollector QC;
3862 const Type *NonQualTy = QC.strip(ArgType);
3863 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3864 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3865 if (Attr->getCaptureKind() == OMPC_map) {
3866 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3867 LangAS::opencl_global);
3868 }
3869 }
3870 ArgType = CGM.getContext().getPointerType(PointeeTy);
3871 QC.addRestrict();
3872 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003873 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003874 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003875 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003876 return ImplicitParamDecl::Create(
3877 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3878 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003879 return ParmVarDecl::Create(
3880 CGM.getContext(),
3881 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003882 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00003883 NativeParam->getIdentifier(), ArgType,
3884 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003885}
3886
3887Address
3888CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
3889 const VarDecl *NativeParam,
3890 const VarDecl *TargetParam) const {
3891 assert(NativeParam != TargetParam &&
3892 NativeParam->getType()->isReferenceType() &&
3893 "Native arg must not be the same as target arg.");
3894 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3895 QualType NativeParamType = NativeParam->getType();
3896 QualifierCollector QC;
3897 const Type *NonQualTy = QC.strip(NativeParamType);
3898 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3899 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00003900 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003901 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003902 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003903 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003904 // First cast to generic.
3905 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3906 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3907 /*AddrSpace=*/0));
3908 // Cast from generic to native address space.
3909 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3910 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3911 NativePointeeAddrSpace));
3912 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3913 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00003914 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003915 return NativeParamAddr;
3916}
3917
3918void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00003919 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003920 ArrayRef<llvm::Value *> Args) const {
3921 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003922 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003923 auto *FnType =
3924 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
3925 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00003926 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3927 TargetArgs.append(std::next(Args.begin(), I), Args.end());
3928 break;
3929 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003930 llvm::Type *TargetType = FnType->getParamType(I);
3931 llvm::Value *NativeArg = Args[I];
3932 if (!TargetType->isPointerTy()) {
3933 TargetArgs.emplace_back(NativeArg);
3934 continue;
3935 }
3936 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00003937 NativeArg,
3938 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003939 TargetArgs.emplace_back(
3940 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3941 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00003942 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003943}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003944
3945/// Emit function which wraps the outline parallel region
3946/// and controls the arguments which are passed to this function.
3947/// The wrapper ensures that the outlined function is called
3948/// with the correct arguments when data is shared.
3949llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
3950 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3951 ASTContext &Ctx = CGM.getContext();
3952 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3953
3954 // Create a function that takes as argument the source thread.
3955 FunctionArgList WrapperArgs;
3956 QualType Int16QTy =
3957 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3958 QualType Int32QTy =
3959 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003960 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003961 /*Id=*/nullptr, Int16QTy,
3962 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003963 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003964 /*Id=*/nullptr, Int32QTy,
3965 ImplicitParamDecl::Other);
3966 WrapperArgs.emplace_back(&ParallelLevelArg);
3967 WrapperArgs.emplace_back(&WrapperArg);
3968
Alexey Bataev9ff80832018-04-16 20:16:21 +00003969 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003970 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3971
3972 auto *Fn = llvm::Function::Create(
3973 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00003974 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00003975 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003976 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003977 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003978
3979 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3980 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003981 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003982
3983 const auto *RD = CS.getCapturedRecordDecl();
3984 auto CurField = RD->field_begin();
3985
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003986 Address ZeroAddr = CGF.CreateMemTemp(
3987 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3988 /*Name*/ ".zero.addr");
3989 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003990 // Get the array of arguments.
3991 SmallVector<llvm::Value *, 8> Args;
3992
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00003993 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3994 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00003995
3996 CGBuilderTy &Bld = CGF.Builder;
3997 auto CI = CS.capture_begin();
3998
3999 // Use global memory for data sharing.
4000 // Handle passing of global args to workers.
4001 Address GlobalArgs =
4002 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4003 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4004 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4005 CGF.EmitRuntimeCall(
4006 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4007 DataSharingArgs);
4008
4009 // Retrieve the shared variables from the list of references returned
4010 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004011 Address SharedArgListAddress = Address::invalid();
4012 if (CS.capture_size() > 0 ||
4013 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4014 SharedArgListAddress = CGF.EmitLoadOfPointer(
4015 GlobalArgs, CGF.getContext()
4016 .getPointerType(CGF.getContext().getPointerType(
4017 CGF.getContext().VoidPtrTy))
4018 .castAs<PointerType>());
4019 }
4020 unsigned Idx = 0;
4021 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4022 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4023 CGF.getPointerSize());
4024 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4025 Src, CGF.SizeTy->getPointerTo());
4026 llvm::Value *LB = CGF.EmitLoadOfScalar(
4027 TypedAddress,
4028 /*Volatile=*/false,
4029 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4030 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4031 Args.emplace_back(LB);
4032 ++Idx;
4033 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4034 CGF.getPointerSize());
4035 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4036 Src, CGF.SizeTy->getPointerTo());
4037 llvm::Value *UB = CGF.EmitLoadOfScalar(
4038 TypedAddress,
4039 /*Volatile=*/false,
4040 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4041 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4042 Args.emplace_back(UB);
4043 ++Idx;
4044 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004045 if (CS.capture_size() > 0) {
4046 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004047 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4048 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004049 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4050 CGF.getPointerSize());
4051 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004052 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4053 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4054 /*Volatile=*/false,
4055 CGFContext.getPointerType(ElemTy),
4056 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004057 if (CI->capturesVariableByCopy() &&
4058 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004059 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4060 CI->getLocation());
4061 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004062 Args.emplace_back(Arg);
4063 }
4064 }
4065
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004066 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004067 CGF.FinishFunction();
4068 return Fn;
4069}
4070
4071void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4072 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004073 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4074 return;
4075
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004076 assert(D && "Expected function or captured|block decl.");
4077 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4078 "Function is registered already.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004079 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004080 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004081 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4082 Body = FD->getBody();
4083 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4084 Body = BD->getBody();
4085 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4086 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004087 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004088 if (NeedToDelayGlobalization &&
4089 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4090 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004091 }
4092 if (!Body)
4093 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004094 CheckVarsEscapingDeclContext VarChecker(CGF);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004095 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004096 const RecordDecl *GlobalizedVarsRecord =
4097 VarChecker.getGlobalizedRecord(IsInTargetMasterThreadRegion);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004098 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4099 VarChecker.getEscapedVariableLengthDecls();
4100 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004101 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004102 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4103 I->getSecond().MappedParams =
4104 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4105 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4106 I->getSecond().EscapedParameters.insert(
4107 VarChecker.getEscapedParameters().begin(),
4108 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004109 I->getSecond().EscapedVariableLengthDecls.append(
4110 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004111 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004112 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004113 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004114 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004115 Data.insert(
4116 std::make_pair(VD, MappedVarData(FD, IsInTargetMasterThreadRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004117 }
4118 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004119 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004120 struct GlobalizationScope final : EHScopeStack::Cleanup {
4121 GlobalizationScope() = default;
4122
4123 void Emit(CodeGenFunction &CGF, Flags flags) override {
4124 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004125 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004126 }
4127 };
4128 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004129 }
4130}
4131
4132Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4133 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004134 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4135 return Address::invalid();
4136
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004137 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004138 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4139 if (I == FunctionGlobalizedDecls.end())
4140 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004141 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004142 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004143 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004144 if (VD->hasAttrs()) {
4145 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4146 E(VD->attr_end());
4147 IT != E; ++IT) {
4148 auto VDI = I->getSecond().LocalVarData.find(
4149 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4150 ->getCanonicalDecl());
4151 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004152 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004153 }
4154 }
4155 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004156}
4157
4158void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004159 FunctionGlobalizedDecls.erase(CGF.CurFn);
4160 CGOpenMPRuntime::functionFinished(CGF);
4161}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004162
4163void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4164 CodeGenFunction &CGF, const OMPLoopDirective &S,
4165 OpenMPDistScheduleClauseKind &ScheduleKind,
4166 llvm::Value *&Chunk) const {
4167 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4168 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4169 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4170 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4171 S.getIterationVariable()->getType(), S.getBeginLoc());
4172 }
4173}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004174
4175void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4176 CodeGenFunction &CGF, const OMPLoopDirective &S,
4177 OpenMPScheduleClauseKind &ScheduleKind,
4178 llvm::Value *&Chunk) const {
4179 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4180 ScheduleKind = OMPC_SCHEDULE_static;
4181 Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
4182 S.getIterationVariable()->getType()), 1);
4183 }
4184}