clang 24.0.0git
CGOpenMPRuntimeGPU.cpp
Go to the documentation of this file.
1//===---- CGOpenMPRuntimeGPU.cpp - Interface to OpenMP GPU Runtimes ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a generalized class for OpenMP runtime code generation
10// specialized by GPU targets NVPTX, AMDGCN and SPIR-V.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeGPU.h"
15#include "CGDebugInfo.h"
16#include "CodeGenFunction.h"
17#include "TargetInfo.h"
18#include "clang/AST/Attr.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/Frontend/OpenMP/OMPDeviceConstants.h"
25#include "llvm/Frontend/OpenMP/OMPGridValues.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/TargetParser/NVPTXTargetParser.h"
29
30using namespace clang;
31using namespace CodeGen;
32using namespace llvm::omp;
33
34namespace {
35/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
36class NVPTXActionTy final : public PrePostActionTy {
37 llvm::FunctionCallee EnterCallee = nullptr;
38 ArrayRef<llvm::Value *> EnterArgs;
39 llvm::FunctionCallee ExitCallee = nullptr;
40 ArrayRef<llvm::Value *> ExitArgs;
41 bool Conditional = false;
42 llvm::BasicBlock *ContBlock = nullptr;
43
44public:
45 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
46 ArrayRef<llvm::Value *> EnterArgs,
47 llvm::FunctionCallee ExitCallee,
48 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
49 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
50 ExitArgs(ExitArgs), Conditional(Conditional) {}
51 void Enter(CodeGenFunction &CGF) override {
52 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
53 if (Conditional) {
54 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
55 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
56 ContBlock = CGF.createBasicBlock("omp_if.end");
57 // Generate the branch (If-stmt)
58 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
59 CGF.EmitBlock(ThenBlock);
60 }
61 }
62 void Done(CodeGenFunction &CGF) {
63 // Emit the rest of blocks/branches
64 CGF.EmitBranch(ContBlock);
65 CGF.EmitBlock(ContBlock, true);
66 }
67 void Exit(CodeGenFunction &CGF) override {
68 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
69 }
70};
71
72/// A class to track the execution mode when codegening directives within
73/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
74/// to the target region and used by containing directives such as 'parallel'
75/// to emit optimized code.
76class ExecutionRuntimeModesRAII {
77private:
81
82public:
83 ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode,
85 : ExecMode(ExecMode) {
86 SavedExecMode = ExecMode;
87 ExecMode = EntryMode;
88 }
89 ~ExecutionRuntimeModesRAII() { ExecMode = SavedExecMode; }
90};
91
92static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
93 RefExpr = RefExpr->IgnoreParens();
94 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
95 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
96 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
97 Base = TempASE->getBase()->IgnoreParenImpCasts();
98 RefExpr = Base;
99 } else if (auto *OASE = dyn_cast<ArraySectionExpr>(RefExpr)) {
100 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
101 while (const auto *TempOASE = dyn_cast<ArraySectionExpr>(Base))
102 Base = TempOASE->getBase()->IgnoreParenImpCasts();
103 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
104 Base = TempASE->getBase()->IgnoreParenImpCasts();
105 RefExpr = Base;
106 }
107 RefExpr = RefExpr->IgnoreParenImpCasts();
108 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
109 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
110 const auto *ME = cast<MemberExpr>(RefExpr);
111 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
112}
113
114static RecordDecl *buildRecordForGlobalizedVars(
116 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
117 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
118 &MappedDeclsFields,
119 int BufSize) {
120 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
121 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
122 return nullptr;
123 SmallVector<VarsDataTy, 4> GlobalizedVars;
124 for (const ValueDecl *D : EscapedDecls)
125 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
126 for (const ValueDecl *D : EscapedDeclsForTeams)
127 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
128
129 // Build struct _globalized_locals_ty {
130 // /* globalized vars */[WarSize] align (decl_align)
131 // /* globalized vars */ for EscapedDeclsForTeams
132 // };
133 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
134 GlobalizedRD->startDefinition();
135 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(llvm::from_range,
136 EscapedDeclsForTeams);
137 for (const auto &Pair : GlobalizedVars) {
138 const ValueDecl *VD = Pair.second;
139 QualType Type = VD->getType();
141 Type = C.getPointerType(Type.getNonReferenceType());
142 else
143 Type = Type.getNonReferenceType();
144 SourceLocation Loc = VD->getLocation();
145 FieldDecl *Field;
146 if (SingleEscaped.count(VD)) {
147 Field = FieldDecl::Create(
148 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
149 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
150 /*BW=*/nullptr, /*Mutable=*/false,
151 /*InitStyle=*/ICIS_NoInit);
152 Field->setAccess(AS_public);
153 if (VD->hasAttrs()) {
154 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
155 E(VD->getAttrs().end());
156 I != E; ++I)
157 Field->addAttr(*I);
158 }
159 } else {
160 if (BufSize > 1) {
161 llvm::APInt ArraySize(32, BufSize);
162 Type = C.getConstantArrayType(Type, ArraySize, nullptr,
164 }
165 Field = FieldDecl::Create(
166 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
167 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
168 /*BW=*/nullptr, /*Mutable=*/false,
169 /*InitStyle=*/ICIS_NoInit);
170 Field->setAccess(AS_public);
171 llvm::APInt Align(32, Pair.first.getQuantity());
172 Field->addAttr(AlignedAttr::CreateImplicit(
173 C, /*IsAlignmentExpr=*/true,
175 C.getIntTypeForBitwidth(32, /*Signed=*/0),
177 {}, AlignedAttr::GNU_aligned));
178 }
179 GlobalizedRD->addDecl(Field);
180 MappedDeclsFields.try_emplace(VD, Field);
181 }
182 GlobalizedRD->completeDefinition();
183 return GlobalizedRD;
184}
185
186/// Get the list of variables that can escape their declaration context.
187class CheckVarsEscapingDeclContext final
188 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
189 CodeGenFunction &CGF;
190 llvm::SetVector<const ValueDecl *> EscapedDecls;
191 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
192 llvm::SetVector<const ValueDecl *> DelayedVariableLengthDecls;
193 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
194 RecordDecl *GlobalizedRD = nullptr;
195 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
196 bool AllEscaped = false;
197 bool IsForCombinedParallelRegion = false;
198
199 void markAsEscaped(const ValueDecl *VD) {
200 // Do not globalize declare target variables.
201 if (!isa<VarDecl>(VD) ||
202 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
203 return;
205 // Use user-specified allocation.
206 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
207 return;
208 // Variables captured by value must be globalized.
209 bool IsCaptured = false;
210 if (auto *CSI = CGF.CapturedStmtInfo) {
211 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
212 // Check if need to capture the variable that was already captured by
213 // value in the outer region.
214 IsCaptured = true;
215 if (!IsForCombinedParallelRegion) {
216 if (!FD->hasAttrs())
217 return;
218 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
219 if (!Attr)
220 return;
221 if (((Attr->getCaptureKind() != OMPC_map) &&
222 !isOpenMPPrivate(Attr->getCaptureKind())) ||
223 ((Attr->getCaptureKind() == OMPC_map) &&
224 !FD->getType()->isAnyPointerType()))
225 return;
226 }
227 if (!FD->getType()->isReferenceType()) {
228 assert(!VD->getType()->isVariablyModifiedType() &&
229 "Parameter captured by value with variably modified type");
230 EscapedParameters.insert(VD);
231 } else if (!IsForCombinedParallelRegion) {
232 return;
233 }
234 }
235 }
236 if ((!CGF.CapturedStmtInfo ||
237 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
238 VD->getType()->isReferenceType())
239 // Do not globalize variables with reference type.
240 return;
241 if (VD->getType()->isVariablyModifiedType()) {
242 // If not captured at the target region level then mark the escaped
243 // variable as delayed.
244 if (IsCaptured)
245 EscapedVariableLengthDecls.insert(VD);
246 else
247 DelayedVariableLengthDecls.insert(VD);
248 } else
249 EscapedDecls.insert(VD);
250 }
251
252 void VisitValueDecl(const ValueDecl *VD) {
253 if (VD->getType()->isLValueReferenceType())
254 markAsEscaped(VD);
255 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
256 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
257 const bool SavedAllEscaped = AllEscaped;
258 AllEscaped = VD->getType()->isLValueReferenceType();
259 Visit(VarD->getInit());
260 AllEscaped = SavedAllEscaped;
261 }
262 }
263 }
264 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
265 ArrayRef<OMPClause *> Clauses,
266 bool IsCombinedParallelRegion) {
267 if (!S)
268 return;
269 for (const CapturedStmt::Capture &C : S->captures()) {
270 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
271 const ValueDecl *VD = C.getCapturedVar();
272 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
273 if (IsCombinedParallelRegion) {
274 // Check if the variable is privatized in the combined construct and
275 // those private copies must be shared in the inner parallel
276 // directive.
277 IsForCombinedParallelRegion = false;
278 for (const OMPClause *C : Clauses) {
279 if (!isOpenMPPrivate(C->getClauseKind()) ||
280 C->getClauseKind() == OMPC_reduction ||
281 C->getClauseKind() == OMPC_linear ||
282 C->getClauseKind() == OMPC_private)
283 continue;
284 ArrayRef<const Expr *> Vars;
285 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
286 Vars = PC->getVarRefs();
287 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
288 Vars = PC->getVarRefs();
289 else
290 llvm_unreachable("Unexpected clause.");
291 for (const auto *E : Vars) {
292 const Decl *D =
293 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
294 if (D == VD->getCanonicalDecl()) {
295 IsForCombinedParallelRegion = true;
296 break;
297 }
298 }
299 if (IsForCombinedParallelRegion)
300 break;
301 }
302 }
303 markAsEscaped(VD);
305 VisitValueDecl(VD);
306 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
307 }
308 }
309 }
310
311 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
312 assert(!GlobalizedRD &&
313 "Record for globalized variables is built already.");
314 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
315 unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
316 if (IsInTTDRegion)
317 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
318 else
319 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
320 GlobalizedRD = ::buildRecordForGlobalizedVars(
321 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
322 MappedDeclsFields, WarpSize);
323 }
324
325public:
326 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
327 ArrayRef<const ValueDecl *> TeamsReductions)
328 : CGF(CGF), EscapedDecls(llvm::from_range, TeamsReductions) {}
329 ~CheckVarsEscapingDeclContext() = default;
330 void VisitDeclStmt(const DeclStmt *S) {
331 if (!S)
332 return;
333 for (const Decl *D : S->decls())
334 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
335 VisitValueDecl(VD);
336 }
337 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
338 if (!D)
339 return;
340 if (!D->hasAssociatedStmt())
341 return;
342 if (const auto *S =
343 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
344 // Do not analyze directives that do not actually require capturing,
345 // like `omp for` or `omp simd` directives.
346 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
347 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
348 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
349 VisitStmt(S->getCapturedStmt());
350 return;
351 }
352 VisitOpenMPCapturedStmt(
353 S, D->clauses(),
354 CaptureRegions.back() == OMPD_parallel &&
355 isOpenMPDistributeDirective(D->getDirectiveKind()));
356 }
357 }
358 // A metadirective has no associated statement; visit its variants and
359 // conditions.
360 void VisitOMPMetaDirective(const OMPMetaDirective *D) { VisitStmt(D); }
361 void VisitCapturedStmt(const CapturedStmt *S) {
362 if (!S)
363 return;
364 for (const CapturedStmt::Capture &C : S->captures()) {
365 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
366 const ValueDecl *VD = C.getCapturedVar();
367 markAsEscaped(VD);
369 VisitValueDecl(VD);
370 }
371 }
372 }
373 void VisitLambdaExpr(const LambdaExpr *E) {
374 if (!E)
375 return;
376 for (const LambdaCapture &C : E->captures()) {
377 if (C.capturesVariable()) {
378 if (C.getCaptureKind() == LCK_ByRef) {
379 const ValueDecl *VD = C.getCapturedVar();
380 markAsEscaped(VD);
382 VisitValueDecl(VD);
383 }
384 }
385 }
386 }
387 void VisitBlockExpr(const BlockExpr *E) {
388 if (!E)
389 return;
390 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
391 if (C.isByRef()) {
392 const VarDecl *VD = C.getVariable();
393 markAsEscaped(VD);
395 VisitValueDecl(VD);
396 }
397 }
398 }
399 void VisitCallExpr(const CallExpr *E) {
400 if (!E)
401 return;
402 for (const Expr *Arg : E->arguments()) {
403 if (!Arg)
404 continue;
405 if (Arg->isLValue()) {
406 const bool SavedAllEscaped = AllEscaped;
407 AllEscaped = true;
408 Visit(Arg);
409 AllEscaped = SavedAllEscaped;
410 } else {
411 Visit(Arg);
412 }
413 }
414 Visit(E->getCallee());
415 }
416 void VisitDeclRefExpr(const DeclRefExpr *E) {
417 if (!E)
418 return;
419 const ValueDecl *VD = E->getDecl();
420 if (AllEscaped)
421 markAsEscaped(VD);
423 VisitValueDecl(VD);
424 else if (VD->isInitCapture())
425 VisitValueDecl(VD);
426 }
427 void VisitUnaryOperator(const UnaryOperator *E) {
428 if (!E)
429 return;
430 if (E->getOpcode() == UO_AddrOf) {
431 const bool SavedAllEscaped = AllEscaped;
432 AllEscaped = true;
433 Visit(E->getSubExpr());
434 AllEscaped = SavedAllEscaped;
435 } else {
436 Visit(E->getSubExpr());
437 }
438 }
439 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
440 if (!E)
441 return;
442 if (E->getCastKind() == CK_ArrayToPointerDecay) {
443 const bool SavedAllEscaped = AllEscaped;
444 AllEscaped = true;
445 Visit(E->getSubExpr());
446 AllEscaped = SavedAllEscaped;
447 } else {
448 Visit(E->getSubExpr());
449 }
450 }
451 void VisitExpr(const Expr *E) {
452 if (!E)
453 return;
454 bool SavedAllEscaped = AllEscaped;
455 if (!E->isLValue())
456 AllEscaped = false;
457 for (const Stmt *Child : E->children())
458 if (Child)
459 Visit(Child);
460 AllEscaped = SavedAllEscaped;
461 }
462 void VisitStmt(const Stmt *S) {
463 if (!S)
464 return;
465 for (const Stmt *Child : S->children())
466 if (Child)
467 Visit(Child);
468 }
469
470 /// Returns the record that handles all the escaped local variables and used
471 /// instead of their original storage.
472 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
473 if (!GlobalizedRD)
474 buildRecordForGlobalizedVars(IsInTTDRegion);
475 return GlobalizedRD;
476 }
477
478 /// Returns the field in the globalized record for the escaped variable.
479 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
480 assert(GlobalizedRD &&
481 "Record for globalized variables must be generated already.");
482 return MappedDeclsFields.lookup(VD);
483 }
484
485 /// Returns the list of the escaped local variables/parameters.
486 ArrayRef<const ValueDecl *> getEscapedDecls() const {
487 return EscapedDecls.getArrayRef();
488 }
489
490 /// Checks if the escaped local variable is actually a parameter passed by
491 /// value.
492 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
493 return EscapedParameters;
494 }
495
496 /// Returns the list of the escaped variables with the variably modified
497 /// types.
498 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
499 return EscapedVariableLengthDecls.getArrayRef();
500 }
501
502 /// Returns the list of the delayed variables with the variably modified
503 /// types.
504 ArrayRef<const ValueDecl *> getDelayedVariableLengthDecls() const {
505 return DelayedVariableLengthDecls.getArrayRef();
506 }
507};
508} // anonymous namespace
509
511CGOpenMPRuntimeGPU::getExecutionMode() const {
512 return CurrentExecutionMode;
513}
514
516CGOpenMPRuntimeGPU::getDataSharingMode() const {
517 return CurrentDataSharingMode;
518}
519
520/// Check for inner (nested) SPMD construct, if any
522 const OMPExecutableDirective &D) {
523 const auto *CS = D.getInnermostCapturedStmt();
524 const auto *Body =
525 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
526 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
527
528 if (const auto *NestedDir =
529 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
530 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
531 switch (D.getDirectiveKind()) {
532 case OMPD_target:
533 if (isOpenMPParallelDirective(DKind))
534 return true;
535 if (DKind == OMPD_teams) {
536 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
537 /*IgnoreCaptured=*/true);
538 if (!Body)
539 return false;
540 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
541 if (const auto *NND =
542 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
543 DKind = NND->getDirectiveKind();
544 if (isOpenMPParallelDirective(DKind))
545 return true;
546 }
547 }
548 return false;
549 case OMPD_target_teams:
550 return isOpenMPParallelDirective(DKind);
551 case OMPD_target_simd:
552 case OMPD_target_parallel:
553 case OMPD_target_parallel_for:
554 case OMPD_target_parallel_for_simd:
555 case OMPD_target_teams_distribute:
556 case OMPD_target_teams_distribute_simd:
557 case OMPD_target_teams_distribute_parallel_for:
558 case OMPD_target_teams_distribute_parallel_for_simd:
559 case OMPD_parallel:
560 case OMPD_for:
561 case OMPD_parallel_for:
562 case OMPD_parallel_master:
563 case OMPD_parallel_sections:
564 case OMPD_for_simd:
565 case OMPD_parallel_for_simd:
566 case OMPD_cancel:
567 case OMPD_cancellation_point:
568 case OMPD_ordered_standalone:
569 case OMPD_ordered_blockassoc:
570 case OMPD_threadprivate:
571 case OMPD_allocate:
572 case OMPD_task:
573 case OMPD_simd:
574 case OMPD_sections:
575 case OMPD_section:
576 case OMPD_single:
577 case OMPD_master:
578 case OMPD_critical:
579 case OMPD_taskyield:
580 case OMPD_barrier:
581 case OMPD_taskwait:
582 case OMPD_taskgroup:
583 case OMPD_atomic:
584 case OMPD_flush:
585 case OMPD_depobj:
586 case OMPD_scan:
587 case OMPD_teams:
588 case OMPD_target_data:
589 case OMPD_target_exit_data:
590 case OMPD_target_enter_data:
591 case OMPD_distribute:
592 case OMPD_distribute_simd:
593 case OMPD_distribute_parallel_for:
594 case OMPD_distribute_parallel_for_simd:
595 case OMPD_teams_distribute:
596 case OMPD_teams_distribute_simd:
597 case OMPD_teams_distribute_parallel_for:
598 case OMPD_teams_distribute_parallel_for_simd:
599 case OMPD_target_update:
600 case OMPD_declare_simd:
601 case OMPD_declare_variant:
602 case OMPD_begin_declare_variant:
603 case OMPD_end_declare_variant:
604 case OMPD_declare_target:
605 case OMPD_end_declare_target:
606 case OMPD_declare_reduction:
607 case OMPD_declare_mapper:
608 case OMPD_taskloop:
609 case OMPD_taskloop_simd:
610 case OMPD_master_taskloop:
611 case OMPD_master_taskloop_simd:
612 case OMPD_parallel_master_taskloop:
613 case OMPD_parallel_master_taskloop_simd:
614 case OMPD_requires:
615 case OMPD_unknown:
616 default:
617 llvm_unreachable("Unexpected directive.");
618 }
619 }
620
621 return false;
622}
623
625 const OMPExecutableDirective &D) {
626 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
627 switch (DirectiveKind) {
628 case OMPD_target:
629 case OMPD_target_teams:
630 return hasNestedSPMDDirective(Ctx, D);
631 case OMPD_target_parallel_loop:
632 case OMPD_target_parallel:
633 case OMPD_target_parallel_for:
634 case OMPD_target_parallel_for_simd:
635 case OMPD_target_teams_distribute_parallel_for:
636 case OMPD_target_teams_distribute_parallel_for_simd:
637 case OMPD_target_simd:
638 case OMPD_target_loop:
639 case OMPD_target_teams_distribute_simd:
640 return true;
641 case OMPD_target_teams_distribute:
642 return false;
643 case OMPD_target_teams_loop:
644 // Whether this is true or not depends on how the directive will
645 // eventually be emitted.
646 if (auto *TTLD = dyn_cast<OMPTargetTeamsGenericLoopDirective>(&D))
647 return TTLD->canBeParallelFor();
648 return false;
649 case OMPD_parallel:
650 case OMPD_for:
651 case OMPD_parallel_for:
652 case OMPD_parallel_master:
653 case OMPD_parallel_sections:
654 case OMPD_for_simd:
655 case OMPD_parallel_for_simd:
656 case OMPD_cancel:
657 case OMPD_cancellation_point:
658 case OMPD_ordered_standalone:
659 case OMPD_ordered_blockassoc:
660 case OMPD_threadprivate:
661 case OMPD_allocate:
662 case OMPD_task:
663 case OMPD_simd:
664 case OMPD_sections:
665 case OMPD_section:
666 case OMPD_single:
667 case OMPD_master:
668 case OMPD_critical:
669 case OMPD_taskyield:
670 case OMPD_barrier:
671 case OMPD_taskwait:
672 case OMPD_taskgroup:
673 case OMPD_atomic:
674 case OMPD_flush:
675 case OMPD_depobj:
676 case OMPD_scan:
677 case OMPD_teams:
678 case OMPD_target_data:
679 case OMPD_target_exit_data:
680 case OMPD_target_enter_data:
681 case OMPD_distribute:
682 case OMPD_distribute_simd:
683 case OMPD_distribute_parallel_for:
684 case OMPD_distribute_parallel_for_simd:
685 case OMPD_teams_distribute:
686 case OMPD_teams_distribute_simd:
687 case OMPD_teams_distribute_parallel_for:
688 case OMPD_teams_distribute_parallel_for_simd:
689 case OMPD_target_update:
690 case OMPD_declare_simd:
691 case OMPD_declare_variant:
692 case OMPD_begin_declare_variant:
693 case OMPD_end_declare_variant:
694 case OMPD_declare_target:
695 case OMPD_end_declare_target:
696 case OMPD_declare_reduction:
697 case OMPD_declare_mapper:
698 case OMPD_taskloop:
699 case OMPD_taskloop_simd:
700 case OMPD_master_taskloop:
701 case OMPD_master_taskloop_simd:
702 case OMPD_parallel_master_taskloop:
703 case OMPD_parallel_master_taskloop_simd:
704 case OMPD_requires:
705 case OMPD_unknown:
706 default:
707 break;
708 }
709 llvm_unreachable(
710 "Unknown programming model for OpenMP directive on NVPTX target.");
711}
712
713void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
714 StringRef ParentName,
715 llvm::Function *&OutlinedFn,
716 llvm::Constant *&OutlinedFnID,
717 bool IsOffloadEntry,
718 const RegionCodeGenTy &CodeGen) {
719 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_NonSPMD);
720 EntryFunctionState EST;
721 WrapperFunctionsMap.clear();
722
723 [[maybe_unused]] bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
724 assert(!IsBareKernel && "bare kernel should not be at generic mode");
725
726 // Emit target region as a standalone region.
727 class NVPTXPrePostActionTy : public PrePostActionTy {
728 CGOpenMPRuntimeGPU::EntryFunctionState &EST;
729 const OMPExecutableDirective &D;
730
731 public:
732 NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST,
733 const OMPExecutableDirective &D)
734 : EST(EST), D(D) {}
735 void Enter(CodeGenFunction &CGF) override {
736 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
737 RT.emitKernelInit(D, CGF, EST, /* IsSPMD */ false);
738 // Skip target region initialization.
739 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
740 }
741 void Exit(CodeGenFunction &CGF) override {
742 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
743 RT.clearLocThreadIdInsertPt(CGF);
744 RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ false);
745 }
746 } Action(EST, D);
747 CodeGen.setAction(Action);
748 IsInTTDRegion = true;
749 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
750 IsOffloadEntry, CodeGen);
751 IsInTTDRegion = false;
752}
753
754void CGOpenMPRuntimeGPU::emitBareKernelEnvironment(
755 const OMPExecutableDirective &D, CodeGenFunction &CGF) {
756 // Bare kernels manage their own initialization and never call
757 // __kmpc_target_init, but the runtime still needs a
758 // '<kernel>_kernel_environment' global to know how the kernel was
759 // configured, so emit it directly here.
760 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs Attrs;
761 Attrs.ExecFlags = llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_BARE;
762 CGBuilderTy &Bld = CGF.Builder;
763 OMPBuilder.emitKernelEnvironment(Bld, Attrs);
764}
765
766void CGOpenMPRuntimeGPU::emitKernelInit(const OMPExecutableDirective &D,
767 CodeGenFunction &CGF,
768 EntryFunctionState &EST, bool IsSPMD) {
769 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs Attrs;
770 Attrs.ExecFlags =
771 IsSPMD ? llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_SPMD
772 : llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC;
773 computeMinAndMaxThreadsAndTeams(D, CGF, Attrs);
774
775 CGBuilderTy &Bld = CGF.Builder;
776 Bld.restoreIP(OMPBuilder.createTargetInit(Bld, Attrs));
777 if (!IsSPMD)
778 emitGenericVarsProlog(CGF, EST.Loc);
779}
780
781void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction &CGF,
782 EntryFunctionState &EST,
783 bool IsSPMD) {
784 if (!IsSPMD)
785 emitGenericVarsEpilog(CGF);
786
787 // This is temporary until we remove the fixed sized buffer.
788 ASTContext &C = CGM.getContext();
789 RecordDecl *StaticRD = C.buildImplicitRecord(
790 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::Union);
791 StaticRD->startDefinition();
792 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
793 CanQualType RecTy = C.getCanonicalTagType(TeamReductionRec);
794 auto *Field = FieldDecl::Create(
795 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
796 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
797 /*BW=*/nullptr, /*Mutable=*/false,
798 /*InitStyle=*/ICIS_NoInit);
799 Field->setAccess(AS_public);
800 StaticRD->addDecl(Field);
801 }
802 StaticRD->completeDefinition();
803 CanQualType StaticTy = C.getCanonicalTagType(StaticRD);
804 llvm::Type *LLVMReductionsBufferTy =
805 CGM.getTypes().ConvertTypeForMem(StaticTy);
806 const auto &DL = CGM.getModule().getDataLayout();
807 uint64_t ReductionDataSize =
808 TeamsReductions.empty()
809 ? 0
810 : DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
811 CGBuilderTy &Bld = CGF.Builder;
812 OMPBuilder.createTargetDeinit(Bld, ReductionDataSize);
813 TeamsReductions.clear();
814}
815
816void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
817 StringRef ParentName,
818 llvm::Function *&OutlinedFn,
819 llvm::Constant *&OutlinedFnID,
820 bool IsOffloadEntry,
821 const RegionCodeGenTy &CodeGen) {
822 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_SPMD);
823 EntryFunctionState EST;
824
825 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
826
827 // Emit target region as a standalone region.
828 class NVPTXPrePostActionTy : public PrePostActionTy {
829 CGOpenMPRuntimeGPU &RT;
830 CGOpenMPRuntimeGPU::EntryFunctionState &EST;
831 bool IsBareKernel;
832 DataSharingMode Mode;
833 const OMPExecutableDirective &D;
834
835 public:
836 NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
837 CGOpenMPRuntimeGPU::EntryFunctionState &EST,
838 bool IsBareKernel, const OMPExecutableDirective &D)
839 : RT(RT), EST(EST), IsBareKernel(IsBareKernel),
840 Mode(RT.CurrentDataSharingMode), D(D) {}
841 void Enter(CodeGenFunction &CGF) override {
842 if (IsBareKernel) {
843 RT.CurrentDataSharingMode = DataSharingMode::DS_CUDA;
844 RT.emitBareKernelEnvironment(D, CGF);
845 return;
846 }
847 RT.emitKernelInit(D, CGF, EST, /* IsSPMD */ true);
848 // Skip target region initialization.
849 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
850 }
851 void Exit(CodeGenFunction &CGF) override {
852 if (IsBareKernel) {
853 RT.CurrentDataSharingMode = Mode;
854 return;
855 }
856 RT.clearLocThreadIdInsertPt(CGF);
857 RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ true);
858 }
859 } Action(*this, EST, IsBareKernel, D);
860 CodeGen.setAction(Action);
861 IsInTTDRegion = true;
862 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
863 IsOffloadEntry, CodeGen);
864 IsInTTDRegion = false;
865}
866
867void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
868 const OMPExecutableDirective &D, StringRef ParentName,
869 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
870 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
871 if (!IsOffloadEntry) // Nothing to do.
872 return;
873
874 assert(!ParentName.empty() && "Invalid target region parent name!");
875
876 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
877 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
878 if (Mode || IsBareKernel)
879 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
880 CodeGen);
881 else
882 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
883 CodeGen);
884}
885
888 llvm::OpenMPIRBuilderConfig Config(
889 CGM.getLangOpts().OpenMPIsTargetDevice, isGPU(),
890 CGM.getLangOpts().OpenMPOffloadMandatory,
891 /*HasRequiresReverseOffload*/ false, /*HasRequiresUnifiedAddress*/ false,
892 hasRequiresUnifiedSharedMemory(), /*HasRequiresDynamicAllocators*/ false);
893 Config.setDefaultTargetAS(
894 CGM.getContext().getTargetInfo().getTargetAddressSpace(LangAS::Default));
895 Config.setRuntimeCC(CGM.getRuntimeCC());
896
897 OMPBuilder.setConfig(Config);
898
899 if (!CGM.getLangOpts().OpenMPIsTargetDevice)
900 llvm_unreachable("OpenMP can only handle device code.");
901
902 if (CGM.getLangOpts().OpenMPCUDAMode)
903 CurrentDataSharingMode = CGOpenMPRuntimeGPU::DS_CUDA;
904
905 llvm::OpenMPIRBuilder &OMPBuilder = getOMPBuilder();
906 if (CGM.getLangOpts().NoGPULib || CGM.getLangOpts().OMPHostIRFile.empty())
907 return;
908
909 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTargetDebug,
910 "__omp_rtl_debug_kind");
911 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTeamSubscription,
912 "__omp_rtl_assume_teams_oversubscription");
913 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPThreadSubscription,
914 "__omp_rtl_assume_threads_oversubscription");
915 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoThreadState,
916 "__omp_rtl_assume_no_thread_state");
917 OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoNestedParallelism,
918 "__omp_rtl_assume_no_nested_parallelism");
919}
920
922 ProcBindKind ProcBind,
923 SourceLocation Loc) {
924 // Nothing to do.
925}
926
928 const Expr *Message,
929 SourceLocation Loc) {
930 CGM.getDiags().Report(Loc, diag::warn_omp_gpu_unsupported_clause)
931 << getOpenMPClauseName(OMPC_message);
932 return nullptr;
933}
934
935llvm::Value *
937 SourceLocation Loc) {
938 CGM.getDiags().Report(Loc, diag::warn_omp_gpu_unsupported_clause)
939 << getOpenMPClauseName(OMPC_severity);
940 return nullptr;
941}
942
944 CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc,
946 SourceLocation SeverityLoc, const Expr *Message,
947 SourceLocation MessageLoc) {
948 if (Modifier == OMPC_NUMTHREADS_strict) {
949 CGM.getDiags().Report(Loc,
950 diag::warn_omp_gpu_unsupported_modifier_for_clause)
951 << "strict" << getOpenMPClauseName(OMPC_num_threads);
952 return;
953 }
954
955 // Nothing to do.
956}
957
959 const Expr *NumTeams,
960 const Expr *ThreadLimit,
961 SourceLocation Loc) {}
962
965 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
966 const RegionCodeGenTy &CodeGen) {
967 // Emit target region as a standalone region.
968 bool PrevIsInTTDRegion = IsInTTDRegion;
969 IsInTTDRegion = false;
970 auto *OutlinedFun =
972 CGF, D, ThreadIDVar, InnermostKind, CodeGen));
973 IsInTTDRegion = PrevIsInTTDRegion;
974 if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD) {
975 llvm::Function *WrapperFun =
976 createParallelDataSharingWrapper(OutlinedFun, D);
977 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
978 }
979
980 return OutlinedFun;
981}
982
983/// Get list of lastprivate variables from the teams distribute ... or
984/// teams {distribute ...} directives.
985static void
988 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
989 "expected teams directive.");
990 const OMPExecutableDirective *Dir = &D;
991 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
993 Ctx,
994 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
995 /*IgnoreCaptured=*/true))) {
996 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
997 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
998 Dir = nullptr;
999 }
1000 }
1001 if (!Dir)
1002 return;
1003 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
1004 for (const Expr *E : C->getVarRefs())
1005 Vars.push_back(getPrivateItem(E));
1006 }
1007}
1008
1009/// Get list of reduction variables from the teams ... directives.
1010static void
1013 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1014 "expected teams directive.");
1015 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1016 for (const Expr *E : C->privates())
1017 Vars.push_back(getPrivateItem(E));
1018 }
1019}
1020
1023 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1024 const RegionCodeGenTy &CodeGen) {
1025 SourceLocation Loc = D.getBeginLoc();
1026
1027 const RecordDecl *GlobalizedRD = nullptr;
1028 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
1029 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1030 unsigned WarpSize = CGM.getTarget().getGridValue().GV_Warp_Size;
1031 // Globalize team reductions variable unconditionally in all modes.
1032 if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1033 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
1034 if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
1035 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1036 if (!LastPrivatesReductions.empty()) {
1037 GlobalizedRD = ::buildRecordForGlobalizedVars(
1038 CGM.getContext(), {}, LastPrivatesReductions, MappedDeclsFields,
1039 WarpSize);
1040 }
1041 } else if (!LastPrivatesReductions.empty()) {
1042 assert(!TeamAndReductions.first &&
1043 "Previous team declaration is not expected.");
1044 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
1045 std::swap(TeamAndReductions.second, LastPrivatesReductions);
1046 }
1047
1048 // Emit target region as a standalone region.
1049 class NVPTXPrePostActionTy : public PrePostActionTy {
1050 SourceLocation &Loc;
1051 const RecordDecl *GlobalizedRD;
1052 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1053 &MappedDeclsFields;
1054
1055 public:
1056 NVPTXPrePostActionTy(
1057 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1058 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1059 &MappedDeclsFields)
1060 : Loc(Loc), GlobalizedRD(GlobalizedRD),
1061 MappedDeclsFields(MappedDeclsFields) {}
1062 void Enter(CodeGenFunction &CGF) override {
1063 auto &Rt =
1064 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1065 if (GlobalizedRD) {
1066 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1067 I->getSecond().MappedParams =
1068 std::make_unique<CodeGenFunction::OMPMapVars>();
1069 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1070 for (const auto &Pair : MappedDeclsFields) {
1071 assert(Pair.getFirst()->isCanonicalDecl() &&
1072 "Expected canonical declaration");
1073 Data.try_emplace(Pair.getFirst());
1074 }
1075 }
1076 Rt.emitGenericVarsProlog(CGF, Loc);
1077 }
1078 void Exit(CodeGenFunction &CGF) override {
1079 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
1080 .emitGenericVarsEpilog(CGF);
1081 }
1082 } Action(Loc, GlobalizedRD, MappedDeclsFields);
1083 CodeGen.setAction(Action);
1084 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1085 CGF, D, ThreadIDVar, InnermostKind, CodeGen);
1086
1087 return OutlinedFun;
1088}
1089
1090void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
1091 SourceLocation Loc) {
1092 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
1093 return;
1094
1095 CGBuilderTy &Bld = CGF.Builder;
1096
1097 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1098 if (I == FunctionGlobalizedDecls.end())
1099 return;
1100
1101 for (auto &Rec : I->getSecond().LocalVarData) {
1102 const auto *VD = cast<VarDecl>(Rec.first);
1103 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1104 QualType VarTy = VD->getType();
1105
1106 // Get the local allocation of a firstprivate variable before sharing
1107 llvm::Value *ParValue;
1108 if (EscapedParam) {
1109 LValue ParLVal =
1110 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1111 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1112 }
1113
1114 // Allocate space for the variable to be globalized
1115 llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
1116 llvm::CallBase *VoidPtr =
1117 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1118 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1119 AllocArgs, VD->getName());
1120 // FIXME: We should use the variables actual alignment as an argument.
1121 VoidPtr->addRetAttr(llvm::Attribute::get(
1122 CGM.getLLVMContext(), llvm::Attribute::Alignment,
1124
1125 // Cast the void pointer and get the address of the globalized variable.
1126 llvm::Value *CastedVoidPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1127 VoidPtr, Bld.getPtrTy(0), VD->getName() + "_on_stack");
1128 LValue VarAddr =
1129 CGF.MakeNaturalAlignPointeeRawAddrLValue(CastedVoidPtr, VarTy);
1130 Rec.second.PrivateAddr = VarAddr.getAddress();
1131 Rec.second.GlobalizedVal = VoidPtr;
1132
1133 // Assign the local allocation to the newly globalized location.
1134 if (EscapedParam) {
1135 CGF.EmitStoreOfScalar(ParValue, VarAddr);
1136 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
1137 }
1138 if (auto *DI = CGF.getDebugInfo())
1139 VoidPtr->setDebugLoc(DI->SourceLocToDebugLoc(VD->getLocation()));
1140 }
1141
1142 for (const auto *ValueD : I->getSecond().EscapedVariableLengthDecls) {
1143 const auto *VD = cast<VarDecl>(ValueD);
1144 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1145 getKmpcAllocShared(CGF, VD);
1146 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(AddrSizePair);
1147 LValue Base = CGF.MakeAddrLValue(AddrSizePair.first, VD->getType(),
1148 CGM.getContext().getDeclAlign(VD),
1150 I->getSecond().MappedParams->setVarAddr(CGF, VD, Base.getAddress());
1151 }
1152 I->getSecond().MappedParams->apply(CGF);
1153}
1154
1156 const VarDecl *VD) const {
1157 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1158 if (I == FunctionGlobalizedDecls.end())
1159 return false;
1160
1161 // Check variable declaration is delayed:
1162 return llvm::is_contained(I->getSecond().DelayedVariableLengthDecls, VD);
1163}
1164
1165std::pair<llvm::Value *, llvm::Value *>
1167 const VarDecl *VD) {
1168 CGBuilderTy &Bld = CGF.Builder;
1169
1170 // Compute size and alignment.
1171 llvm::Value *Size = CGF.getTypeSize(VD->getType());
1172 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1173 Size = Bld.CreateNUWAdd(
1174 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1175 llvm::Value *AlignVal =
1176 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1177 Size = Bld.CreateUDiv(Size, AlignVal);
1178 Size = Bld.CreateNUWMul(Size, AlignVal);
1179
1180 // Allocate space for this VLA object to be globalized.
1181 llvm::Value *AllocArgs[] = {Size};
1182 llvm::CallBase *VoidPtr =
1183 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1184 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1185 AllocArgs, VD->getName());
1186 VoidPtr->addRetAttr(llvm::Attribute::get(
1187 CGM.getLLVMContext(), llvm::Attribute::Alignment, Align.getQuantity()));
1188
1189 return std::make_pair(VoidPtr, Size);
1190}
1191
1193 CodeGenFunction &CGF,
1194 const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair) {
1195 // Deallocate the memory for each globalized VLA object
1196 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1197 CGM.getModule(), OMPRTL___kmpc_free_shared),
1198 {AddrSizePair.first, AddrSizePair.second});
1199}
1200
1201void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF) {
1202 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
1203 return;
1204
1205 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1206 if (I != FunctionGlobalizedDecls.end()) {
1207 // Deallocate the memory for each globalized VLA object that was
1208 // globalized in the prolog (i.e. emitGenericVarsProlog).
1209 for (const auto &AddrSizePair :
1210 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1211 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1212 CGM.getModule(), OMPRTL___kmpc_free_shared),
1213 {AddrSizePair.first, AddrSizePair.second});
1214 }
1215 // Deallocate the memory for each globalized value
1216 for (auto &Rec : llvm::reverse(I->getSecond().LocalVarData)) {
1217 const auto *VD = cast<VarDecl>(Rec.first);
1218 I->getSecond().MappedParams->restore(CGF);
1219
1220 llvm::Value *FreeArgs[] = {Rec.second.GlobalizedVal,
1221 CGF.getTypeSize(VD->getType())};
1222 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1223 CGM.getModule(), OMPRTL___kmpc_free_shared),
1224 FreeArgs);
1225 }
1226 }
1227}
1228
1230 const OMPExecutableDirective &D,
1231 SourceLocation Loc,
1232 llvm::Function *OutlinedFn,
1233 ArrayRef<llvm::Value *> CapturedVars) {
1234 if (!CGF.HaveInsertPoint())
1235 return;
1236
1237 bool IsBareKernel = D.getSingleClause<OMPXBareClause>();
1238
1240 /*Name=*/".zero.addr");
1241 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
1243 // We don't emit any thread id function call in bare kernel, but because the
1244 // outlined function has a pointer argument, we emit a nullptr here.
1245 if (IsBareKernel)
1246 OutlinedFnArgs.push_back(llvm::ConstantPointerNull::get(CGM.VoidPtrTy));
1247 else
1248 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).emitRawPointer(CGF));
1249 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1250 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1251 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1252}
1253
1255 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
1256 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond,
1257 llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier,
1258 OpenMPSeverityClauseKind Severity, const Expr *Message) {
1259 if (!CGF.HaveInsertPoint())
1260 return;
1261
1262 auto &&ParallelGen = [this, Loc, OutlinedFn, CapturedVars, IfCond,
1263 NumThreads](CodeGenFunction &CGF,
1264 PrePostActionTy &Action) {
1265 CGBuilderTy &Bld = CGF.Builder;
1266 llvm::Value *NumThreadsVal = NumThreads;
1267 llvm::Function *WFn = WrapperFunctionsMap[OutlinedFn];
1268 llvm::PointerType *FnPtrTy = llvm::PointerType::get(
1269 CGF.getLLVMContext(), CGM.getDataLayout().getProgramAddressSpace());
1270
1271 llvm::Value *ID = llvm::ConstantPointerNull::get(FnPtrTy);
1272 if (WFn)
1273 ID = Bld.CreateBitOrPointerCast(WFn, FnPtrTy);
1274
1275 llvm::Value *FnPtr = Bld.CreateBitOrPointerCast(OutlinedFn, FnPtrTy);
1276
1277 // Create a private scope that will globalize the arguments
1278 // passed from the outside of the target region.
1279 // TODO: Is that needed?
1280 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1281
1282 Address CapturedVarsAddrs = CGF.CreateDefaultAlignTempAlloca(
1283 llvm::ArrayType::get(CGM.VoidPtrTy, CapturedVars.size()),
1284 "captured_vars_addrs");
1285 // There's something to share.
1286 if (!CapturedVars.empty()) {
1287 // Prepare for parallel region. Indicate the outlined function.
1288 ASTContext &Ctx = CGF.getContext();
1289 unsigned Idx = 0;
1290 for (llvm::Value *V : CapturedVars) {
1291 Address Dst = Bld.CreateConstArrayGEP(CapturedVarsAddrs, Idx);
1292 llvm::Value *PtrV;
1293 if (V->getType()->isIntegerTy())
1294 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1295 else
1297 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1298 Ctx.getPointerType(Ctx.VoidPtrTy));
1299 ++Idx;
1300 }
1301 }
1302
1303 llvm::Value *IfCondVal = nullptr;
1304 if (IfCond)
1305 IfCondVal = Bld.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.Int32Ty,
1306 /* isSigned */ false);
1307 else
1308 IfCondVal = llvm::ConstantInt::get(CGF.Int32Ty, 1);
1309
1310 if (!NumThreadsVal)
1311 NumThreadsVal = llvm::ConstantInt::getAllOnesValue(CGF.Int32Ty);
1312 else
1313 NumThreadsVal = Bld.CreateZExtOrTrunc(NumThreadsVal, CGF.Int32Ty);
1314
1315 // No strict prescriptiveness for the number of threads.
1316 llvm::Value *StrictNumThreadsVal = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1317
1318 assert(IfCondVal && "Expected a value");
1319 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1320 llvm::Value *Args[] = {
1321 RTLoc,
1322 getThreadID(CGF, Loc),
1323 IfCondVal,
1324 NumThreadsVal,
1325 llvm::ConstantInt::getAllOnesValue(CGF.Int32Ty),
1326 FnPtr,
1327 ID,
1328 Bld.CreateBitOrPointerCast(CapturedVarsAddrs.emitRawPointer(CGF),
1329 CGF.VoidPtrPtrTy),
1330 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size()),
1331 StrictNumThreadsVal};
1332
1333 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1334 CGM.getModule(), OMPRTL___kmpc_parallel_60),
1335 Args);
1336 };
1337
1338 RegionCodeGenTy RCG(ParallelGen);
1339 RCG(CGF);
1340}
1341
1342void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
1343 // Always emit simple barriers!
1344 if (!CGF.HaveInsertPoint())
1345 return;
1346 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
1347 // This function does not use parameters, so we can emit just default values.
1348 llvm::Value *Args[] = {
1349 llvm::ConstantPointerNull::get(
1351 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
1352 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1353 CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
1354 Args);
1355}
1356
1358 SourceLocation Loc,
1359 OpenMPDirectiveKind Kind, bool,
1360 bool) {
1361 // Always emit simple barriers!
1362 if (!CGF.HaveInsertPoint())
1363 return;
1364 // Build call __kmpc_cancel_barrier(loc, thread_id);
1365 unsigned Flags = getDefaultFlagsForBarriers(Kind);
1366 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1367 getThreadID(CGF, Loc)};
1368
1369 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1370 CGM.getModule(), OMPRTL___kmpc_barrier),
1371 Args);
1372}
1373
1375 CodeGenFunction &CGF, StringRef CriticalName,
1376 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1377 const Expr *Hint) {
1378 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1379 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1380 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1381 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1382 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1383
1384 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1385
1386 // Get the mask of active threads in the warp.
1387 llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1388 CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
1389 // Fetch team-local id of the thread.
1390 llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
1391
1392 // Get the width of the team.
1393 llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
1394
1395 // Initialize the counter variable for the loop.
1396 QualType Int32Ty =
1397 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1398 Address Counter = CGF.CreateMemTempWithoutCast(Int32Ty, "critical_counter");
1399 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1400 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1401 /*isInit=*/true);
1402
1403 // Block checks if loop counter exceeds upper bound.
1404 CGF.EmitBlock(LoopBB);
1405 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1406 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1407 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1408
1409 // Block tests which single thread should execute region, and which threads
1410 // should go straight to synchronisation point.
1411 CGF.EmitBlock(TestBB);
1412 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1413 llvm::Value *CmpThreadToCounter =
1414 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1415 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1416
1417 // Block emits the body of the critical region.
1418 CGF.EmitBlock(BodyBB);
1419
1420 // Output the critical statement.
1421 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
1422 Hint);
1423
1424 // After the body surrounded by the critical region, the single executing
1425 // thread will jump to the synchronisation point.
1426 // Block waits for all threads in current team to finish then increments the
1427 // counter variable and returns to the loop.
1428 CGF.EmitBlock(SyncBB);
1429 // Reconverge active threads in the warp.
1430 (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1431 CGM.getModule(), OMPRTL___kmpc_syncwarp),
1432 Mask);
1433
1434 llvm::Value *IncCounterVal =
1435 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1436 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1437 CGF.EmitBranch(LoopBB);
1438
1439 // Block that is reached when all threads in the team complete the region.
1440 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1441}
1442
1443/// Cast value to the specified type.
1444static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
1445 QualType ValTy, QualType CastTy,
1446 SourceLocation Loc) {
1447 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
1448 "Cast type must sized.");
1449 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
1450 "Val type must sized.");
1451 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
1452 if (ValTy == CastTy)
1453 return Val;
1454 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
1455 CGF.getContext().getTypeSizeInChars(CastTy))
1456 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
1457 if (CastTy->isIntegerType() && ValTy->isIntegerType())
1458 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
1460 Address CastItem = CGF.CreateMemTempWithoutCast(CastTy);
1461 Address ValCastItem = CastItem.withElementType(Val->getType());
1462 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
1464 TBAAAccessInfo());
1465 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
1467 TBAAAccessInfo());
1468}
1469
1470/// Extracts the built-in reduction operator from a combiner of the form `x = x
1471/// <op> rhs` (or the min/max conditional), or nullopt if the shape is not
1472/// recognized (e.g. user-defined reductions).
1473static std::optional<BinaryOperatorKind>
1474getReductionBinOpKind(const Expr *ReductionOp) {
1475 const auto *Assign = dyn_cast<BinaryOperator>(ReductionOp);
1476 if (!Assign || Assign->getOpcode() != BO_Assign)
1477 return std::nullopt;
1478 const Expr *RHS = Assign->getRHS();
1479 // min/max are lowered as `x <cmp> rhs ? x : rhs`; the comparison identifies
1480 // it.
1481 if (const auto *ACO =
1482 dyn_cast<AbstractConditionalOperator>(RHS->IgnoreParenImpCasts()))
1483 RHS = ACO->getCond();
1484 if (const auto *BO = dyn_cast<BinaryOperator>(RHS->IgnoreParenImpCasts()))
1485 return BO->getOpcode();
1486 return std::nullopt;
1487}
1488
1489/// Maps a built-in reduction operator to an atomicrmw opcode for the atomic
1490/// cross-team reduction fast path, or nullopt if there is no direct atomicrmw
1491/// (e.g. user-defined, complex, fp min/max) so the buffer path is used instead.
1492static std::optional<llvm::AtomicRMWInst::BinOp>
1494 bool IsInt = Ty->isIntegerType();
1495 bool IsSigned = Ty->hasSignedIntegerRepresentation();
1496 switch (BOK) {
1497 case BO_Add:
1498 case BO_Sub: // A `-` reduction sums the partials, so it accumulates with add.
1499 if (IsInt)
1500 return llvm::AtomicRMWInst::Add;
1501 if (Ty->isFloatingType())
1502 return llvm::AtomicRMWInst::FAdd;
1503 return std::nullopt;
1504 case BO_And:
1505 return IsInt ? std::optional(llvm::AtomicRMWInst::And) : std::nullopt;
1506 case BO_Or:
1507 return IsInt ? std::optional(llvm::AtomicRMWInst::Or) : std::nullopt;
1508 case BO_Xor:
1509 return IsInt ? std::optional(llvm::AtomicRMWInst::Xor) : std::nullopt;
1510 case BO_LT: // min
1511 if (IsInt)
1512 return IsSigned ? llvm::AtomicRMWInst::Min : llvm::AtomicRMWInst::UMin;
1513 return std::nullopt;
1514 case BO_GT: // max
1515 if (IsInt)
1516 return IsSigned ? llvm::AtomicRMWInst::Max : llvm::AtomicRMWInst::UMax;
1517 return std::nullopt;
1518 default:
1519 return std::nullopt;
1520 }
1521}
1522
1523///
1524/// Design of OpenMP reductions on the GPU
1525///
1526/// Consider a typical OpenMP program with one or more reduction
1527/// clauses:
1528///
1529/// float foo;
1530/// double bar;
1531/// #pragma omp target teams distribute parallel for \
1532/// reduction(+:foo) reduction(*:bar)
1533/// for (int i = 0; i < N; i++) {
1534/// foo += A[i]; bar *= B[i];
1535/// }
1536///
1537/// where 'foo' and 'bar' are reduced across all OpenMP threads in
1538/// all teams. In our OpenMP implementation on the NVPTX device an
1539/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
1540/// within a team are mapped to CUDA threads within a threadblock.
1541/// Our goal is to efficiently aggregate values across all OpenMP
1542/// threads such that:
1543///
1544/// - the compiler and runtime are logically concise, and
1545/// - the reduction is performed efficiently in a hierarchical
1546/// manner as follows: within OpenMP threads in the same warp,
1547/// across warps in a threadblock, and finally across teams on
1548/// the NVPTX device.
1549///
1550/// Introduction to Decoupling
1551///
1552/// We would like to decouple the compiler and the runtime so that the
1553/// latter is ignorant of the reduction variables (number, data types)
1554/// and the reduction operators. This allows a simpler interface
1555/// and implementation while still attaining good performance.
1556///
1557/// Pseudocode for the aforementioned OpenMP program generated by the
1558/// compiler is as follows:
1559///
1560/// 1. Create private copies of reduction variables on each OpenMP
1561/// thread: 'foo_private', 'bar_private'
1562/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
1563/// to it and writes the result in 'foo_private' and 'bar_private'
1564/// respectively.
1565/// 3. Call the OpenMP runtime on the GPU to reduce within a team
1566/// and store the result on the team master:
1567///
1568/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
1569/// reduceData, shuffleReduceFn, interWarpCpyFn)
1570///
1571/// where:
1572/// struct ReduceData {
1573/// double *foo;
1574/// double *bar;
1575/// } reduceData
1576/// reduceData.foo = &foo_private
1577/// reduceData.bar = &bar_private
1578///
1579/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
1580/// auxiliary functions generated by the compiler that operate on
1581/// variables of type 'ReduceData'. They aid the runtime perform
1582/// algorithmic steps in a data agnostic manner.
1583///
1584/// 'shuffleReduceFn' is a pointer to a function that reduces data
1585/// of type 'ReduceData' across two OpenMP threads (lanes) in the
1586/// same warp. It takes the following arguments as input:
1587///
1588/// a. variable of type 'ReduceData' on the calling lane,
1589/// b. its lane_id,
1590/// c. an offset relative to the current lane_id to generate a
1591/// remote_lane_id. The remote lane contains the second
1592/// variable of type 'ReduceData' that is to be reduced.
1593/// d. an algorithm version parameter determining which reduction
1594/// algorithm to use.
1595///
1596/// 'shuffleReduceFn' retrieves data from the remote lane using
1597/// efficient GPU shuffle intrinsics and reduces, using the
1598/// algorithm specified by the 4th parameter, the two operands
1599/// element-wise. The result is written to the first operand.
1600///
1601/// Different reduction algorithms are implemented in different
1602/// runtime functions, all calling 'shuffleReduceFn' to perform
1603/// the essential reduction step. Therefore, based on the 4th
1604/// parameter, this function behaves slightly differently to
1605/// cooperate with the runtime to ensure correctness under
1606/// different circumstances.
1607///
1608/// 'InterWarpCpyFn' is a pointer to a function that transfers
1609/// reduced variables across warps. It tunnels, through CUDA
1610/// shared memory, the thread-private data of type 'ReduceData'
1611/// from lane 0 of each warp to a lane in the first warp.
1612/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
1613/// The last team writes the global reduced value to memory.
1614///
1615/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
1616/// reduceData, shuffleReduceFn, interWarpCpyFn,
1617/// scratchpadCopyFn, loadAndReduceFn)
1618///
1619/// 'scratchpadCopyFn' is a helper that stores reduced
1620/// data from the team master to a scratchpad array in
1621/// global memory.
1622///
1623/// 'loadAndReduceFn' is a helper that loads data from
1624/// the scratchpad array and reduces it with the input
1625/// operand.
1626///
1627/// These compiler generated functions hide address
1628/// calculation and alignment information from the runtime.
1629/// 5. if ret == 1:
1630/// The team master of the last team stores the reduced
1631/// result to the globals in memory.
1632/// foo += reduceData.foo; bar *= reduceData.bar
1633///
1634///
1635/// Warp Reduction Algorithms
1636///
1637/// On the warp level, we have three algorithms implemented in the
1638/// OpenMP runtime depending on the number of active lanes:
1639///
1640/// Full Warp Reduction
1641///
1642/// The reduce algorithm within a warp where all lanes are active
1643/// is implemented in the runtime as follows:
1644///
1645/// full_warp_reduce(void *reduce_data,
1646/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1647/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
1648/// ShuffleReduceFn(reduce_data, 0, offset, 0);
1649/// }
1650///
1651/// The algorithm completes in log(2, WARPSIZE) steps.
1652///
1653/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
1654/// not used therefore we save instructions by not retrieving lane_id
1655/// from the corresponding special registers. The 4th parameter, which
1656/// represents the version of the algorithm being used, is set to 0 to
1657/// signify full warp reduction.
1658///
1659/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1660///
1661/// #reduce_elem refers to an element in the local lane's data structure
1662/// #remote_elem is retrieved from a remote lane
1663/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1664/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
1665///
1666/// Contiguous Partial Warp Reduction
1667///
1668/// This reduce algorithm is used within a warp where only the first
1669/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
1670/// number of OpenMP threads in a parallel region is not a multiple of
1671/// WARPSIZE. The algorithm is implemented in the runtime as follows:
1672///
1673/// void
1674/// contiguous_partial_reduce(void *reduce_data,
1675/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
1676/// int size, int lane_id) {
1677/// int curr_size;
1678/// int offset;
1679/// curr_size = size;
1680/// mask = curr_size/2;
1681/// while (offset>0) {
1682/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
1683/// curr_size = (curr_size+1)/2;
1684/// offset = curr_size/2;
1685/// }
1686/// }
1687///
1688/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1689///
1690/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1691/// if (lane_id < offset)
1692/// reduce_elem = reduce_elem REDUCE_OP remote_elem
1693/// else
1694/// reduce_elem = remote_elem
1695///
1696/// This algorithm assumes that the data to be reduced are located in a
1697/// contiguous subset of lanes starting from the first. When there is
1698/// an odd number of active lanes, the data in the last lane is not
1699/// aggregated with any other lane's dat but is instead copied over.
1700///
1701/// Dispersed Partial Warp Reduction
1702///
1703/// This algorithm is used within a warp when any discontiguous subset of
1704/// lanes are active. It is used to implement the reduction operation
1705/// across lanes in an OpenMP simd region or in a nested parallel region.
1706///
1707/// void
1708/// dispersed_partial_reduce(void *reduce_data,
1709/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
1710/// int size, remote_id;
1711/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
1712/// do {
1713/// remote_id = next_active_lane_id_right_after_me();
1714/// # the above function returns 0 of no active lane
1715/// # is present right after the current lane.
1716/// size = number_of_active_lanes_in_this_warp();
1717/// logical_lane_id /= 2;
1718/// ShuffleReduceFn(reduce_data, logical_lane_id,
1719/// remote_id-1-threadIdx.x, 2);
1720/// } while (logical_lane_id % 2 == 0 && size > 1);
1721/// }
1722///
1723/// There is no assumption made about the initial state of the reduction.
1724/// Any number of lanes (>=1) could be active at any position. The reduction
1725/// result is returned in the first active lane.
1726///
1727/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
1728///
1729/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
1730/// if (lane_id % 2 == 0 && offset > 0)
1731/// reduce_elem = reduce_elem REDUCE_OP remote_elem
1732/// else
1733/// reduce_elem = remote_elem
1734///
1735///
1736/// Intra-Team Reduction
1737///
1738/// This function, as implemented in the runtime call
1739/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
1740/// threads in a team. It first reduces within a warp using the
1741/// aforementioned algorithms. We then proceed to gather all such
1742/// reduced values at the first warp.
1743///
1744/// The runtime makes use of the function 'InterWarpCpyFn', which copies
1745/// data from each of the "warp master" (zeroth lane of each warp, where
1746/// warp-reduced data is held) to the zeroth warp. This step reduces (in
1747/// a mathematical sense) the problem of reduction across warp masters in
1748/// a block to the problem of warp reduction.
1749///
1750///
1751/// Inter-Team Reduction
1752///
1753/// Once a team has reduced its data to a single value, it is stored in
1754/// a global scratchpad array. Since each team has a distinct slot, this
1755/// can be done without locking.
1756///
1757/// The last team to write to the scratchpad array proceeds to reduce the
1758/// scratchpad array. One or more workers in the last team use the helper
1759/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
1760/// the k'th worker reduces every k'th element.
1761///
1762/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
1763/// reduce across workers and compute a globally reduced value.
1764///
1768 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
1769 if (!CGF.HaveInsertPoint())
1770 return;
1771
1772 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
1773 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
1774
1775 if (Options.SimpleReduction) {
1776 assert(!TeamsReduction && !ParallelReduction &&
1777 "Invalid reduction selection in emitReduction.");
1778 (void)ParallelReduction;
1779 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
1780 ReductionOps, Options);
1781 return;
1782 }
1783
1784 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
1785 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
1786 int Cnt = 0;
1787 for (const Expr *DRE : Privates) {
1788 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
1789 ++Cnt;
1790 }
1791 const RecordDecl *ReductionRec = ::buildRecordForGlobalizedVars(
1792 CGM.getContext(), PrivatesReductions, {}, VarFieldMap, 1);
1793
1794 // The atomic cross-team reduction fast path is opt-in. Hand each eligible
1795 // scalar reduction an atomic combiner; createReductionsGPU uses the atomic
1796 // path only if every reduction in the set has one. Track whether that holds
1797 // so we can skip the (then unused) per-team buffer registration.
1798 bool UseAtomicReduction =
1799 TeamsReduction && CGM.getLangOpts().OpenMPTargetAtomicReduction;
1800 bool AllAtomicable = UseAtomicReduction;
1801
1802 // Source location for the ident struct
1803 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1804
1805 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1806 InsertPointTy AllocaIP(CGF.AllocaInsertPt->getIterator());
1807 InsertPointTy CodeGenIP(CGF.Builder.GetInsertPoint());
1808 llvm::OpenMPIRBuilder::LocationDescription OmpLoc(
1809 CodeGenIP, CGF.SourceLocToDebugLoc(Loc));
1811
1813 unsigned Idx = 0;
1814 for (const Expr *Private : Privates) {
1815 llvm::Type *ElementType;
1816 llvm::Value *Variable;
1817 llvm::Value *PrivateVariable;
1818 llvm::OpenMPIRBuilder::ReductionGenAtomicCBTy AtomicReductionGen = nullptr;
1819 ElementType = CGF.ConvertTypeForMem(Private->getType());
1820 const auto *RHSVar =
1821 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[Idx])->getDecl());
1822 PrivateVariable = CGF.GetAddrOfLocalVar(RHSVar).emitRawPointer(CGF);
1823 const auto *LHSVar =
1824 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[Idx])->getDecl());
1825 Variable = CGF.GetAddrOfLocalVar(LHSVar).emitRawPointer(CGF);
1826 llvm::OpenMPIRBuilder::EvalKind EvalKind;
1827 switch (CGF.getEvaluationKind(Private->getType())) {
1828 case TEK_Scalar:
1829 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Scalar;
1830 break;
1831 case TEK_Complex:
1832 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Complex;
1833 break;
1834 case TEK_Aggregate:
1835 EvalKind = llvm::OpenMPIRBuilder::EvalKind::Aggregate;
1836 break;
1837 }
1838 auto ReductionGen = [&](InsertPointTy CodeGenIP, unsigned I,
1839 llvm::Value **LHSPtr, llvm::Value **RHSPtr,
1840 llvm::Function *NewFunc) {
1841 CGF.Builder.restoreIP(CodeGenIP);
1842 auto *CurFn = CGF.CurFn;
1843 CGF.CurFn = NewFunc;
1844
1845 const bool DisableDebugInfo = !NewFunc->getSubprogram();
1846 llvm::DebugLoc SavedDebugLoc;
1847 if (DisableDebugInfo) {
1848 // The helper has no DISubprogram of its own, so a debug location here
1849 // would name the enclosing function's scope, which is invalid IR.
1850 // Suppress them, as the other OpenMPIRBuilder-generated helpers do.
1851 SavedDebugLoc = CGF.Builder.getCurrentDebugLocation();
1852 CGF.Builder.SetCurrentDebugLocation({});
1853 CGF.disableDebugInfo();
1854 }
1855
1856 *LHSPtr = CGF.GetAddrOfLocalVar(
1857 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()))
1858 .emitRawPointer(CGF);
1859 *RHSPtr = CGF.GetAddrOfLocalVar(
1860 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()))
1861 .emitRawPointer(CGF);
1862
1863 emitSingleReductionCombiner(CGF, ReductionOps[I], Privates[I],
1864 cast<DeclRefExpr>(LHSExprs[I]),
1865 cast<DeclRefExpr>(RHSExprs[I]));
1866
1867 if (DisableDebugInfo) {
1868 CGF.enableDebugInfo();
1869 CGF.Builder.SetCurrentDebugLocation(SavedDebugLoc);
1870 }
1871
1872 CGF.CurFn = CurFn;
1873 return CGF.Builder.GetInsertPoint();
1874 };
1875
1876 // For the atomic fast path, hand this reduction an atomic combiner if it is
1877 // a scalar with a direct atomicrmw; otherwise the set is not fully
1878 // atomicable and falls back to the buffer path.
1879 if (UseAtomicReduction) {
1880 std::optional<llvm::AtomicRMWInst::BinOp> AtomicOp;
1881 if (EvalKind == llvm::OpenMPIRBuilder::EvalKind::Scalar) {
1882 if (std::optional<BinaryOperatorKind> BOK =
1883 getReductionBinOpKind(ReductionOps[Idx]))
1884 AtomicOp = getReductionAtomicRMWOp(*BOK, Private->getType());
1885 }
1886 if (!AtomicOp) {
1887 AllAtomicable = false;
1888 } else {
1889 llvm::AtomicRMWInst::BinOp Op = *AtomicOp;
1890 llvm::Align Alignment =
1891 CGM.getModule().getDataLayout().getPrefTypeAlign(ElementType);
1892 // Device (agent) scope suffices: all teams accumulate on-device and the
1893 // host reads the result only after the kernel (via map-back), so the
1894 // far costlier system scope is unnecessary. The
1895 // no.fine.grained/no.remote memory metadata is omitted so the atomic
1896 // stays correct under USM.
1897 llvm::SyncScope::ID SSID = CGF.getTargetHooks().getLLVMSyncScopeID(
1899 llvm::AtomicOrdering::Monotonic, CGF.getLLVMContext());
1900 AtomicReductionGen = [Op, Alignment,
1901 SSID](InsertPointTy IP, llvm::Type *EltTy,
1902 llvm::Value *LHS, llvm::Value *RHS)
1903 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1904 llvm::IRBuilder<> Builder(IP);
1905 llvm::Value *Val = Builder.CreateLoad(EltTy, RHS);
1906 Builder.CreateAtomicRMW(Op, LHS, Val, Alignment,
1907 llvm::AtomicOrdering::Monotonic, SSID);
1908 return Builder.GetInsertPoint();
1909 };
1910 }
1911 }
1912
1913 ReductionInfos.emplace_back(llvm::OpenMPIRBuilder::ReductionInfo(
1914 ElementType, Variable, PrivateVariable, EvalKind,
1915 /*ReductionGen=*/nullptr, ReductionGen, AtomicReductionGen,
1916 /*DataPtrPtrGen=*/nullptr));
1917 Idx++;
1918 }
1919
1920 // The atomic path folds directly into the mapped variable and needs no
1921 // per-team buffer; register the record for buffer allocation otherwise.
1922 if (TeamsReduction && !AllAtomicable)
1923 TeamsReductions.push_back(ReductionRec);
1924
1925 bool IsSPMD = getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD;
1926 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
1927 cantFail(OMPBuilder.createReductionsGPU(
1928 OmpLoc, AllocaIP, CodeGenIP, ReductionInfos, /*IsByRef=*/{}, false,
1929 TeamsReduction, IsSPMD,
1930 llvm::OpenMPIRBuilder::ReductionGenCBKind::Clang,
1931 CGF.getTarget().getGridValue(), RTLoc));
1932 CGF.Builder.restoreIP(AfterIP);
1933}
1934
1935const VarDecl *
1937 const VarDecl *NativeParam) const {
1938 if (!NativeParam->getType()->isReferenceType())
1939 return NativeParam;
1940 QualType ArgType = NativeParam->getType();
1942 const Type *NonQualTy = QC.strip(ArgType);
1943 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
1944 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
1945 if (Attr->getCaptureKind() == OMPC_map) {
1946 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
1948 }
1949 }
1950 ArgType = CGM.getContext().getPointerType(PointeeTy);
1951 QC.addRestrict();
1952 ArgType = QC.apply(CGM.getContext(), ArgType);
1953 if (isa<ImplicitParamDecl>(NativeParam))
1955 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
1957 return ParmVarDecl::Create(
1958 CGM.getContext(),
1959 const_cast<DeclContext *>(NativeParam->getDeclContext()),
1960 NativeParam->getBeginLoc(), NativeParam->getLocation(),
1961 NativeParam->getIdentifier(), ArgType,
1962 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
1963}
1964
1965Address
1967 const VarDecl *NativeParam,
1968 const VarDecl *TargetParam) const {
1969 assert(NativeParam != TargetParam &&
1970 NativeParam->getType()->isReferenceType() &&
1971 "Native arg must not be the same as target arg.");
1972 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
1973 QualType NativeParamType = NativeParam->getType();
1975 const Type *NonQualTy = QC.strip(NativeParamType);
1976 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
1977 unsigned NativePointeeAddrSpace =
1978 CGF.getTypes().getTargetAddressSpace(NativePointeeTy);
1979 QualType TargetTy = TargetParam->getType();
1980 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(LocalAddr, /*Volatile=*/false,
1981 TargetTy, SourceLocation());
1982 // Cast to native address space.
1984 TargetAddr,
1985 llvm::PointerType::get(CGF.getLLVMContext(), NativePointeeAddrSpace));
1986 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
1987 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
1988 NativeParamType);
1989 return NativeParamAddr;
1990}
1991
1993 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
1994 ArrayRef<llvm::Value *> Args) const {
1996 TargetArgs.reserve(Args.size());
1997 auto *FnType = OutlinedFn.getFunctionType();
1998 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
1999 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
2000 TargetArgs.append(std::next(Args.begin(), I), Args.end());
2001 break;
2002 }
2003 llvm::Type *TargetType = FnType->getParamType(I);
2004 llvm::Value *NativeArg = Args[I];
2005 if (!TargetType->isPointerTy()) {
2006 TargetArgs.emplace_back(NativeArg);
2007 continue;
2008 }
2009 TargetArgs.emplace_back(
2010 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(NativeArg, TargetType));
2011 }
2012 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
2013}
2014
2015/// Emit function which wraps the outline parallel region
2016/// and controls the arguments which are passed to this function.
2017/// The wrapper ensures that the outlined function is called
2018/// with the correct arguments when data is shared.
2019llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
2020 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
2021 ASTContext &Ctx = CGM.getContext();
2022 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
2023
2024 // Create a function that takes as argument the source thread.
2025 FunctionArgList WrapperArgs;
2026 QualType Int16QTy =
2027 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
2028 QualType Int32QTy =
2029 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
2030 auto *ParallelLevelArg = ImplicitParamDecl::Create(
2031 Ctx, /*DC=*/nullptr, D.getBeginLoc(),
2032 /*Id=*/nullptr, Int16QTy, ImplicitParamKind::Other);
2033 auto *WrapperArg = ImplicitParamDecl::Create(
2034 Ctx, /*DC=*/nullptr, D.getBeginLoc(),
2035 /*Id=*/nullptr, Int32QTy, ImplicitParamKind::Other);
2036 WrapperArgs.emplace_back(ParallelLevelArg);
2037 WrapperArgs.emplace_back(WrapperArg);
2038
2039 const CGFunctionInfo &CGFI =
2041
2042 auto *Fn = llvm::Function::Create(
2043 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2044 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
2045
2046 // Ensure we do not inline the function. This is trivially true for the ones
2047 // passed to __kmpc_fork_call but the ones calles in serialized regions
2048 // could be inlined. This is not a perfect but it is closer to the invariant
2049 // we want, namely, every data environment starts with a new function.
2050 // TODO: We should pass the if condition to the runtime function and do the
2051 // handling there. Much cleaner code.
2052 Fn->addFnAttr(llvm::Attribute::NoInline);
2053
2055 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2056
2057 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2058 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
2059 D.getBeginLoc(), D.getBeginLoc());
2060
2061 const auto *RD = CS.getCapturedRecordDecl();
2062 auto CurField = RD->field_begin();
2063
2064 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2065 /*Name=*/".zero.addr");
2066 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
2067 // Get the array of arguments.
2069
2070 Args.emplace_back(CGF.GetAddrOfLocalVar(WrapperArg).emitRawPointer(CGF));
2071 Args.emplace_back(ZeroAddr.emitRawPointer(CGF));
2072
2073 CGBuilderTy &Bld = CGF.Builder;
2074 auto CI = CS.capture_begin();
2075
2076 // Use global memory for data sharing.
2077 // Handle passing of global args to workers.
2078 RawAddress GlobalArgs =
2079 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
2080 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
2081 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
2082 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2083 CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
2084 DataSharingArgs);
2085
2086 // Retrieve the shared variables from the list of references returned
2087 // by the runtime. Pass the variables to the outlined function.
2088 Address SharedArgListAddress = Address::invalid();
2089 if (CS.capture_size() > 0 ||
2090 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
2091 SharedArgListAddress = CGF.EmitLoadOfPointer(
2092 GlobalArgs, CGF.getContext()
2094 .castAs<PointerType>());
2095 }
2096 unsigned Idx = 0;
2097 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
2098 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
2100 Src, Bld.getPtrTy(0), CGF.SizeTy);
2101 llvm::Value *LB = CGF.EmitLoadOfScalar(
2102 TypedAddress,
2103 /*Volatile=*/false,
2105 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
2106 Args.emplace_back(LB);
2107 ++Idx;
2108 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
2109 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(Src, Bld.getPtrTy(0),
2110 CGF.SizeTy);
2111 llvm::Value *UB = CGF.EmitLoadOfScalar(
2112 TypedAddress,
2113 /*Volatile=*/false,
2115 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
2116 Args.emplace_back(UB);
2117 ++Idx;
2118 }
2119 if (CS.capture_size() > 0) {
2120 ASTContext &CGFContext = CGF.getContext();
2121 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
2122 QualType ElemTy = CurField->getType();
2123 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
2125 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)),
2126 CGF.ConvertTypeForMem(ElemTy));
2127 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
2128 /*Volatile=*/false,
2129 CGFContext.getPointerType(ElemTy),
2130 CI->getLocation());
2131 if (CI->capturesVariableByCopy() &&
2132 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
2133 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
2134 CI->getLocation());
2135 }
2136 Args.emplace_back(Arg);
2137 }
2138 }
2139
2140 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
2141 CGF.FinishFunction();
2142 return Fn;
2143}
2144
2146 const Decl *D) {
2147 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
2148 return;
2149
2150 assert(D && "Expected function or captured|block decl.");
2151 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
2152 "Function is registered already.");
2153 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
2154 "Team is set but not processed.");
2155 const Stmt *Body = nullptr;
2156 bool NeedToDelayGlobalization = false;
2157 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2158 Body = FD->getBody();
2159 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2160 Body = BD->getBody();
2161 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
2162 Body = CD->getBody();
2163 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
2164 if (NeedToDelayGlobalization &&
2165 getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
2166 return;
2167 }
2168 if (!Body)
2169 return;
2170 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
2171 VarChecker.Visit(Body);
2172 const RecordDecl *GlobalizedVarsRecord =
2173 VarChecker.getGlobalizedRecord(IsInTTDRegion);
2174 TeamAndReductions.first = nullptr;
2175 TeamAndReductions.second.clear();
2176 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
2177 VarChecker.getEscapedVariableLengthDecls();
2178 ArrayRef<const ValueDecl *> DelayedVariableLengthDecls =
2179 VarChecker.getDelayedVariableLengthDecls();
2180 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty() &&
2181 DelayedVariableLengthDecls.empty())
2182 return;
2183 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2184 I->getSecond().MappedParams =
2185 std::make_unique<CodeGenFunction::OMPMapVars>();
2186 I->getSecond().EscapedParameters.insert(
2187 VarChecker.getEscapedParameters().begin(),
2188 VarChecker.getEscapedParameters().end());
2189 I->getSecond().EscapedVariableLengthDecls.append(
2190 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
2191 I->getSecond().DelayedVariableLengthDecls.append(
2192 DelayedVariableLengthDecls.begin(), DelayedVariableLengthDecls.end());
2193 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2194 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
2195 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
2196 Data.try_emplace(VD);
2197 }
2198 if (!NeedToDelayGlobalization) {
2199 emitGenericVarsProlog(CGF, D->getBeginLoc());
2200 struct GlobalizationScope final : EHScopeStack::Cleanup {
2201 GlobalizationScope() = default;
2202
2203 void Emit(CodeGenFunction &CGF, Flags flags) override {
2204 static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
2205 .emitGenericVarsEpilog(CGF);
2206 }
2207 };
2208 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
2209 }
2210}
2211
2213 const VarDecl *VD) {
2214 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
2215 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2216 auto AS = LangAS::Default;
2217 switch (A->getAllocatorType()) {
2218 case OMPAllocateDeclAttr::OMPNullMemAlloc:
2219 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
2220 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
2221 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
2222 break;
2223 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
2224 return Address::invalid();
2225 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
2226 // TODO: implement aupport for user-defined allocators.
2227 return Address::invalid();
2228 case OMPAllocateDeclAttr::OMPConstMemAlloc:
2230 break;
2231 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
2233 break;
2234 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
2235 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
2236 break;
2237 }
2238 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
2239 auto *GV = new llvm::GlobalVariable(
2240 CGM.getModule(), VarTy, /*isConstant=*/false,
2241 llvm::GlobalValue::InternalLinkage, llvm::PoisonValue::get(VarTy),
2242 VD->getName(),
2243 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
2244 CGM.getContext().getTargetAddressSpace(AS));
2245 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2246 GV->setAlignment(Align.getAsAlign());
2247 return Address(
2249 GV, CGF.Builder.getPtrTy(CGM.getContext().getTargetAddressSpace(
2250 VD->getType().getAddressSpace()))),
2251 VarTy, Align);
2252 }
2253
2254 if (getDataSharingMode() != CGOpenMPRuntimeGPU::DS_Generic)
2255 return Address::invalid();
2256
2257 VD = VD->getCanonicalDecl();
2258 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2259 if (I == FunctionGlobalizedDecls.end())
2260 return Address::invalid();
2261 auto VDI = I->getSecond().LocalVarData.find(VD);
2262 if (VDI != I->getSecond().LocalVarData.end())
2263 return VDI->second.PrivateAddr;
2264 if (VD->hasAttrs()) {
2266 E(VD->attr_end());
2267 IT != E; ++IT) {
2268 auto VDI = I->getSecond().LocalVarData.find(
2269 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
2270 ->getCanonicalDecl());
2271 if (VDI != I->getSecond().LocalVarData.end())
2272 return VDI->second.PrivateAddr;
2273 }
2274 }
2275
2276 return Address::invalid();
2277}
2278
2280 FunctionGlobalizedDecls.erase(CGF.CurFn);
2282}
2283
2285 CodeGenFunction &CGF, const OMPLoopDirective &S,
2286 OpenMPDistScheduleClauseKind &ScheduleKind,
2287 llvm::Value *&Chunk) const {
2288 auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2289 if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
2290 ScheduleKind = OMPC_DIST_SCHEDULE_static;
2291 Chunk = CGF.EmitScalarConversion(
2292 RT.getGPUNumThreads(CGF),
2293 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2294 S.getIterationVariable()->getType(), S.getBeginLoc());
2295 return;
2296 }
2298 CGF, S, ScheduleKind, Chunk);
2299}
2300
2302 CodeGenFunction &CGF, const OMPLoopDirective &S,
2303 OpenMPScheduleClauseKind &ScheduleKind,
2304 const Expr *&ChunkExpr) const {
2305 ScheduleKind = OMPC_SCHEDULE_static;
2306 // Chunk size is 1 in this case.
2307 llvm::APInt ChunkSize(32, 1);
2308 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
2309 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2310 SourceLocation());
2311}
2312
2314 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
2315 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
2316 " Expected target-based directive.");
2317 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
2318 for (const CapturedStmt::Capture &C : CS->captures()) {
2319 // Capture variables captured by reference in lambdas for target-based
2320 // directives.
2321 if (!C.capturesVariable())
2322 continue;
2323 const VarDecl *VD = C.getCapturedVar();
2324 const auto *RD = VD->getType()
2328 if (!RD || !RD->isLambda())
2329 continue;
2330 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
2331 LValue VDLVal;
2333 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
2334 else
2335 VDLVal = CGF.MakeAddrLValue(
2336 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
2337 llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
2338 FieldDecl *ThisCapture = nullptr;
2339 RD->getCaptureFields(Captures, ThisCapture);
2340 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
2341 LValue ThisLVal =
2342 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
2343 llvm::Value *CXXThis = CGF.LoadCXXThis();
2344 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
2345 }
2346 for (const LambdaCapture &LC : RD->captures()) {
2347 if (LC.getCaptureKind() != LCK_ByRef)
2348 continue;
2349 const ValueDecl *VD = LC.getCapturedVar();
2350 // FIXME: For now VD is always a VarDecl because OpenMP does not support
2351 // capturing structured bindings in lambdas yet.
2352 if (!CS->capturesVariable(cast<VarDecl>(VD)))
2353 continue;
2354 auto It = Captures.find(VD);
2355 assert(It != Captures.end() && "Found lambda capture without field.");
2356 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
2357 Address VDAddr = CGF.GetAddrOfLocalVar(cast<VarDecl>(VD));
2359 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
2360 VD->getType().getCanonicalType())
2361 .getAddress();
2362 CGF.EmitStoreOfScalar(VDAddr.emitRawPointer(CGF), VarLVal);
2363 }
2364 }
2365}
2366
2368 LangAS &AS) {
2369 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
2370 return false;
2371 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2372 switch(A->getAllocatorType()) {
2373 case OMPAllocateDeclAttr::OMPNullMemAlloc:
2374 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
2375 // Not supported, fallback to the default mem space.
2376 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
2377 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
2378 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
2379 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
2380 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
2381 AS = LangAS::Default;
2382 return true;
2383 case OMPAllocateDeclAttr::OMPConstMemAlloc:
2385 return true;
2386 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
2388 return true;
2389 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
2390 llvm_unreachable("Expected predefined allocator for the variables with the "
2391 "static storage.");
2392 }
2393 return false;
2394}
2395
2396/// Check to see if target architecture supports unified addressing which is
2397/// a restriction for OpenMP requires clause "unified_shared_memory".
2399 StringRef CPU = CGM.getTarget().getTargetOpts().CPU;
2400 if (CGM.getTarget().getTriple().isNVPTX() &&
2401 !llvm::NVPTX::supportsUnifiedAddressing(llvm::NVPTX::parseArch(CPU))) {
2402 for (const OMPClause *Clause : D->clauselists()) {
2403 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
2404 CGM.getDiags().Report(Clause->getBeginLoc(),
2405 diag::err_omp_unified_shared_memory_unsupported)
2406 << CPU;
2407 return;
2408 }
2409 }
2410 }
2411
2413}
2414
2416 CGBuilderTy &Bld = CGF.Builder;
2417 llvm::Module *M = &CGF.CGM.getModule();
2418 const char *LocSize = "__kmpc_get_hardware_num_threads_in_block";
2419 llvm::Function *F = M->getFunction(LocSize);
2420 if (!F) {
2421 F = llvm::Function::Create(llvm::FunctionType::get(CGF.Int32Ty, {}, false),
2422 llvm::GlobalVariable::ExternalLinkage, LocSize,
2423 &CGF.CGM.getModule());
2424 }
2425 return Bld.CreateCall(F, {}, "nvptx_num_threads");
2426}
2427
2430 return CGF.EmitRuntimeCall(
2431 OMPBuilder.getOrCreateRuntimeFunction(
2432 CGM.getModule(), OMPRTL___kmpc_get_hardware_thread_id_in_block),
2433 Args);
2434}
#define V(N, I)
static std::optional< BinaryOperatorKind > getReductionBinOpKind(const Expr *ReductionOp)
Extracts the built-in reduction operator from a combiner of the form x = x / <op> rhs (or the min/max...
static void getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D, llvm::SmallVectorImpl< const ValueDecl * > &Vars)
Get list of reduction variables from the teams ... directives.
static llvm::Value * castValueToType(CodeGenFunction &CGF, llvm::Value *Val, QualType ValTy, QualType CastTy, SourceLocation Loc)
Cast value to the specified type.
static void getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D, llvm::SmallVectorImpl< const ValueDecl * > &Vars)
Get list of lastprivate variables from the teams distribute ... or teams {distribute ....
static bool hasNestedSPMDDirective(ASTContext &Ctx, const OMPExecutableDirective &D)
Check for inner (nested) SPMD construct, if any.
static bool supportsSPMDExecutionMode(ASTContext &Ctx, const OMPExecutableDirective &D)
static std::optional< llvm::AtomicRMWInst::BinOp > getReductionAtomicRMWOp(BinaryOperatorKind BOK, QualType Ty)
Maps a built-in reduction operator to an atomicrmw opcode for the atomic cross-team reduction fast pa...
This file defines OpenMP nodes for declarative directives.
This file defines OpenMP AST classes for clauses.
static std::pair< ValueDecl *, bool > getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, SourceRange &ERange, bool AllowArraySection=false, bool AllowAssumedSizeArray=false, StringRef DiagType="")
This file defines OpenMP AST classes for executable directives and clauses.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4805
This is a common base class for loop directives ('omp simd', 'omp for', 'omp for simd' etc....
Expr * getIterationVariable() const
This represents 'ompx_bare' clause in the 'pragma omp target teams ...' directive.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
Attr - This represents one attribute.
Definition Attr.h:47
ArrayRef< Capture > captures() const
Definition Decl.h:4986
const BlockDecl * getBlockDecl() const
Definition Expr.h:6770
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
Describes the capture of either a variable, or 'this', or variable-length array type.
Definition Stmt.h:3963
This captures a statement into a function.
Definition Stmt.h:3950
bool capturesVariable(const VarDecl *Var) const
True if this variable has been captured.
Definition Stmt.cpp:1517
capture_range captures()
Definition Stmt.h:4088
CastKind getCastKind() const
Definition Expr.h:3789
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:156
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:223
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition CGBuilder.h:261
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = T* ... produce name = getelementptr inbounds addr, i64 index where i64 is actually the t...
Definition CGBuilder.h:281
CGFunctionInfo - Class to encapsulate the information about a function definition.
llvm::Function * emitTeamsOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override
Emits inlined function for the specified OpenMP teams.
void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc) override
Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32global_tid, int proc_bind) to generate...
void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > Privates, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, ArrayRef< const Expr * > ReductionOps, ReductionOptionsTy Options) override
Emit a code for reduction clause.
DataSharingMode
Target codegen is specialized based on two data-sharing modes: CUDA, in which the local variables are...
@ DS_Generic
Generic data-sharing mode.
void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const override
Choose a default value for the dist_schedule clause.
Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD) override
Gets the OpenMP-specific address of the local variable.
void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) override
Emits OpenMP-specific function prolog.
void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const override
Choose a default value for the schedule clause.
void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) override
This function ought to emit, in the general case, a call to.
void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint=nullptr) override
Emits a critical region.
void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars) override
Emits code for teams call of the OutlinedFn with variables captured in a record which address is stor...
bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS) override
Checks if the variable has associated OMPAllocateDeclAttr attribute with the predefined allocator and...
void getKmpcFreeShared(CodeGenFunction &CGF, const std::pair< llvm::Value *, llvm::Value * > &AddrSizePair) override
Get call to __kmpc_free_shared.
llvm::Function * emitParallelOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override
Emits inlined function for the specified OpenMP parallel.
void functionFinished(CodeGenFunction &CGF) override
Cleans up references to the objects in finished function.
llvm::Value * getGPUThreadID(CodeGenFunction &CGF)
Get the id of the current thread on the GPU.
void processRequiresDirective(const OMPRequiresDecl *D) override
Perform check on requires decl to ensure that target architecture supports unified addressing.
bool isDelayedVariableLengthDecl(CodeGenFunction &CGF, const VarDecl *VD) const override
Declare generalized virtual functions which need to be defined by all specializations of OpenMPGPURun...
void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef< llvm::Value * > Args={}) const override
Emits call of the outlined function with the provided arguments, translating these arguments to corre...
Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const override
Gets the address of the native argument basing on the address of the target-specific parameter.
ExecutionMode
Defines the execution mode.
@ EM_NonSPMD
Non-SPMD execution mode (1 master thread, others are workers).
@ EM_Unknown
Unknown execution mode (orphaned directive).
@ EM_SPMD
SPMD execution mode (all threads are worker threads).
void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks=true, bool ForceSimpleCall=false) override
Emit an implicit/explicit barrier for OpenMP threads.
llvm::Value * getGPUNumThreads(CodeGenFunction &CGF)
Get the maximum number of threads in a block of the GPU.
const VarDecl * translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const override
Translates the native parameter of outlined function if this is required for target.
std::pair< llvm::Value *, llvm::Value * > getKmpcAllocShared(CodeGenFunction &CGF, const VarDecl *VD) override
Get call to __kmpc_alloc_shared.
bool isGPU() const override
Returns true if the current target is a GPU.
llvm::Value * emitSeverityClause(OpenMPSeverityClauseKind Severity, SourceLocation Loc) override
llvm::Value * emitMessageClause(CodeGenFunction &CGF, const Expr *Message, SourceLocation Loc) override
void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef< llvm::Value * > CapturedVars, const Expr *IfCond, llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier=OMPC_NUMTHREADS_unknown, OpenMPSeverityClauseKind Severity=OMPC_SEVERITY_fatal, const Expr *Message=nullptr) override
Emits code for parallel or serial call of the OutlinedFn with variables captured in a record which ad...
void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc, OpenMPNumThreadsClauseModifier Modifier=OMPC_NUMTHREADS_unknown, OpenMPSeverityClauseKind Severity=OMPC_SEVERITY_fatal, SourceLocation SeverityLoc=SourceLocation(), const Expr *Message=nullptr, SourceLocation MessageLoc=SourceLocation()) override
Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32global_tid, kmp_int32 num_threads) ...
void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const override
Adjust some parameters for the target-based directives, like addresses of the variables captured by r...
virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc)
Emits address of the word in a memory where current thread id is stored.
static const Stmt * getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body)
Checks if the Body is the CompoundStmt and returns its child statement iff there is only one that is ...
llvm::Value * emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, unsigned Flags=0, bool EmitLoc=false)
Emits object of ident_t type with info for source location.
virtual void functionFinished(CodeGenFunction &CGF)
Cleans up references to the objects in finished function.
virtual llvm::Function * emitTeamsOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP teams directive D.
llvm::OpenMPIRBuilder OMPBuilder
An OpenMP-IR-Builder instance.
virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen)
Helper to emit outlined function for 'target' directive.
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void processRequiresDirective(const OMPRequiresDecl *D)
Perform check on requires decl to ensure that target architecture supports unified addressing.
llvm::Value * getThreadID(CodeGenFunction &CGF, SourceLocation Loc)
Gets thread id value for the current thread.
void computeMinAndMaxThreadsAndTeams(const OMPExecutableDirective &D, CodeGenFunction &CGF, llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs)
Helper to determine the min/max number of threads/teams for D.
static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind)
Returns default flags for the barriers depending on the directive, for which this barier is going to ...
virtual llvm::Function * emitParallelOutlinedFunction(CodeGenFunction &CGF, const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen)
Emits outlined function for the specified OpenMP parallel directive D.
virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const
Choose default schedule type and chunk value for the dist_schedule clause.
llvm::Type * getIdentTyPointerTy()
Returns pointer to ident_t type.
void emitSingleReductionCombiner(CodeGenFunction &CGF, const Expr *ReductionOp, const Expr *PrivateRef, const DeclRefExpr *LHS, const DeclRefExpr *RHS)
Emits single reduction combiner.
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint=nullptr)
Emits a critical region.
virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef< llvm::Value * > Args={}) const
Emits call of the outlined function with the provided arguments, translating these arguments to corre...
virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef< const Expr * > Privates, ArrayRef< const Expr * > LHSExprs, ArrayRef< const Expr * > RHSExprs, ArrayRef< const Expr * > ReductionOps, ReductionOptionsTy Options)
Emit a code for reduction clause.
The scope used to remap some variables as private in the OpenMP loop body (or other captured region e...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3444
CGCapturedStmtInfo * CapturedStmtInfo
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
Definition CGExpr.cpp:3453
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:187
const TargetInfo & getTarget() const
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:244
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:6139
const TargetCodeGenInfo & getTargetHooks() const
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:236
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertTypeForMem(QualType T)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:679
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:200
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:659
This class organizes the cross-function state that is used while generating LLVM code.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
llvm::Module & getModule() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
ASTContext & getContext() const
llvm::LLVMContext & getLLVMContext()
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2098
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition CGCall.cpp:774
unsigned getTargetAddressSpace(QualType T) const
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
Address getAddress() const
Definition CGValue.h:373
A basic class for pre|post-action for advanced codegen sequence for OpenMP region.
An abstract representation of an aligned address.
Definition Address.h:42
llvm::Value * getPointer() const
Definition Address.h:66
Class provides a way to call simple version of codegen for OpenMP region, or an advanced with possibl...
void setAction(PrePostActionTy &Action) const
llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, SyncScope Scope, llvm::AtomicOrdering Ordering, llvm::LLVMContext &Ctx) const
Get the syncscope used in LLVM IR as a SyncScope ID.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
void addDecl(Decl *D)
Add the declaration D into this context.
ValueDecl * getDecl()
Definition Expr.h:1383
decl_range decls()
Definition Stmt.h:1690
T * getAttr() const
Definition DeclBase.h:582
bool hasAttrs() const
Definition DeclBase.h:527
attr_iterator attr_end() const
Definition DeclBase.h:551
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1002
attr_iterator attr_begin() const
Definition DeclBase.h:548
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
AttrVec & getAttrs()
Definition DeclBase.h:533
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3341
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4805
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5712
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
Describes the capture of a variable or of this, or of a C++1y init-capture.
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1390
capture_range captures() const
Retrieve this lambda's captures.
Definition ExprCXX.cpp:1403
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
This is a basic class for representing single OpenMP clause.
This represents 'pragma omp requires...' directive.
Definition DeclOpenMP.h:479
clauselist_range clauselists()
Definition DeclOpenMP.h:504
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2965
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getCanonicalType() const
Definition TypeBase.h:8630
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8518
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8525
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4989
Represents a struct/union/class.
Definition Decl.h:4506
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5402
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5017
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:762
virtual const llvm::omp::GV & getGridValue() const
The base class of the type hierarchy.
Definition TypeBase.h:1879
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isReferenceType() const
Definition TypeBase.h:8839
bool isLValueReferenceType() const
Definition TypeBase.h:8843
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2438
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isFloatingType() const
Definition Type.cpp:2519
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5697
Represents a variable declaration or definition.
Definition Decl.h:934
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2240
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
Privates[]
This class represents the 'transparent' clause in the 'pragma omp task' directive.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
bool isOpenMPDistributeDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a distribute directive.
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ AS_public
Definition Specifiers.h:128
@ CR_OpenMP
bool isOpenMPParallelDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a parallel-kind directive.
bool isOpenMPPrivate(OpenMPClauseKind Kind)
Checks if the specified clause is one of private clauses like 'private', 'firstprivate',...
@ SC_None
Definition Specifiers.h:254
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
bool isOpenMPTargetExecutionDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a target code offload directive.
bool isOpenMPTeamsDirective(OpenMPDirectiveKind DKind)
Checks if the specified directive is a teams-kind directive.
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
bool isOpenMPLoopBoundSharingDirective(OpenMPDirectiveKind Kind)
Checks if the specified directive kind is one of the composite or combined directives that need loop ...
LangAS
Defines the address space values used by the address space qualifier of QualType.
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition OpenMPKinds.h:25
void getOpenMPCaptureRegions(llvm::SmallVectorImpl< OpenMPDirectiveKind > &CaptureRegions, OpenMPDirectiveKind DKind)
Return the captured regions of an OpenMP directive.
OpenMPNumThreadsClauseModifier
U cast(CodeGen::Address addr)
Definition Address.h:327
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1775
@ Other
Other implicit parameter.
Definition Decl.h:1787
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition OpenMPKinds.h:31
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t