1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides a class for OpenMP runtime code generation.
12 //===----------------------------------------------------------------------===//
15 #include "CGCleanup.h"
16 #include "CGOpenMPRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "ConstantBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Value.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/raw_ostream.h"
31 using namespace clang;
32 using namespace CodeGen;
35 /// \brief Base class for handling code generation inside OpenMP regions.
36 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
48 /// \brief Region with outlined function for standalone 'target' directive.
52 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
54 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
57 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
60 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
63 Kind(Kind), HasCancel(HasCancel) {}
65 /// \brief Get a variable or parameter for storing global thread id
66 /// inside OpenMP construct.
67 virtual const VarDecl *getThreadIDVariable() const = 0;
69 /// \brief Emit the captured statement body.
70 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
72 /// \brief Get an LValue for the current ThreadID variable.
73 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
76 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
80 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82 bool hasCancel() const { return HasCancel; }
84 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
88 ~CGOpenMPRegionInfo() override = default;
91 CGOpenMPRegionKind RegionKind;
92 RegionCodeGenTy CodeGen;
93 OpenMPDirectiveKind Kind;
97 /// \brief API for captured statement code generation in OpenMP constructs.
98 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
101 const RegionCodeGenTy &CodeGen,
102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
114 /// \brief Get the name of the capture helper.
115 StringRef getHelperName() const override { return HelperName; }
117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
124 /// \brief A variable or parameter storing global thread id for OpenMP
126 const VarDecl *ThreadIDVar;
127 StringRef HelperName;
130 /// \brief API for captured statement code generation in OpenMP constructs.
131 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
133 class UntiedTaskActionTy final : public PrePostActionTy {
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
181 const VarDecl *ThreadIDVar,
182 const RegionCodeGenTy &CodeGen,
183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
186 ThreadIDVar(ThreadIDVar), Action(Action) {
187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
194 /// \brief Get an LValue for the current ThreadID variable.
195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
211 /// \brief A variable or parameter storing global thread id for OpenMP
213 const VarDecl *ThreadIDVar;
214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
218 /// \brief API for inlined captured statement code generation in OpenMP
220 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
223 const RegionCodeGenTy &CodeGen,
224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
229 // \brief Retrieve the value of the context parameter.
230 llvm::Value *getContextValue() const override {
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
236 void setContextValue(llvm::Value *V) override {
237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
241 llvm_unreachable("No context value for inlined OpenMP region");
244 /// \brief Lookup the captured field decl for a variable.
245 const FieldDecl *lookup(const VarDecl *VD) const override {
247 return OuterRegionInfo->lookup(VD);
248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
253 FieldDecl *getThisFieldDecl() const override {
255 return OuterRegionInfo->getThisFieldDecl();
259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
261 const VarDecl *getThreadIDVariable() const override {
263 return OuterRegionInfo->getThreadIDVariable();
267 /// \brief Get the name of the capture helper.
268 StringRef getHelperName() const override {
269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
271 llvm_unreachable("No helper name for inlined OpenMP construct");
274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
276 OuterRegionInfo->emitUntiedSwitch(CGF);
279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
286 ~CGOpenMPInlinedRegionInfo() override = default;
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
294 /// \brief API for captured statement code generation in OpenMP target
295 /// constructs. For this captures, implicit parameters are used instead of the
296 /// captured fields. The name of the target region has to be unique in a given
297 /// application so it is provided by the client, because only the client has
298 /// the information to generate that.
299 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
311 /// \brief Get the name of the capture helper.
312 StringRef getHelperName() const override { return HelperName; }
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
320 StringRef HelperName;
323 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
324 llvm_unreachable("No codegen for expressions");
326 /// \brief API for generation of expressions captured in a innermost OpenMP
328 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333 /*HasCancel=*/false),
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
354 (void)PrivScope.Privatize();
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
387 /// \brief RAII for emitting code of OpenMP constructs.
388 class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
399 OpenMPDirectiveKind Kind, bool HasCancel)
401 // Start emission for the construct.
402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
420 /// \brief Values for bit flags used in the ident_t to describe the fields.
421 /// All enumeric elements are named and described in accordance with the code
422 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423 enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
442 /// \brief Describes ident structure that describes a source location.
443 /// All descriptions are taken from
444 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445 /// Original structure:
446 /// typedef struct ident {
447 /// kmp_int32 reserved_1; /**< might be used in Fortran;
449 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450 /// KMP_IDENT_KMPC identifies this union
452 /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
455 /// /* but currently used for storing
456 /// region-specific ITT */
457 /// /* contextual information. */
458 ///#endif /* USE_ITT_BUILD */
459 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
461 /// char const *psource; /**< String describing the source location.
462 /// The string is composed of semi-colon separated
463 // fields which describe the source file,
464 /// the function and a pair of line numbers that
465 /// delimit the construct.
468 enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
483 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484 /// the enum sched_type in kmp.h).
485 enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
488 OMP_sch_static_chunked = 33,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
494 /// static with chunk adjustment (e.g., simd)
495 OMP_sch_static_balanced_chunked = 45,
496 /// \brief Lower bound for 'ordered' versions.
498 OMP_ord_static_chunked = 65,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
504 OMP_sch_default = OMP_sch_static,
505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
515 enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
630 OMPRTL__kmpc_fork_teams,
631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
645 OMPRTL__kmpc_doacross_wait,
648 // Offloading related calls
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
673 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
675 class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
687 } // anonymous namespace
689 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
700 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
701 return CGF.EmitLoadOfPointerLValue(
702 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
703 getThreadIDVariable()->getType()->castAs<PointerType>());
706 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
707 if (!CGF.HaveInsertPoint())
709 // 1.2.2 OpenMP Language Terminology
710 // Structured block - An executable statement with a single entry at the
711 // top and a single exit at the bottom.
712 // The point of exit cannot be a branch out of the structured block.
713 // longjmp() and throw() must not violate the entry/exit criteria.
714 CGF.EHStack.pushTerminate();
716 CGF.EHStack.popTerminate();
719 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
720 CodeGenFunction &CGF) {
721 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
722 getThreadIDVariable()->getType(),
723 AlignmentSource::Decl);
726 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
727 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
728 IdentTy = llvm::StructType::create(
729 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
730 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
731 CGM.Int8PtrTy /* psource */, nullptr);
732 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
734 loadOffloadInfoMetadata();
737 void CGOpenMPRuntime::clear() {
738 InternalVars.clear();
741 static llvm::Function *
742 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
743 const Expr *CombinerInitializer, const VarDecl *In,
744 const VarDecl *Out, bool IsCombiner) {
745 // void .omp_combiner.(Ty *in, Ty *out);
746 auto &C = CGM.getContext();
747 QualType PtrTy = C.getPointerType(Ty).withRestrict();
748 FunctionArgList Args;
749 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
750 /*Id=*/nullptr, PtrTy);
751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
752 /*Id=*/nullptr, PtrTy);
753 Args.push_back(&OmpOutParm);
754 Args.push_back(&OmpInParm);
756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
757 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
758 auto *Fn = llvm::Function::Create(
759 FnTy, llvm::GlobalValue::InternalLinkage,
760 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
761 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
762 Fn->removeFnAttr(llvm::Attribute::NoInline);
763 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
764 CodeGenFunction CGF(CGM);
765 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
766 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
767 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
768 CodeGenFunction::OMPPrivateScope Scope(CGF);
769 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
770 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
771 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
774 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
775 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
776 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
779 (void)Scope.Privatize();
780 CGF.EmitIgnoredExpr(CombinerInitializer);
781 Scope.ForceCleanup();
782 CGF.FinishFunction();
786 void CGOpenMPRuntime::emitUserDefinedReduction(
787 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
788 if (UDRMap.count(D) > 0)
790 auto &C = CGM.getContext();
792 In = &C.Idents.get("omp_in");
793 Out = &C.Idents.get("omp_out");
795 llvm::Function *Combiner = emitCombinerOrInitializer(
796 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
797 cast<VarDecl>(D->lookup(Out).front()),
798 /*IsCombiner=*/true);
799 llvm::Function *Initializer = nullptr;
800 if (auto *Init = D->getInitializer()) {
801 if (!Priv || !Orig) {
802 Priv = &C.Idents.get("omp_priv");
803 Orig = &C.Idents.get("omp_orig");
805 Initializer = emitCombinerOrInitializer(
806 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
807 cast<VarDecl>(D->lookup(Priv).front()),
808 /*IsCombiner=*/false);
810 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
812 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
813 Decls.second.push_back(D);
817 std::pair<llvm::Function *, llvm::Function *>
818 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
819 auto I = UDRMap.find(D);
820 if (I != UDRMap.end())
822 emitUserDefinedReduction(/*CGF=*/nullptr, D);
823 return UDRMap.lookup(D);
826 // Layout information for ident_t.
827 static CharUnits getIdentAlign(CodeGenModule &CGM) {
828 return CGM.getPointerAlign();
830 static CharUnits getIdentSize(CodeGenModule &CGM) {
831 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
832 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
834 static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
835 // All the fields except the last are i32, so this works beautifully.
836 return unsigned(Field) * CharUnits::fromQuantity(4);
838 static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
839 IdentFieldIndex Field,
840 const llvm::Twine &Name = "") {
841 auto Offset = getOffsetOfIdentField(Field);
842 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
845 llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
846 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
847 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
848 assert(ThreadIDVar->getType()->isPointerType() &&
849 "thread id variable must be of type kmp_int32 *");
850 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
851 CodeGenFunction CGF(CGM, true);
852 bool HasCancel = false;
853 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
854 HasCancel = OPD->hasCancel();
855 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
856 HasCancel = OPSD->hasCancel();
857 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
858 HasCancel = OPFD->hasCancel();
859 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
860 HasCancel, getOutlinedHelperName());
861 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
862 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
865 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
866 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
867 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
868 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
869 bool Tied, unsigned &NumberOfParts) {
870 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
872 auto *ThreadID = getThreadID(CGF, D.getLocStart());
873 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
874 llvm::Value *TaskArgs[] = {
876 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
877 TaskTVar->getType()->castAs<PointerType>())
879 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
881 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
883 CodeGen.setAction(Action);
884 assert(!ThreadIDVar->getType()->isPointerType() &&
885 "thread id variable must be of type kmp_int32 for tasks");
886 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
887 auto *TD = dyn_cast<OMPTaskDirective>(&D);
888 CodeGenFunction CGF(CGM, true);
889 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
891 TD ? TD->hasCancel() : false, Action);
892 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
893 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
895 NumberOfParts = Action.getNumberOfParts();
899 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
900 CharUnits Align = getIdentAlign(CGM);
901 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
903 if (!DefaultOpenMPPSource) {
904 // Initialize default location for psource field of ident_t structure of
905 // all ident_t objects. Format is ";file;function;line;column;;".
907 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
908 DefaultOpenMPPSource =
909 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
910 DefaultOpenMPPSource =
911 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
914 ConstantInitBuilder builder(CGM);
915 auto fields = builder.beginStruct(IdentTy);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.addInt(CGM.Int32Ty, Flags);
918 fields.addInt(CGM.Int32Ty, 0);
919 fields.addInt(CGM.Int32Ty, 0);
920 fields.add(DefaultOpenMPPSource);
921 auto DefaultOpenMPLocation =
922 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
923 llvm::GlobalValue::PrivateLinkage);
924 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
926 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
928 return Address(Entry, Align);
931 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
934 Flags |= OMP_IDENT_KMPC;
935 // If no debug info is generated - return global default location.
936 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
938 return getOrCreateDefaultLocation(Flags).getPointer();
940 assert(CGF.CurFn && "No function in current CodeGenFunction.");
942 Address LocValue = Address::invalid();
943 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
944 if (I != OpenMPLocThreadIDMap.end())
945 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
947 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
948 // GetOpenMPThreadID was called before this routine.
949 if (!LocValue.isValid()) {
950 // Generate "ident_t .kmpc_loc.addr;"
951 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
953 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
954 Elem.second.DebugLoc = AI.getPointer();
957 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
958 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
959 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
960 CGM.getSize(getIdentSize(CGF.CGM)));
963 // char **psource = &.kmpc_loc_<flags>.addr.psource;
964 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
966 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
967 if (OMPDebugLoc == nullptr) {
968 SmallString<128> Buffer2;
969 llvm::raw_svector_ostream OS2(Buffer2);
970 // Build debug location
971 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
972 OS2 << ";" << PLoc.getFilename() << ";";
973 if (const FunctionDecl *FD =
974 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
975 OS2 << FD->getQualifiedNameAsString();
977 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
978 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
979 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
981 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
982 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
984 // Our callers always pass this to a runtime function, so for
985 // convenience, go ahead and return a naked pointer.
986 return LocValue.getPointer();
989 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
990 SourceLocation Loc) {
991 assert(CGF.CurFn && "No function in current CodeGenFunction.");
993 llvm::Value *ThreadID = nullptr;
994 // Check whether we've already cached a load of the thread id in this
996 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
997 if (I != OpenMPLocThreadIDMap.end()) {
998 ThreadID = I->second.ThreadID;
999 if (ThreadID != nullptr)
1002 if (auto *OMPRegionInfo =
1003 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1004 if (OMPRegionInfo->getThreadIDVariable()) {
1005 // Check if this an outlined function with thread id passed as argument.
1006 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1007 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1008 // If value loaded in entry block, cache it and use it everywhere in
1010 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1011 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1012 Elem.second.ThreadID = ThreadID;
1018 // This is not an outlined function region - need to call __kmpc_int32
1019 // kmpc_global_thread_num(ident_t *loc).
1020 // Generate thread id value and cache this value for use across the
1022 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1023 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1025 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1026 emitUpdateLocation(CGF, Loc));
1027 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1028 Elem.second.ThreadID = ThreadID;
1032 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1033 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1034 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1035 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1036 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1037 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1040 FunctionUDRMap.erase(CGF.CurFn);
1044 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1047 return llvm::PointerType::getUnqual(IdentTy);
1050 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1051 if (!Kmpc_MicroTy) {
1052 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1053 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1054 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1055 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1057 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1061 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1062 llvm::Constant *RTLFn = nullptr;
1063 switch (static_cast<OpenMPRTLFunction>(Function)) {
1064 case OMPRTL__kmpc_fork_call: {
1065 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1068 getKmpc_MicroPointerTy()};
1069 llvm::FunctionType *FnTy =
1070 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1071 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1074 case OMPRTL__kmpc_global_thread_num: {
1075 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1076 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1077 llvm::FunctionType *FnTy =
1078 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1082 case OMPRTL__kmpc_threadprivate_cached: {
1083 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1084 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1086 CGM.VoidPtrTy, CGM.SizeTy,
1087 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1088 llvm::FunctionType *FnTy =
1089 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1090 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1093 case OMPRTL__kmpc_critical: {
1094 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1095 // kmp_critical_name *crit);
1096 llvm::Type *TypeParams[] = {
1097 getIdentTyPointerTy(), CGM.Int32Ty,
1098 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1099 llvm::FunctionType *FnTy =
1100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1104 case OMPRTL__kmpc_critical_with_hint: {
1105 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1106 // kmp_critical_name *crit, uintptr_t hint);
1107 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1108 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1110 llvm::FunctionType *FnTy =
1111 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1112 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1115 case OMPRTL__kmpc_threadprivate_register: {
1116 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1117 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1118 // typedef void *(*kmpc_ctor)(void *);
1120 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1121 /*isVarArg*/ false)->getPointerTo();
1122 // typedef void *(*kmpc_cctor)(void *, void *);
1123 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1124 auto KmpcCopyCtorTy =
1125 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1126 /*isVarArg*/ false)->getPointerTo();
1127 // typedef void (*kmpc_dtor)(void *);
1129 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1131 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1132 KmpcCopyCtorTy, KmpcDtorTy};
1133 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1134 /*isVarArg*/ false);
1135 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1138 case OMPRTL__kmpc_end_critical: {
1139 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1140 // kmp_critical_name *crit);
1141 llvm::Type *TypeParams[] = {
1142 getIdentTyPointerTy(), CGM.Int32Ty,
1143 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1144 llvm::FunctionType *FnTy =
1145 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1146 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1149 case OMPRTL__kmpc_cancel_barrier: {
1150 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1152 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1153 llvm::FunctionType *FnTy =
1154 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1158 case OMPRTL__kmpc_barrier: {
1159 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1160 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1161 llvm::FunctionType *FnTy =
1162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1166 case OMPRTL__kmpc_for_static_fini: {
1167 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1168 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1169 llvm::FunctionType *FnTy =
1170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1174 case OMPRTL__kmpc_push_num_threads: {
1175 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1176 // kmp_int32 num_threads)
1177 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1179 llvm::FunctionType *FnTy =
1180 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1181 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1184 case OMPRTL__kmpc_serialized_parallel: {
1185 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1187 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1188 llvm::FunctionType *FnTy =
1189 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1190 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1193 case OMPRTL__kmpc_end_serialized_parallel: {
1194 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1196 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1197 llvm::FunctionType *FnTy =
1198 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1199 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1202 case OMPRTL__kmpc_flush: {
1203 // Build void __kmpc_flush(ident_t *loc);
1204 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1205 llvm::FunctionType *FnTy =
1206 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1210 case OMPRTL__kmpc_master: {
1211 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1212 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1213 llvm::FunctionType *FnTy =
1214 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1215 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1218 case OMPRTL__kmpc_end_master: {
1219 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1220 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1221 llvm::FunctionType *FnTy =
1222 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1223 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1226 case OMPRTL__kmpc_omp_taskyield: {
1227 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1235 case OMPRTL__kmpc_single: {
1236 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1243 case OMPRTL__kmpc_end_single: {
1244 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1245 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1246 llvm::FunctionType *FnTy =
1247 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1248 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1251 case OMPRTL__kmpc_omp_task_alloc: {
1252 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1253 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1254 // kmp_routine_entry_t *task_entry);
1255 assert(KmpRoutineEntryPtrTy != nullptr &&
1256 "Type kmp_routine_entry_t must be created.");
1257 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1258 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1259 // Return void * and then cast to particular kmp_task_t type.
1260 llvm::FunctionType *FnTy =
1261 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1262 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1265 case OMPRTL__kmpc_omp_task: {
1266 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1268 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1270 llvm::FunctionType *FnTy =
1271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1272 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1275 case OMPRTL__kmpc_copyprivate: {
1276 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1277 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1278 // kmp_int32 didit);
1279 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1281 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1282 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1283 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1285 llvm::FunctionType *FnTy =
1286 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1287 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1290 case OMPRTL__kmpc_reduce: {
1291 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1292 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1293 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1294 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1295 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1296 /*isVarArg=*/false);
1297 llvm::Type *TypeParams[] = {
1298 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1299 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1300 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1301 llvm::FunctionType *FnTy =
1302 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1303 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1306 case OMPRTL__kmpc_reduce_nowait: {
1307 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1308 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1309 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1311 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1312 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1313 /*isVarArg=*/false);
1314 llvm::Type *TypeParams[] = {
1315 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1316 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1317 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1323 case OMPRTL__kmpc_end_reduce: {
1324 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1325 // kmp_critical_name *lck);
1326 llvm::Type *TypeParams[] = {
1327 getIdentTyPointerTy(), CGM.Int32Ty,
1328 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1329 llvm::FunctionType *FnTy =
1330 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1331 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1334 case OMPRTL__kmpc_end_reduce_nowait: {
1335 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1336 // kmp_critical_name *lck);
1337 llvm::Type *TypeParams[] = {
1338 getIdentTyPointerTy(), CGM.Int32Ty,
1339 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1340 llvm::FunctionType *FnTy =
1341 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1343 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1346 case OMPRTL__kmpc_omp_task_begin_if0: {
1347 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1349 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1351 llvm::FunctionType *FnTy =
1352 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1354 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1357 case OMPRTL__kmpc_omp_task_complete_if0: {
1358 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1360 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1362 llvm::FunctionType *FnTy =
1363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1364 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1365 /*Name=*/"__kmpc_omp_task_complete_if0");
1368 case OMPRTL__kmpc_ordered: {
1369 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1370 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1371 llvm::FunctionType *FnTy =
1372 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1373 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1376 case OMPRTL__kmpc_end_ordered: {
1377 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1378 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1379 llvm::FunctionType *FnTy =
1380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1381 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1384 case OMPRTL__kmpc_omp_taskwait: {
1385 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1386 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1387 llvm::FunctionType *FnTy =
1388 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1389 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1392 case OMPRTL__kmpc_taskgroup: {
1393 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1394 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1395 llvm::FunctionType *FnTy =
1396 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1397 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1400 case OMPRTL__kmpc_end_taskgroup: {
1401 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1402 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1403 llvm::FunctionType *FnTy =
1404 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1405 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1408 case OMPRTL__kmpc_push_proc_bind: {
1409 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1411 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1412 llvm::FunctionType *FnTy =
1413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1417 case OMPRTL__kmpc_omp_task_with_deps: {
1418 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1419 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1420 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1421 llvm::Type *TypeParams[] = {
1422 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1423 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1424 llvm::FunctionType *FnTy =
1425 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1427 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1430 case OMPRTL__kmpc_omp_wait_deps: {
1431 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1432 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1433 // kmp_depend_info_t *noalias_dep_list);
1434 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1435 CGM.Int32Ty, CGM.VoidPtrTy,
1436 CGM.Int32Ty, CGM.VoidPtrTy};
1437 llvm::FunctionType *FnTy =
1438 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1439 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1442 case OMPRTL__kmpc_cancellationpoint: {
1443 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1444 // global_tid, kmp_int32 cncl_kind)
1445 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1446 llvm::FunctionType *FnTy =
1447 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1448 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1451 case OMPRTL__kmpc_cancel: {
1452 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1453 // kmp_int32 cncl_kind)
1454 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1455 llvm::FunctionType *FnTy =
1456 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1457 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1460 case OMPRTL__kmpc_push_num_teams: {
1461 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1462 // kmp_int32 num_teams, kmp_int32 num_threads)
1463 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1465 llvm::FunctionType *FnTy =
1466 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1467 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1470 case OMPRTL__kmpc_fork_teams: {
1471 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1473 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1474 getKmpc_MicroPointerTy()};
1475 llvm::FunctionType *FnTy =
1476 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1477 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1480 case OMPRTL__kmpc_taskloop: {
1481 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1482 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1483 // sched, kmp_uint64 grainsize, void *task_dup);
1484 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1488 CGM.Int64Ty->getPointerTo(),
1489 CGM.Int64Ty->getPointerTo(),
1495 llvm::FunctionType *FnTy =
1496 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1497 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1500 case OMPRTL__kmpc_doacross_init: {
1501 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1502 // num_dims, struct kmp_dim *dims);
1503 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1507 llvm::FunctionType *FnTy =
1508 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1509 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1512 case OMPRTL__kmpc_doacross_fini: {
1513 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1514 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1515 llvm::FunctionType *FnTy =
1516 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1517 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1520 case OMPRTL__kmpc_doacross_post: {
1521 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1523 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1524 CGM.Int64Ty->getPointerTo()};
1525 llvm::FunctionType *FnTy =
1526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1527 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1530 case OMPRTL__kmpc_doacross_wait: {
1531 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1533 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1534 CGM.Int64Ty->getPointerTo()};
1535 llvm::FunctionType *FnTy =
1536 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1537 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1540 case OMPRTL__tgt_target: {
1541 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1542 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1544 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1549 CGM.SizeTy->getPointerTo(),
1550 CGM.Int32Ty->getPointerTo()};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1556 case OMPRTL__tgt_target_teams: {
1557 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1558 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1559 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1560 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1565 CGM.SizeTy->getPointerTo(),
1566 CGM.Int32Ty->getPointerTo(),
1569 llvm::FunctionType *FnTy =
1570 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1574 case OMPRTL__tgt_register_lib: {
1575 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1577 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1578 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1579 llvm::FunctionType *FnTy =
1580 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1581 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1584 case OMPRTL__tgt_unregister_lib: {
1585 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1587 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1588 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1589 llvm::FunctionType *FnTy =
1590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1594 case OMPRTL__tgt_target_data_begin: {
1595 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1596 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1597 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1601 CGM.SizeTy->getPointerTo(),
1602 CGM.Int32Ty->getPointerTo()};
1603 llvm::FunctionType *FnTy =
1604 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1608 case OMPRTL__tgt_target_data_end: {
1609 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1610 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1611 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1615 CGM.SizeTy->getPointerTo(),
1616 CGM.Int32Ty->getPointerTo()};
1617 llvm::FunctionType *FnTy =
1618 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1619 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1622 case OMPRTL__tgt_target_data_update: {
1623 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1624 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1625 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1629 CGM.SizeTy->getPointerTo(),
1630 CGM.Int32Ty->getPointerTo()};
1631 llvm::FunctionType *FnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1637 assert(RTLFn && "Unable to find OpenMP runtime function");
1641 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1643 assert((IVSize == 32 || IVSize == 64) &&
1644 "IV size is not compatible with the omp runtime");
1645 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1646 : "__kmpc_for_static_init_4u")
1647 : (IVSigned ? "__kmpc_for_static_init_8"
1648 : "__kmpc_for_static_init_8u");
1649 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1650 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1651 llvm::Type *TypeParams[] = {
1652 getIdentTyPointerTy(), // loc
1654 CGM.Int32Ty, // schedtype
1655 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1662 llvm::FunctionType *FnTy =
1663 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1664 return CGM.CreateRuntimeFunction(FnTy, Name);
1667 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1669 assert((IVSize == 32 || IVSize == 64) &&
1670 "IV size is not compatible with the omp runtime");
1673 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1674 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1675 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1676 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1678 CGM.Int32Ty, // schedtype
1684 llvm::FunctionType *FnTy =
1685 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1686 return CGM.CreateRuntimeFunction(FnTy, Name);
1689 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1691 assert((IVSize == 32 || IVSize == 64) &&
1692 "IV size is not compatible with the omp runtime");
1695 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1696 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1697 llvm::Type *TypeParams[] = {
1698 getIdentTyPointerTy(), // loc
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1703 return CGM.CreateRuntimeFunction(FnTy, Name);
1706 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1708 assert((IVSize == 32 || IVSize == 64) &&
1709 "IV size is not compatible with the omp runtime");
1712 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1713 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1714 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1715 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1716 llvm::Type *TypeParams[] = {
1717 getIdentTyPointerTy(), // loc
1719 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1724 llvm::FunctionType *FnTy =
1725 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1726 return CGM.CreateRuntimeFunction(FnTy, Name);
1730 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1731 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1732 !CGM.getContext().getTargetInfo().isTLSSupported());
1733 // Lookup the entry, lazily creating it if necessary.
1734 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
1735 Twine(CGM.getMangledName(VD)) + ".cache.");
1738 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1741 SourceLocation Loc) {
1742 if (CGM.getLangOpts().OpenMPUseTLS &&
1743 CGM.getContext().getTargetInfo().isTLSSupported())
1746 auto VarTy = VDAddr.getElementType();
1747 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1748 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1750 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1751 getOrCreateThreadPrivateCache(VD)};
1752 return Address(CGF.EmitRuntimeCall(
1753 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1754 VDAddr.getAlignment());
1757 void CGOpenMPRuntime::emitThreadPrivateVarInit(
1758 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1759 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1760 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1762 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1763 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1765 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1766 // to register constructor/destructor for variable.
1767 llvm::Value *Args[] = {OMPLoc,
1768 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1770 Ctor, CopyCtor, Dtor};
1771 CGF.EmitRuntimeCall(
1772 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
1775 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1776 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1777 bool PerformInit, CodeGenFunction *CGF) {
1778 if (CGM.getLangOpts().OpenMPUseTLS &&
1779 CGM.getContext().getTargetInfo().isTLSSupported())
1782 VD = VD->getDefinition(CGM.getContext());
1783 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1784 ThreadPrivateWithDefinition.insert(VD);
1785 QualType ASTTy = VD->getType();
1787 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1788 auto Init = VD->getAnyInitializer();
1789 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1790 // Generate function that re-emits the declaration's initializer into the
1791 // threadprivate copy of the variable VD
1792 CodeGenFunction CtorCGF(CGM);
1793 FunctionArgList Args;
1794 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1795 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1796 Args.push_back(&Dst);
1798 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1799 CGM.getContext().VoidPtrTy, Args);
1800 auto FTy = CGM.getTypes().GetFunctionType(FI);
1801 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1802 FTy, ".__kmpc_global_ctor_.", FI, Loc);
1803 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1804 Args, SourceLocation());
1805 auto ArgVal = CtorCGF.EmitLoadOfScalar(
1806 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1807 CGM.getContext().VoidPtrTy, Dst.getLocation());
1808 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1809 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1810 CtorCGF.ConvertTypeForMem(ASTTy));
1811 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1812 /*IsInitializer=*/true);
1813 ArgVal = CtorCGF.EmitLoadOfScalar(
1814 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1815 CGM.getContext().VoidPtrTy, Dst.getLocation());
1816 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1817 CtorCGF.FinishFunction();
1820 if (VD->getType().isDestructedType() != QualType::DK_none) {
1821 // Generate function that emits destructor call for the threadprivate copy
1822 // of the variable VD
1823 CodeGenFunction DtorCGF(CGM);
1824 FunctionArgList Args;
1825 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1826 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1827 Args.push_back(&Dst);
1829 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1830 CGM.getContext().VoidTy, Args);
1831 auto FTy = CGM.getTypes().GetFunctionType(FI);
1832 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1833 FTy, ".__kmpc_global_dtor_.", FI, Loc);
1834 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1835 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1837 // Create a scope with an artificial location for the body of this function.
1838 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1839 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1840 DtorCGF.GetAddrOfLocalVar(&Dst),
1841 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1842 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
1843 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1844 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1845 DtorCGF.FinishFunction();
1848 // Do not emit init function if it is not required.
1852 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1854 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1855 /*isVarArg=*/false)->getPointerTo();
1856 // Copying constructor for the threadprivate variable.
1857 // Must be NULL - reserved by runtime, but currently it requires that this
1858 // parameter is always NULL. Otherwise it fires assertion.
1859 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1860 if (Ctor == nullptr) {
1861 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1862 /*isVarArg=*/false)->getPointerTo();
1863 Ctor = llvm::Constant::getNullValue(CtorTy);
1865 if (Dtor == nullptr) {
1866 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1867 /*isVarArg=*/false)->getPointerTo();
1868 Dtor = llvm::Constant::getNullValue(DtorTy);
1871 auto InitFunctionTy =
1872 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1873 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1874 InitFunctionTy, ".__omp_threadprivate_init_.",
1875 CGM.getTypes().arrangeNullaryFunction());
1876 CodeGenFunction InitCGF(CGM);
1877 FunctionArgList ArgList;
1878 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1879 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1881 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1882 InitCGF.FinishFunction();
1883 return InitFunction;
1885 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1890 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1891 /// function. Here is the logic:
1897 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1898 const RegionCodeGenTy &ThenGen,
1899 const RegionCodeGenTy &ElseGen) {
1900 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1902 // If the condition constant folds and can be elided, try to avoid emitting
1903 // the condition and the dead arm of the if/else.
1905 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1913 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1914 // emit the conditional branch.
1915 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1916 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1917 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1918 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1920 // Emit the 'then' code.
1921 CGF.EmitBlock(ThenBlock);
1923 CGF.EmitBranch(ContBlock);
1924 // Emit the 'else' code if present.
1925 // There is no need to emit line number for unconditional branch.
1926 (void)ApplyDebugLocation::CreateEmpty(CGF);
1927 CGF.EmitBlock(ElseBlock);
1929 // There is no need to emit line number for unconditional branch.
1930 (void)ApplyDebugLocation::CreateEmpty(CGF);
1931 CGF.EmitBranch(ContBlock);
1932 // Emit the continuation block for code after the if.
1933 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
1936 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1937 llvm::Value *OutlinedFn,
1938 ArrayRef<llvm::Value *> CapturedVars,
1939 const Expr *IfCond) {
1940 if (!CGF.HaveInsertPoint())
1942 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1943 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1944 PrePostActionTy &) {
1945 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1946 auto &RT = CGF.CGM.getOpenMPRuntime();
1947 llvm::Value *Args[] = {
1949 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1950 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
1951 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1952 RealArgs.append(std::begin(Args), std::end(Args));
1953 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1955 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
1956 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1958 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1959 PrePostActionTy &) {
1960 auto &RT = CGF.CGM.getOpenMPRuntime();
1961 auto ThreadID = RT.getThreadID(CGF, Loc);
1963 // __kmpc_serialized_parallel(&Loc, GTid);
1964 llvm::Value *Args[] = {RTLoc, ThreadID};
1965 CGF.EmitRuntimeCall(
1966 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
1968 // OutlinedFn(>id, &zero, CapturedStruct);
1969 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
1971 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1972 /*Name*/ ".zero.addr");
1973 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1974 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1975 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1976 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1977 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1978 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
1980 // __kmpc_end_serialized_parallel(&Loc, GTid);
1981 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
1982 CGF.EmitRuntimeCall(
1983 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1987 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1989 RegionCodeGenTy ThenRCG(ThenGen);
1994 // If we're inside an (outlined) parallel region, use the region info's
1995 // thread-ID variable (it is passed in a first argument of the outlined function
1996 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1997 // regular serial code region, get thread ID by calling kmp_int32
1998 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1999 // return the address of that temp.
2000 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2001 SourceLocation Loc) {
2002 if (auto *OMPRegionInfo =
2003 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2004 if (OMPRegionInfo->getThreadIDVariable())
2005 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2007 auto ThreadID = getThreadID(CGF, Loc);
2009 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2010 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2011 CGF.EmitStoreOfScalar(ThreadID,
2012 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2014 return ThreadIDTemp;
2018 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2019 const llvm::Twine &Name) {
2020 SmallString<256> Buffer;
2021 llvm::raw_svector_ostream Out(Buffer);
2023 auto RuntimeName = Out.str();
2024 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2026 assert(Elem.second->getType()->getPointerElementType() == Ty &&
2027 "OMP internal variable has different type than requested");
2028 return &*Elem.second;
2031 return Elem.second = new llvm::GlobalVariable(
2032 CGM.getModule(), Ty, /*IsConstant*/ false,
2033 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2037 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2038 llvm::Twine Name(".gomp_critical_user_", CriticalName);
2039 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
2043 /// Common pre(post)-action for different OpenMP constructs.
2044 class CommonActionTy final : public PrePostActionTy {
2045 llvm::Value *EnterCallee;
2046 ArrayRef<llvm::Value *> EnterArgs;
2047 llvm::Value *ExitCallee;
2048 ArrayRef<llvm::Value *> ExitArgs;
2050 llvm::BasicBlock *ContBlock = nullptr;
2053 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2054 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2055 bool Conditional = false)
2056 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2057 ExitArgs(ExitArgs), Conditional(Conditional) {}
2058 void Enter(CodeGenFunction &CGF) override {
2059 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2061 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2062 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2063 ContBlock = CGF.createBasicBlock("omp_if.end");
2064 // Generate the branch (If-stmt)
2065 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2066 CGF.EmitBlock(ThenBlock);
2069 void Done(CodeGenFunction &CGF) {
2070 // Emit the rest of blocks/branches
2071 CGF.EmitBranch(ContBlock);
2072 CGF.EmitBlock(ContBlock, true);
2074 void Exit(CodeGenFunction &CGF) override {
2075 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2078 } // anonymous namespace
2080 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2081 StringRef CriticalName,
2082 const RegionCodeGenTy &CriticalOpGen,
2083 SourceLocation Loc, const Expr *Hint) {
2084 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2086 // __kmpc_end_critical(ident_t *, gtid, Lock);
2087 // Prepare arguments and build a call to __kmpc_critical
2088 if (!CGF.HaveInsertPoint())
2090 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2091 getCriticalRegionLock(CriticalName)};
2092 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2095 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2096 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2098 CommonActionTy Action(
2099 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2100 : OMPRTL__kmpc_critical),
2101 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2102 CriticalOpGen.setAction(Action);
2103 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2106 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2107 const RegionCodeGenTy &MasterOpGen,
2108 SourceLocation Loc) {
2109 if (!CGF.HaveInsertPoint())
2111 // if(__kmpc_master(ident_t *, gtid)) {
2113 // __kmpc_end_master(ident_t *, gtid);
2115 // Prepare arguments and build a call to __kmpc_master
2116 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2117 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2118 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2119 /*Conditional=*/true);
2120 MasterOpGen.setAction(Action);
2121 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2125 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2126 SourceLocation Loc) {
2127 if (!CGF.HaveInsertPoint())
2129 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2130 llvm::Value *Args[] = {
2131 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2132 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2133 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
2134 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2135 Region->emitUntiedSwitch(CGF);
2138 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2139 const RegionCodeGenTy &TaskgroupOpGen,
2140 SourceLocation Loc) {
2141 if (!CGF.HaveInsertPoint())
2143 // __kmpc_taskgroup(ident_t *, gtid);
2144 // TaskgroupOpGen();
2145 // __kmpc_end_taskgroup(ident_t *, gtid);
2146 // Prepare arguments and build a call to __kmpc_taskgroup
2147 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2148 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2149 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2151 TaskgroupOpGen.setAction(Action);
2152 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2155 /// Given an array of pointers to variables, project the address of a
2157 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2158 unsigned Index, const VarDecl *Var) {
2159 // Pull out the pointer to the variable.
2161 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
2162 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2164 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2165 Addr = CGF.Builder.CreateElementBitCast(
2166 Addr, CGF.ConvertTypeForMem(Var->getType()));
2170 static llvm::Value *emitCopyprivateCopyFunction(
2171 CodeGenModule &CGM, llvm::Type *ArgsType,
2172 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2173 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
2174 auto &C = CGM.getContext();
2175 // void copy_func(void *LHSArg, void *RHSArg);
2176 FunctionArgList Args;
2177 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2179 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2181 Args.push_back(&LHSArg);
2182 Args.push_back(&RHSArg);
2183 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2184 auto *Fn = llvm::Function::Create(
2185 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2186 ".omp.copyprivate.copy_func", &CGM.getModule());
2187 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
2188 CodeGenFunction CGF(CGM);
2189 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2190 // Dest = (void*[n])(LHSArg);
2191 // Src = (void*[n])(RHSArg);
2192 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2193 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2194 ArgsType), CGF.getPointerAlign());
2195 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2196 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2197 ArgsType), CGF.getPointerAlign());
2198 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2199 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2201 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2202 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2203 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2204 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2206 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2207 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2209 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2210 QualType Type = VD->getType();
2211 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2213 CGF.FinishFunction();
2217 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2218 const RegionCodeGenTy &SingleOpGen,
2220 ArrayRef<const Expr *> CopyprivateVars,
2221 ArrayRef<const Expr *> SrcExprs,
2222 ArrayRef<const Expr *> DstExprs,
2223 ArrayRef<const Expr *> AssignmentOps) {
2224 if (!CGF.HaveInsertPoint())
2226 assert(CopyprivateVars.size() == SrcExprs.size() &&
2227 CopyprivateVars.size() == DstExprs.size() &&
2228 CopyprivateVars.size() == AssignmentOps.size());
2229 auto &C = CGM.getContext();
2230 // int32 did_it = 0;
2231 // if(__kmpc_single(ident_t *, gtid)) {
2233 // __kmpc_end_single(ident_t *, gtid);
2236 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2237 // <copy_func>, did_it);
2239 Address DidIt = Address::invalid();
2240 if (!CopyprivateVars.empty()) {
2241 // int32 did_it = 0;
2242 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2243 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2244 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2246 // Prepare arguments and build a call to __kmpc_single
2247 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2248 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2249 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2250 /*Conditional=*/true);
2251 SingleOpGen.setAction(Action);
2252 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2253 if (DidIt.isValid()) {
2255 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2258 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2259 // <copy_func>, did_it);
2260 if (DidIt.isValid()) {
2261 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2262 auto CopyprivateArrayTy =
2263 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2264 /*IndexTypeQuals=*/0);
2265 // Create a list of all private variables for copyprivate.
2266 Address CopyprivateList =
2267 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2268 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2269 Address Elem = CGF.Builder.CreateConstArrayGEP(
2270 CopyprivateList, I, CGF.getPointerSize());
2271 CGF.Builder.CreateStore(
2272 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2273 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2276 // Build function that copies private values from single region to all other
2277 // threads in the corresponding parallel region.
2278 auto *CpyFn = emitCopyprivateCopyFunction(
2279 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2280 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
2281 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2283 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2285 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
2286 llvm::Value *Args[] = {
2287 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2288 getThreadID(CGF, Loc), // i32 <gtid>
2289 BufSize, // size_t <buf_size>
2290 CL.getPointer(), // void *<copyprivate list>
2291 CpyFn, // void (*) (void *, void *) <copy_func>
2292 DidItVal // i32 did_it
2294 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2298 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2299 const RegionCodeGenTy &OrderedOpGen,
2300 SourceLocation Loc, bool IsThreads) {
2301 if (!CGF.HaveInsertPoint())
2303 // __kmpc_ordered(ident_t *, gtid);
2305 // __kmpc_end_ordered(ident_t *, gtid);
2306 // Prepare arguments and build a call to __kmpc_ordered
2308 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2309 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2310 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2312 OrderedOpGen.setAction(Action);
2313 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2316 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2319 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2320 OpenMPDirectiveKind Kind, bool EmitChecks,
2321 bool ForceSimpleCall) {
2322 if (!CGF.HaveInsertPoint())
2324 // Build call __kmpc_cancel_barrier(loc, thread_id);
2325 // Build call __kmpc_barrier(loc, thread_id);
2327 if (Kind == OMPD_for)
2328 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2329 else if (Kind == OMPD_sections)
2330 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2331 else if (Kind == OMPD_single)
2332 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2333 else if (Kind == OMPD_barrier)
2334 Flags = OMP_IDENT_BARRIER_EXPL;
2336 Flags = OMP_IDENT_BARRIER_IMPL;
2337 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2339 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2340 getThreadID(CGF, Loc)};
2341 if (auto *OMPRegionInfo =
2342 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2343 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2344 auto *Result = CGF.EmitRuntimeCall(
2345 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
2347 // if (__kmpc_cancel_barrier()) {
2348 // exit from construct;
2350 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2351 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2352 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2353 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2354 CGF.EmitBlock(ExitBB);
2355 // exit from construct;
2356 auto CancelDestination =
2357 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2358 CGF.EmitBranchThroughCleanup(CancelDestination);
2359 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2364 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2367 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
2368 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2369 bool Chunked, bool Ordered) {
2370 switch (ScheduleKind) {
2371 case OMPC_SCHEDULE_static:
2372 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2373 : (Ordered ? OMP_ord_static : OMP_sch_static);
2374 case OMPC_SCHEDULE_dynamic:
2375 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2376 case OMPC_SCHEDULE_guided:
2377 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2378 case OMPC_SCHEDULE_runtime:
2379 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2380 case OMPC_SCHEDULE_auto:
2381 return Ordered ? OMP_ord_auto : OMP_sch_auto;
2382 case OMPC_SCHEDULE_unknown:
2383 assert(!Chunked && "chunk was specified but schedule kind not known");
2384 return Ordered ? OMP_ord_static : OMP_sch_static;
2386 llvm_unreachable("Unexpected runtime schedule");
2389 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2390 static OpenMPSchedType
2391 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2392 // only static is allowed for dist_schedule
2393 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2396 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2397 bool Chunked) const {
2398 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2399 return Schedule == OMP_sch_static;
2402 bool CGOpenMPRuntime::isStaticNonchunked(
2403 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2404 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2405 return Schedule == OMP_dist_sch_static;
2409 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2411 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2412 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2413 return Schedule != OMP_sch_static;
2416 static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2417 OpenMPScheduleClauseModifier M1,
2418 OpenMPScheduleClauseModifier M2) {
2421 case OMPC_SCHEDULE_MODIFIER_monotonic:
2422 Modifier = OMP_sch_modifier_monotonic;
2424 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2425 Modifier = OMP_sch_modifier_nonmonotonic;
2427 case OMPC_SCHEDULE_MODIFIER_simd:
2428 if (Schedule == OMP_sch_static_chunked)
2429 Schedule = OMP_sch_static_balanced_chunked;
2431 case OMPC_SCHEDULE_MODIFIER_last:
2432 case OMPC_SCHEDULE_MODIFIER_unknown:
2436 case OMPC_SCHEDULE_MODIFIER_monotonic:
2437 Modifier = OMP_sch_modifier_monotonic;
2439 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2440 Modifier = OMP_sch_modifier_nonmonotonic;
2442 case OMPC_SCHEDULE_MODIFIER_simd:
2443 if (Schedule == OMP_sch_static_chunked)
2444 Schedule = OMP_sch_static_balanced_chunked;
2446 case OMPC_SCHEDULE_MODIFIER_last:
2447 case OMPC_SCHEDULE_MODIFIER_unknown:
2450 return Schedule | Modifier;
2453 void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2455 const OpenMPScheduleTy &ScheduleKind,
2456 unsigned IVSize, bool IVSigned,
2457 bool Ordered, llvm::Value *UB,
2458 llvm::Value *Chunk) {
2459 if (!CGF.HaveInsertPoint())
2461 OpenMPSchedType Schedule =
2462 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
2464 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2465 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2466 Schedule != OMP_sch_static_balanced_chunked));
2467 // Call __kmpc_dispatch_init(
2468 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2469 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2470 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
2472 // If the Chunk was not specified in the clause - use default value 1.
2473 if (Chunk == nullptr)
2474 Chunk = CGF.Builder.getIntN(IVSize, 1);
2475 llvm::Value *Args[] = {
2476 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2477 CGF.Builder.getInt32(addMonoNonMonoModifier(
2478 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2479 CGF.Builder.getIntN(IVSize, 0), // Lower
2481 CGF.Builder.getIntN(IVSize, 1), // Stride
2484 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2487 static void emitForStaticInitCall(
2488 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2489 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2490 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2491 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2492 Address ST, llvm::Value *Chunk) {
2493 if (!CGF.HaveInsertPoint())
2497 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2498 Schedule == OMP_sch_static_balanced_chunked ||
2499 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2500 Schedule == OMP_dist_sch_static ||
2501 Schedule == OMP_dist_sch_static_chunked);
2503 // Call __kmpc_for_static_init(
2504 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2505 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2506 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2507 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2508 if (Chunk == nullptr) {
2509 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2510 Schedule == OMP_dist_sch_static) &&
2511 "expected static non-chunked schedule");
2512 // If the Chunk was not specified in the clause - use default value 1.
2513 Chunk = CGF.Builder.getIntN(IVSize, 1);
2515 assert((Schedule == OMP_sch_static_chunked ||
2516 Schedule == OMP_sch_static_balanced_chunked ||
2517 Schedule == OMP_ord_static_chunked ||
2518 Schedule == OMP_dist_sch_static_chunked) &&
2519 "expected static chunked schedule");
2521 llvm::Value *Args[] = {
2522 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2523 Schedule, M1, M2)), // Schedule type
2524 IL.getPointer(), // &isLastIter
2525 LB.getPointer(), // &LB
2526 UB.getPointer(), // &UB
2527 ST.getPointer(), // &Stride
2528 CGF.Builder.getIntN(IVSize, 1), // Incr
2531 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2534 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2536 const OpenMPScheduleTy &ScheduleKind,
2537 unsigned IVSize, bool IVSigned,
2538 bool Ordered, Address IL, Address LB,
2539 Address UB, Address ST,
2540 llvm::Value *Chunk) {
2541 OpenMPSchedType ScheduleNum =
2542 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
2543 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2544 auto *ThreadId = getThreadID(CGF, Loc);
2545 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2546 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2547 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2548 Ordered, IL, LB, UB, ST, Chunk);
2551 void CGOpenMPRuntime::emitDistributeStaticInit(
2552 CodeGenFunction &CGF, SourceLocation Loc,
2553 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2554 bool Ordered, Address IL, Address LB, Address UB, Address ST,
2555 llvm::Value *Chunk) {
2556 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2557 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2558 auto *ThreadId = getThreadID(CGF, Loc);
2559 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2560 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2561 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2562 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2566 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2567 SourceLocation Loc) {
2568 if (!CGF.HaveInsertPoint())
2570 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2571 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2572 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2576 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2580 if (!CGF.HaveInsertPoint())
2582 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2583 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2584 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2587 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2588 SourceLocation Loc, unsigned IVSize,
2589 bool IVSigned, Address IL,
2590 Address LB, Address UB,
2592 // Call __kmpc_dispatch_next(
2593 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2594 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2595 // kmp_int[32|64] *p_stride);
2596 llvm::Value *Args[] = {
2597 emitUpdateLocation(CGF, Loc),
2598 getThreadID(CGF, Loc),
2599 IL.getPointer(), // &isLastIter
2600 LB.getPointer(), // &Lower
2601 UB.getPointer(), // &Upper
2602 ST.getPointer() // &Stride
2605 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2606 return CGF.EmitScalarConversion(
2607 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
2608 CGF.getContext().BoolTy, Loc);
2611 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2612 llvm::Value *NumThreads,
2613 SourceLocation Loc) {
2614 if (!CGF.HaveInsertPoint())
2616 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2617 llvm::Value *Args[] = {
2618 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2619 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2620 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2624 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2625 OpenMPProcBindClauseKind ProcBind,
2626 SourceLocation Loc) {
2627 if (!CGF.HaveInsertPoint())
2629 // Constants for proc bind value accepted by the runtime.
2640 case OMPC_PROC_BIND_master:
2641 RuntimeProcBind = ProcBindMaster;
2643 case OMPC_PROC_BIND_close:
2644 RuntimeProcBind = ProcBindClose;
2646 case OMPC_PROC_BIND_spread:
2647 RuntimeProcBind = ProcBindSpread;
2649 case OMPC_PROC_BIND_unknown:
2650 llvm_unreachable("Unsupported proc_bind value.");
2652 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2653 llvm::Value *Args[] = {
2654 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2655 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2656 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2659 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2660 SourceLocation Loc) {
2661 if (!CGF.HaveInsertPoint())
2663 // Build call void __kmpc_flush(ident_t *loc)
2664 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2665 emitUpdateLocation(CGF, Loc));
2669 /// \brief Indexes of fields for type kmp_task_t.
2670 enum KmpTaskTFields {
2671 /// \brief List of shared variables.
2673 /// \brief Task routine.
2675 /// \brief Partition id for the untied tasks.
2677 /// Function with call of destructors for private variables.
2681 /// (Taskloops only) Lower bound.
2683 /// (Taskloops only) Upper bound.
2685 /// (Taskloops only) Stride.
2687 /// (Taskloops only) Is last iteration flag.
2690 } // anonymous namespace
2692 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2693 // FIXME: Add other entries type when they become supported.
2694 return OffloadEntriesTargetRegion.empty();
2697 /// \brief Initialize target region entry.
2698 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2699 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2700 StringRef ParentName, unsigned LineNum,
2702 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2703 "only required for the device "
2704 "code generation.");
2705 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
2706 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2708 ++OffloadingEntriesNum;
2711 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2712 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2713 StringRef ParentName, unsigned LineNum,
2714 llvm::Constant *Addr, llvm::Constant *ID,
2716 // If we are emitting code for a target, the entry is already initialized,
2717 // only has to be registered.
2718 if (CGM.getLangOpts().OpenMPIsDevice) {
2719 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
2720 "Entry must exist.");
2722 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
2723 assert(Entry.isValid() && "Entry not initialized!");
2724 Entry.setAddress(Addr);
2726 Entry.setFlags(Flags);
2729 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
2730 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
2734 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
2735 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2736 unsigned LineNum) const {
2737 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2738 if (PerDevice == OffloadEntriesTargetRegion.end())
2740 auto PerFile = PerDevice->second.find(FileID);
2741 if (PerFile == PerDevice->second.end())
2743 auto PerParentName = PerFile->second.find(ParentName);
2744 if (PerParentName == PerFile->second.end())
2746 auto PerLine = PerParentName->second.find(LineNum);
2747 if (PerLine == PerParentName->second.end())
2749 // Fail if this entry is already registered.
2750 if (PerLine->second.getAddress() || PerLine->second.getID())
2755 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2756 const OffloadTargetRegionEntryInfoActTy &Action) {
2757 // Scan all target region entries and perform the provided action.
2758 for (auto &D : OffloadEntriesTargetRegion)
2759 for (auto &F : D.second)
2760 for (auto &P : F.second)
2761 for (auto &L : P.second)
2762 Action(D.first, F.first, P.first(), L.first, L.second);
2765 /// \brief Create a Ctor/Dtor-like function whose body is emitted through
2766 /// \a Codegen. This is used to emit the two functions that register and
2767 /// unregister the descriptor of the current compilation unit.
2768 static llvm::Function *
2769 createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2770 const RegionCodeGenTy &Codegen) {
2771 auto &C = CGM.getContext();
2772 FunctionArgList Args;
2773 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2774 /*Id=*/nullptr, C.VoidPtrTy);
2775 Args.push_back(&DummyPtr);
2777 CodeGenFunction CGF(CGM);
2778 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2779 auto FTy = CGM.getTypes().GetFunctionType(FI);
2781 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2782 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2784 CGF.FinishFunction();
2789 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2791 // If we don't have entries or if we are emitting code for the device, we
2792 // don't need to do anything.
2793 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2796 auto &M = CGM.getModule();
2797 auto &C = CGM.getContext();
2799 // Get list of devices we care about
2800 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2802 // We should be creating an offloading descriptor only if there are devices
2804 assert(!Devices.empty() && "No OpenMP offloading devices??");
2806 // Create the external variables that will point to the begin and end of the
2807 // host entries section. These will be defined by the linker.
2808 auto *OffloadEntryTy =
2809 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2810 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2811 M, OffloadEntryTy, /*isConstant=*/true,
2812 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2813 ".omp_offloading.entries_begin");
2814 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2815 M, OffloadEntryTy, /*isConstant=*/true,
2816 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2817 ".omp_offloading.entries_end");
2819 // Create all device images
2820 auto *DeviceImageTy = cast<llvm::StructType>(
2821 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2822 ConstantInitBuilder DeviceImagesBuilder(CGM);
2823 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
2825 for (unsigned i = 0; i < Devices.size(); ++i) {
2826 StringRef T = Devices[i].getTriple();
2827 auto *ImgBegin = new llvm::GlobalVariable(
2828 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2829 /*Initializer=*/nullptr,
2830 Twine(".omp_offloading.img_start.") + Twine(T));
2831 auto *ImgEnd = new llvm::GlobalVariable(
2832 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2833 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
2835 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2838 Dev.add(HostEntriesBegin);
2839 Dev.add(HostEntriesEnd);
2840 Dev.finishAndAddTo(DeviceImagesEntries);
2843 // Create device images global array.
2844 llvm::GlobalVariable *DeviceImages =
2845 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2846 CGM.getPointerAlign(),
2847 /*isConstant=*/true);
2848 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2850 // This is a Zero array to be used in the creation of the constant expressions
2851 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2852 llvm::Constant::getNullValue(CGM.Int32Ty)};
2854 // Create the target region descriptor.
2855 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2856 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2857 ConstantInitBuilder DescBuilder(CGM);
2858 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2859 DescInit.addInt(CGM.Int32Ty, Devices.size());
2860 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2863 DescInit.add(HostEntriesBegin);
2864 DescInit.add(HostEntriesEnd);
2866 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2867 CGM.getPointerAlign(),
2868 /*isConstant=*/true);
2870 // Emit code to register or unregister the descriptor at execution
2871 // startup or closing, respectively.
2873 // Create a variable to drive the registration and unregistration of the
2874 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2875 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2876 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2877 IdentInfo, C.CharTy);
2879 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2880 CGM, ".omp_offloading.descriptor_unreg",
2881 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2882 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2885 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2886 CGM, ".omp_offloading.descriptor_reg",
2887 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2888 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2890 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2895 void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2896 llvm::Constant *Addr, uint64_t Size,
2898 StringRef Name = Addr->getName();
2899 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2900 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2901 llvm::LLVMContext &C = CGM.getModule().getContext();
2902 llvm::Module &M = CGM.getModule();
2904 // Make sure the address has the right type.
2905 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
2907 // Create constant string with the name.
2908 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2910 llvm::GlobalVariable *Str =
2911 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2912 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2913 ".omp_offloading.entry_name");
2914 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2915 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2917 // We can't have any padding between symbols, so we need to have 1-byte
2919 auto Align = CharUnits::fromQuantity(1);
2921 // Create the entry struct.
2922 ConstantInitBuilder EntryBuilder(CGM);
2923 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2924 EntryInit.add(AddrPtr);
2925 EntryInit.add(StrPtr);
2926 EntryInit.addInt(CGM.SizeTy, Size);
2927 EntryInit.addInt(CGM.Int32Ty, Flags);
2928 EntryInit.addInt(CGM.Int32Ty, 0);
2929 llvm::GlobalVariable *Entry =
2930 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2933 llvm::GlobalValue::ExternalLinkage);
2935 // The entry has to be created in the section the linker expects it to be.
2936 Entry->setSection(".omp_offloading.entries");
2939 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2940 // Emit the offloading entries and metadata so that the device codegen side
2941 // can easily figure out what to emit. The produced metadata looks like
2944 // !omp_offload.info = !{!1, ...}
2946 // Right now we only generate metadata for function that contain target
2949 // If we do not have entries, we dont need to do anything.
2950 if (OffloadEntriesInfoManager.empty())
2953 llvm::Module &M = CGM.getModule();
2954 llvm::LLVMContext &C = M.getContext();
2955 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2956 OrderedEntries(OffloadEntriesInfoManager.size());
2958 // Create the offloading info metadata node.
2959 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2961 // Auxiliar methods to create metadata values and strings.
2962 auto getMDInt = [&](unsigned v) {
2963 return llvm::ConstantAsMetadata::get(
2964 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2967 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2969 // Create function that emits metadata for each target region entry;
2970 auto &&TargetRegionMetadataEmitter = [&](
2971 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
2972 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2973 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2974 // Generate metadata for target regions. Each entry of this metadata
2976 // - Entry 0 -> Kind of this type of metadata (0).
2977 // - Entry 1 -> Device ID of the file where the entry was identified.
2978 // - Entry 2 -> File ID of the file where the entry was identified.
2979 // - Entry 3 -> Mangled name of the function where the entry was identified.
2980 // - Entry 4 -> Line in the file where the entry was identified.
2981 // - Entry 5 -> Order the entry was created.
2982 // The first element of the metadata node is the kind.
2983 Ops.push_back(getMDInt(E.getKind()));
2984 Ops.push_back(getMDInt(DeviceID));
2985 Ops.push_back(getMDInt(FileID));
2986 Ops.push_back(getMDString(ParentName));
2987 Ops.push_back(getMDInt(Line));
2988 Ops.push_back(getMDInt(E.getOrder()));
2990 // Save this entry in the right position of the ordered entries array.
2991 OrderedEntries[E.getOrder()] = &E;
2993 // Add metadata to the named metadata node.
2994 MD->addOperand(llvm::MDNode::get(C, Ops));
2997 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2998 TargetRegionMetadataEmitter);
3000 for (auto *E : OrderedEntries) {
3001 assert(E && "All ordered entries must exist!");
3003 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3005 assert(CE->getID() && CE->getAddress() &&
3006 "Entry ID and Addr are invalid!");
3007 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
3009 llvm_unreachable("Unsupported entry kind.");
3013 /// \brief Loads all the offload entries information from the host IR
3015 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3016 // If we are in target mode, load the metadata from the host IR. This code has
3017 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3019 if (!CGM.getLangOpts().OpenMPIsDevice)
3022 if (CGM.getLangOpts().OMPHostIRFile.empty())
3025 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3029 llvm::LLVMContext C;
3030 auto ME = expectedToErrorOrAndEmitErrors(
3031 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3036 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3040 for (auto I : MD->operands()) {
3041 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3043 auto getMDInt = [&](unsigned Idx) {
3044 llvm::ConstantAsMetadata *V =
3045 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3046 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3049 auto getMDString = [&](unsigned Idx) {
3050 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3051 return V->getString();
3054 switch (getMDInt(0)) {
3056 llvm_unreachable("Unexpected metadata!");
3058 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3059 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3060 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3061 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3062 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
3063 /*Order=*/getMDInt(5));
3069 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3070 if (!KmpRoutineEntryPtrTy) {
3071 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3072 auto &C = CGM.getContext();
3073 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3074 FunctionProtoType::ExtProtoInfo EPI;
3075 KmpRoutineEntryPtrQTy = C.getPointerType(
3076 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3077 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3081 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3083 auto *Field = FieldDecl::Create(
3084 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3085 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3086 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3087 Field->setAccess(AS_public);
3092 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3094 // Make sure the type of the entry is already created. This is the type we
3096 // struct __tgt_offload_entry{
3097 // void *addr; // Pointer to the offload entry info.
3098 // // (function or global)
3099 // char *name; // Name of the function or global.
3100 // size_t size; // Size of the entry info (0 if it a function).
3101 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3102 // int32_t reserved; // Reserved, to use by the runtime library.
3104 if (TgtOffloadEntryQTy.isNull()) {
3105 ASTContext &C = CGM.getContext();
3106 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3107 RD->startDefinition();
3108 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3109 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3110 addFieldToRecordDecl(C, RD, C.getSizeType());
3111 addFieldToRecordDecl(
3112 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3113 addFieldToRecordDecl(
3114 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3115 RD->completeDefinition();
3116 TgtOffloadEntryQTy = C.getRecordType(RD);
3118 return TgtOffloadEntryQTy;
3121 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3122 // These are the types we need to build:
3123 // struct __tgt_device_image{
3124 // void *ImageStart; // Pointer to the target code start.
3125 // void *ImageEnd; // Pointer to the target code end.
3126 // // We also add the host entries to the device image, as it may be useful
3127 // // for the target runtime to have access to that information.
3128 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3130 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3131 // // entries (non inclusive).
3133 if (TgtDeviceImageQTy.isNull()) {
3134 ASTContext &C = CGM.getContext();
3135 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3136 RD->startDefinition();
3137 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3138 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3139 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3140 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3141 RD->completeDefinition();
3142 TgtDeviceImageQTy = C.getRecordType(RD);
3144 return TgtDeviceImageQTy;
3147 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3148 // struct __tgt_bin_desc{
3149 // int32_t NumDevices; // Number of devices supported.
3150 // __tgt_device_image *DeviceImages; // Arrays of device images
3151 // // (one per device).
3152 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3154 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3155 // // entries (non inclusive).
3157 if (TgtBinaryDescriptorQTy.isNull()) {
3158 ASTContext &C = CGM.getContext();
3159 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3160 RD->startDefinition();
3161 addFieldToRecordDecl(
3162 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3163 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3164 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3165 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3166 RD->completeDefinition();
3167 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3169 return TgtBinaryDescriptorQTy;
3173 struct PrivateHelpersTy {
3174 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3175 const VarDecl *PrivateElemInit)
3176 : Original(Original), PrivateCopy(PrivateCopy),
3177 PrivateElemInit(PrivateElemInit) {}
3178 const VarDecl *Original;
3179 const VarDecl *PrivateCopy;
3180 const VarDecl *PrivateElemInit;
3182 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3183 } // anonymous namespace
3186 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3187 if (!Privates.empty()) {
3188 auto &C = CGM.getContext();
3189 // Build struct .kmp_privates_t. {
3190 // /* private vars */
3192 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3193 RD->startDefinition();
3194 for (auto &&Pair : Privates) {
3195 auto *VD = Pair.second.Original;
3196 auto Type = VD->getType();
3197 Type = Type.getNonReferenceType();
3198 auto *FD = addFieldToRecordDecl(C, RD, Type);
3199 if (VD->hasAttrs()) {
3200 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3201 E(VD->getAttrs().end());
3206 RD->completeDefinition();
3213 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3214 QualType KmpInt32Ty,
3215 QualType KmpRoutineEntryPointerQTy) {
3216 auto &C = CGM.getContext();
3217 // Build struct kmp_task_t {
3219 // kmp_routine_entry_t routine;
3220 // kmp_int32 part_id;
3221 // kmp_cmplrdata_t data1;
3222 // kmp_cmplrdata_t data2;
3223 // For taskloops additional fields:
3229 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3230 UD->startDefinition();
3231 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3232 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3233 UD->completeDefinition();
3234 QualType KmpCmplrdataTy = C.getRecordType(UD);
3235 auto *RD = C.buildImplicitRecord("kmp_task_t");
3236 RD->startDefinition();
3237 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3238 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3239 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3240 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3241 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3242 if (isOpenMPTaskLoopDirective(Kind)) {
3243 QualType KmpUInt64Ty =
3244 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3245 QualType KmpInt64Ty =
3246 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3247 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3248 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3249 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3250 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3252 RD->completeDefinition();
3257 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3258 ArrayRef<PrivateDataTy> Privates) {
3259 auto &C = CGM.getContext();
3260 // Build struct kmp_task_t_with_privates {
3261 // kmp_task_t task_data;
3262 // .kmp_privates_t. privates;
3264 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3265 RD->startDefinition();
3266 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3267 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3268 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3270 RD->completeDefinition();
3274 /// \brief Emit a proxy function which accepts kmp_task_t as the second
3277 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3278 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3280 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3285 static llvm::Value *
3286 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3287 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3288 QualType KmpTaskTWithPrivatesPtrQTy,
3289 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3290 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3291 llvm::Value *TaskPrivatesMap) {
3292 auto &C = CGM.getContext();
3293 FunctionArgList Args;
3294 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3295 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
3297 KmpTaskTWithPrivatesPtrQTy.withRestrict());
3298 Args.push_back(&GtidArg);
3299 Args.push_back(&TaskTypeArg);
3300 auto &TaskEntryFnInfo =
3301 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3302 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3304 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3305 ".omp_task_entry.", &CGM.getModule());
3306 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
3307 CodeGenFunction CGF(CGM);
3308 CGF.disableDebugInfo();
3309 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3311 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3314 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3315 // tt->task_data.shareds);
3316 auto *GtidParam = CGF.EmitLoadOfScalar(
3317 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3318 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3319 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3320 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3321 auto *KmpTaskTWithPrivatesQTyRD =
3322 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3324 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3325 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3326 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3327 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3328 auto *PartidParam = PartIdLVal.getPointer();
3330 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3331 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3332 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3333 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
3334 CGF.ConvertTypeForMem(SharedsPtrTy));
3336 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3337 llvm::Value *PrivatesParam;
3338 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3339 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3340 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3341 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
3343 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3345 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3348 .CreatePointerBitCastOrAddrSpaceCast(
3349 TDBase.getAddress(), CGF.VoidPtrTy)
3351 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3352 std::end(CommonArgs));
3353 if (isOpenMPTaskLoopDirective(Kind)) {
3354 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3355 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3356 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3357 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3358 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3359 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3360 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3361 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3362 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3363 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3364 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3365 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3366 CallArgs.push_back(LBParam);
3367 CallArgs.push_back(UBParam);
3368 CallArgs.push_back(StParam);
3369 CallArgs.push_back(LIParam);
3371 CallArgs.push_back(SharedsParam);
3373 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3374 CGF.EmitStoreThroughLValue(
3375 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3376 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3377 CGF.FinishFunction();
3381 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3383 QualType KmpInt32Ty,
3384 QualType KmpTaskTWithPrivatesPtrQTy,
3385 QualType KmpTaskTWithPrivatesQTy) {
3386 auto &C = CGM.getContext();
3387 FunctionArgList Args;
3388 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3389 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
3391 KmpTaskTWithPrivatesPtrQTy.withRestrict());
3392 Args.push_back(&GtidArg);
3393 Args.push_back(&TaskTypeArg);
3394 FunctionType::ExtInfo Info;
3395 auto &DestructorFnInfo =
3396 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3397 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3398 auto *DestructorFn =
3399 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3400 ".omp_task_destructor.", &CGM.getModule());
3401 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3403 CodeGenFunction CGF(CGM);
3404 CGF.disableDebugInfo();
3405 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3408 LValue Base = CGF.EmitLoadOfPointerLValue(
3409 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3410 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3411 auto *KmpTaskTWithPrivatesQTyRD =
3412 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3413 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3414 Base = CGF.EmitLValueForField(Base, *FI);
3416 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3417 if (auto DtorKind = Field->getType().isDestructedType()) {
3418 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3419 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3422 CGF.FinishFunction();
3423 return DestructorFn;
3426 /// \brief Emit a privates mapping function for correct handling of private and
3427 /// firstprivate variables.
3429 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3430 /// **noalias priv1,..., <tyn> **noalias privn) {
3431 /// *priv1 = &.privates.priv1;
3433 /// *privn = &.privates.privn;
3436 static llvm::Value *
3437 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3438 ArrayRef<const Expr *> PrivateVars,
3439 ArrayRef<const Expr *> FirstprivateVars,
3440 ArrayRef<const Expr *> LastprivateVars,
3441 QualType PrivatesQTy,
3442 ArrayRef<PrivateDataTy> Privates) {
3443 auto &C = CGM.getContext();
3444 FunctionArgList Args;
3445 ImplicitParamDecl TaskPrivatesArg(
3446 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3447 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3448 Args.push_back(&TaskPrivatesArg);
3449 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3450 unsigned Counter = 1;
3451 for (auto *E: PrivateVars) {
3452 Args.push_back(ImplicitParamDecl::Create(
3453 C, /*DC=*/nullptr, Loc,
3454 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3457 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3458 PrivateVarsPos[VD] = Counter;
3461 for (auto *E : FirstprivateVars) {
3462 Args.push_back(ImplicitParamDecl::Create(
3463 C, /*DC=*/nullptr, Loc,
3464 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3467 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3468 PrivateVarsPos[VD] = Counter;
3471 for (auto *E: LastprivateVars) {
3472 Args.push_back(ImplicitParamDecl::Create(
3473 C, /*DC=*/nullptr, Loc,
3474 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3477 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3478 PrivateVarsPos[VD] = Counter;
3481 auto &TaskPrivatesMapFnInfo =
3482 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3483 auto *TaskPrivatesMapTy =
3484 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3485 auto *TaskPrivatesMap = llvm::Function::Create(
3486 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3487 ".omp_task_privates_map.", &CGM.getModule());
3488 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3489 TaskPrivatesMapFnInfo);
3490 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3491 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3492 CodeGenFunction CGF(CGM);
3493 CGF.disableDebugInfo();
3494 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3495 TaskPrivatesMapFnInfo, Args);
3497 // *privi = &.privates.privi;
3498 LValue Base = CGF.EmitLoadOfPointerLValue(
3499 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3500 TaskPrivatesArg.getType()->castAs<PointerType>());
3501 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3503 for (auto *Field : PrivatesQTyRD->fields()) {
3504 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3505 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3506 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3507 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3508 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
3509 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
3512 CGF.FinishFunction();
3513 return TaskPrivatesMap;
3516 static int array_pod_sort_comparator(const PrivateDataTy *P1,
3517 const PrivateDataTy *P2) {
3518 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3521 /// Emit initialization for private variables in task-based directives.
3522 static void emitPrivatesInit(CodeGenFunction &CGF,
3523 const OMPExecutableDirective &D,
3524 Address KmpTaskSharedsPtr, LValue TDBase,
3525 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3526 QualType SharedsTy, QualType SharedsPtrTy,
3527 const OMPTaskDataTy &Data,
3528 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3529 auto &C = CGF.getContext();
3530 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3531 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3533 if (!Data.FirstprivateVars.empty()) {
3534 SrcBase = CGF.MakeAddrLValue(
3535 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3536 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3539 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3540 cast<CapturedStmt>(*D.getAssociatedStmt()));
3541 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3542 for (auto &&Pair : Privates) {
3543 auto *VD = Pair.second.PrivateCopy;
3544 auto *Init = VD->getAnyInitializer();
3545 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3546 !CGF.isTrivialInitializer(Init)))) {
3547 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3548 if (auto *Elem = Pair.second.PrivateElemInit) {
3549 auto *OriginalVD = Pair.second.Original;
3550 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3551 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3552 SharedRefLValue = CGF.MakeAddrLValue(
3553 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3554 SharedRefLValue.getType(), AlignmentSource::Decl);
3555 QualType Type = OriginalVD->getType();
3556 if (Type->isArrayType()) {
3557 // Initialize firstprivate array.
3558 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3559 // Perform simple memcpy.
3560 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3561 SharedRefLValue.getAddress(), Type);
3563 // Initialize firstprivate array using element-by-element
3565 CGF.EmitOMPAggregateAssign(
3566 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3567 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3568 Address SrcElement) {
3569 // Clean up any temporaries needed by the initialization.
3570 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3571 InitScope.addPrivate(
3572 Elem, [SrcElement]() -> Address { return SrcElement; });
3573 (void)InitScope.Privatize();
3574 // Emit initialization for single element.
3575 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3576 CGF, &CapturesInfo);
3577 CGF.EmitAnyExprToMem(Init, DestElement,
3578 Init->getType().getQualifiers(),
3579 /*IsInitializer=*/false);
3583 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3584 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3585 return SharedRefLValue.getAddress();
3587 (void)InitScope.Privatize();
3588 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3589 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3590 /*capturedByInit=*/false);
3593 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3599 /// Check if duplication function is required for taskloops.
3600 static bool checkInitIsRequired(CodeGenFunction &CGF,
3601 ArrayRef<PrivateDataTy> Privates) {
3602 bool InitRequired = false;
3603 for (auto &&Pair : Privates) {
3604 auto *VD = Pair.second.PrivateCopy;
3605 auto *Init = VD->getAnyInitializer();
3606 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3607 !CGF.isTrivialInitializer(Init));
3609 return InitRequired;
3613 /// Emit task_dup function (for initialization of
3614 /// private/firstprivate/lastprivate vars and last_iter flag)
3616 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3618 /// // setup lastprivate flag
3619 /// task_dst->last = lastpriv;
3620 /// // could be constructor calls here...
3623 static llvm::Value *
3624 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3625 const OMPExecutableDirective &D,
3626 QualType KmpTaskTWithPrivatesPtrQTy,
3627 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3628 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3629 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3630 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3631 auto &C = CGM.getContext();
3632 FunctionArgList Args;
3633 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3634 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3635 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3636 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3637 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3638 /*Id=*/nullptr, C.IntTy);
3639 Args.push_back(&DstArg);
3640 Args.push_back(&SrcArg);
3641 Args.push_back(&LastprivArg);
3642 auto &TaskDupFnInfo =
3643 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3644 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3646 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3647 ".omp_task_dup.", &CGM.getModule());
3648 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3649 CodeGenFunction CGF(CGM);
3650 CGF.disableDebugInfo();
3651 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3653 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3654 CGF.GetAddrOfLocalVar(&DstArg),
3655 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3656 // task_dst->liter = lastpriv;
3658 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3659 LValue Base = CGF.EmitLValueForField(
3660 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3661 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3662 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3663 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3664 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3667 // Emit initial values for private copies (if any).
3668 assert(!Privates.empty());
3669 Address KmpTaskSharedsPtr = Address::invalid();
3670 if (!Data.FirstprivateVars.empty()) {
3671 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3672 CGF.GetAddrOfLocalVar(&SrcArg),
3673 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3674 LValue Base = CGF.EmitLValueForField(
3675 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3676 KmpTaskSharedsPtr = Address(
3677 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3678 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3681 CGF.getNaturalTypeAlignment(SharedsTy));
3683 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3684 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
3685 CGF.FinishFunction();
3689 /// Checks if destructor function is required to be generated.
3690 /// \return true if cleanups are required, false otherwise.
3692 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3693 bool NeedsCleanup = false;
3694 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3695 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3696 for (auto *FD : PrivateRD->fields()) {
3697 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3701 return NeedsCleanup;
3704 CGOpenMPRuntime::TaskResultTy
3705 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3706 const OMPExecutableDirective &D,
3707 llvm::Value *TaskFunction, QualType SharedsTy,
3708 Address Shareds, const OMPTaskDataTy &Data) {
3709 auto &C = CGM.getContext();
3710 llvm::SmallVector<PrivateDataTy, 4> Privates;
3711 // Aggregate privates and sort them by the alignment.
3712 auto I = Data.PrivateCopies.begin();
3713 for (auto *E : Data.PrivateVars) {
3714 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3715 Privates.push_back(std::make_pair(
3717 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3718 /*PrivateElemInit=*/nullptr)));
3721 I = Data.FirstprivateCopies.begin();
3722 auto IElemInitRef = Data.FirstprivateInits.begin();
3723 for (auto *E : Data.FirstprivateVars) {
3724 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3725 Privates.push_back(std::make_pair(
3728 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3729 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
3733 I = Data.LastprivateCopies.begin();
3734 for (auto *E : Data.LastprivateVars) {
3735 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3736 Privates.push_back(std::make_pair(
3738 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3739 /*PrivateElemInit=*/nullptr)));
3742 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3743 array_pod_sort_comparator);
3744 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3745 // Build type kmp_routine_entry_t (if not built yet).
3746 emitKmpRoutineEntryT(KmpInt32Ty);
3747 // Build type kmp_task_t (if not built yet).
3748 if (KmpTaskTQTy.isNull()) {
3749 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3750 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3752 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3753 // Build particular struct kmp_task_t for the given task.
3754 auto *KmpTaskTWithPrivatesQTyRD =
3755 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3756 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3757 QualType KmpTaskTWithPrivatesPtrQTy =
3758 C.getPointerType(KmpTaskTWithPrivatesQTy);
3759 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3760 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
3761 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3762 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3764 // Emit initial values for private copies (if any).
3765 llvm::Value *TaskPrivatesMap = nullptr;
3766 auto *TaskPrivatesMapTy =
3767 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3770 if (!Privates.empty()) {
3771 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3772 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3773 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3774 FI->getType(), Privates);
3775 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3776 TaskPrivatesMap, TaskPrivatesMapTy);
3778 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3779 cast<llvm::PointerType>(TaskPrivatesMapTy));
3781 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3783 auto *TaskEntry = emitProxyTaskFunction(
3784 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3785 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3788 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3789 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3790 // kmp_routine_entry_t *task_entry);
3791 // Task flags. Format is taken from
3792 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3793 // description of kmp_tasking_flags struct.
3797 DestructorsFlag = 0x8,
3800 unsigned Flags = Data.Tied ? TiedFlag : 0;
3801 bool NeedsCleanup = false;
3802 if (!Privates.empty()) {
3803 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3805 Flags = Flags | DestructorsFlag;
3807 if (Data.Priority.getInt())
3808 Flags = Flags | PriorityFlag;
3810 Data.Final.getPointer()
3811 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
3812 CGF.Builder.getInt32(FinalFlag),
3813 CGF.Builder.getInt32(/*C=*/0))
3814 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
3815 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3816 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3817 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3818 getThreadID(CGF, Loc), TaskFlags,
3819 KmpTaskTWithPrivatesTySize, SharedsSize,
3820 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3821 TaskEntry, KmpRoutineEntryPtrTy)};
3822 auto *NewTask = CGF.EmitRuntimeCall(
3823 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
3824 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3825 NewTask, KmpTaskTWithPrivatesPtrTy);
3826 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3827 KmpTaskTWithPrivatesQTy);
3829 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
3830 // Fill the data in the resulting kmp_task_t record.
3831 // Copy shareds if there are any.
3832 Address KmpTaskSharedsPtr = Address::invalid();
3833 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
3835 Address(CGF.EmitLoadOfScalar(
3836 CGF.EmitLValueForField(
3837 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3840 CGF.getNaturalTypeAlignment(SharedsTy));
3841 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
3843 // Emit initial values for private copies (if any).
3844 TaskResultTy Result;
3845 if (!Privates.empty()) {
3846 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3847 SharedsTy, SharedsPtrTy, Data, Privates,
3849 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3850 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3851 Result.TaskDupFn = emitTaskDupFunction(
3852 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3853 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3854 /*WithLastIter=*/!Data.LastprivateVars.empty());
3857 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3858 enum { Priority = 0, Destructors = 1 };
3859 // Provide pointer to function with destructors for privates.
3860 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3861 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3863 llvm::Value *DestructorFn = emitDestructorsFunction(
3864 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3865 KmpTaskTWithPrivatesQTy);
3866 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3867 LValue DestructorsLV = CGF.EmitLValueForField(
3868 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3869 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3870 DestructorFn, KmpRoutineEntryPtrTy),
3874 if (Data.Priority.getInt()) {
3875 LValue Data2LV = CGF.EmitLValueForField(
3876 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3877 LValue PriorityLV = CGF.EmitLValueForField(
3878 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3879 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3881 Result.NewTask = NewTask;
3882 Result.TaskEntry = TaskEntry;
3883 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3884 Result.TDBase = TDBase;
3885 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3889 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3890 const OMPExecutableDirective &D,
3891 llvm::Value *TaskFunction,
3892 QualType SharedsTy, Address Shareds,
3894 const OMPTaskDataTy &Data) {
3895 if (!CGF.HaveInsertPoint())
3898 TaskResultTy Result =
3899 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3900 llvm::Value *NewTask = Result.NewTask;
3901 llvm::Value *TaskEntry = Result.TaskEntry;
3902 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3903 LValue TDBase = Result.TDBase;
3904 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
3905 auto &C = CGM.getContext();
3906 // Process list of dependences.
3907 Address DependenciesArray = Address::invalid();
3908 unsigned NumDependencies = Data.Dependences.size();
3909 if (NumDependencies) {
3910 // Dependence kind for RTL.
3911 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
3912 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3913 RecordDecl *KmpDependInfoRD;
3915 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
3916 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3917 if (KmpDependInfoTy.isNull()) {
3918 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3919 KmpDependInfoRD->startDefinition();
3920 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3921 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3922 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3923 KmpDependInfoRD->completeDefinition();
3924 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3926 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3927 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
3928 // Define type kmp_depend_info[<Dependences.size()>];
3929 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
3930 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
3931 ArrayType::Normal, /*IndexTypeQuals=*/0);
3932 // kmp_depend_info[<Dependences.size()>] deps;
3934 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
3935 for (unsigned i = 0; i < NumDependencies; ++i) {
3936 const Expr *E = Data.Dependences[i].second;
3937 auto Addr = CGF.EmitLValue(E);
3939 QualType Ty = E->getType();
3940 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3942 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3943 llvm::Value *UpAddr =
3944 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
3945 llvm::Value *LowIntPtr =
3946 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
3947 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3948 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3950 Size = CGF.getTypeSize(Ty);
3951 auto Base = CGF.MakeAddrLValue(
3952 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
3954 // deps[i].base_addr = &<Dependences[i].second>;
3955 auto BaseAddrLVal = CGF.EmitLValueForField(
3956 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
3957 CGF.EmitStoreOfScalar(
3958 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3960 // deps[i].len = sizeof(<Dependences[i].second>);
3961 auto LenLVal = CGF.EmitLValueForField(
3962 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3963 CGF.EmitStoreOfScalar(Size, LenLVal);
3964 // deps[i].flags = <Dependences[i].first>;
3965 RTLDependenceKindTy DepKind;
3966 switch (Data.Dependences[i].first) {
3967 case OMPC_DEPEND_in:
3970 // Out and InOut dependencies must use the same code.
3971 case OMPC_DEPEND_out:
3972 case OMPC_DEPEND_inout:
3975 case OMPC_DEPEND_source:
3976 case OMPC_DEPEND_sink:
3977 case OMPC_DEPEND_unknown:
3978 llvm_unreachable("Unknown task dependence type");
3980 auto FlagsLVal = CGF.EmitLValueForField(
3981 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3982 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3985 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3986 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
3990 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3992 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3993 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3994 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3995 // list is not empty
3996 auto *ThreadID = getThreadID(CGF, Loc);
3997 auto *UpLoc = emitUpdateLocation(CGF, Loc);
3998 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3999 llvm::Value *DepTaskArgs[7];
4000 if (NumDependencies) {
4001 DepTaskArgs[0] = UpLoc;
4002 DepTaskArgs[1] = ThreadID;
4003 DepTaskArgs[2] = NewTask;
4004 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4005 DepTaskArgs[4] = DependenciesArray.getPointer();
4006 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4007 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4009 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
4010 NumDependencies, &TaskArgs,
4011 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4013 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4014 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4015 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4017 if (NumDependencies) {
4018 CGF.EmitRuntimeCall(
4019 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
4021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
4024 // Check if parent region is untied and build return for untied task;
4026 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4027 Region->emitUntiedSwitch(CGF);
4030 llvm::Value *DepWaitTaskArgs[6];
4031 if (NumDependencies) {
4032 DepWaitTaskArgs[0] = UpLoc;
4033 DepWaitTaskArgs[1] = ThreadID;
4034 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4035 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4036 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4037 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4039 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4040 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4041 PrePostActionTy &) {
4042 auto &RT = CGF.CGM.getOpenMPRuntime();
4043 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4044 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4045 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4046 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4048 if (NumDependencies)
4049 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
4051 // Call proxy_task_entry(gtid, new_task);
4052 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4053 CodeGenFunction &CGF, PrePostActionTy &Action) {
4055 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4056 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4059 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4060 // kmp_task_t *new_task);
4061 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4062 // kmp_task_t *new_task);
4063 RegionCodeGenTy RCG(CodeGen);
4064 CommonActionTy Action(
4065 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4066 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4067 RCG.setAction(Action);
4072 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
4074 RegionCodeGenTy ThenRCG(ThenCodeGen);
4079 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4080 const OMPLoopDirective &D,
4081 llvm::Value *TaskFunction,
4082 QualType SharedsTy, Address Shareds,
4084 const OMPTaskDataTy &Data) {
4085 if (!CGF.HaveInsertPoint())
4087 TaskResultTy Result =
4088 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4089 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4091 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4092 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4093 // sched, kmp_uint64 grainsize, void *task_dup);
4094 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4095 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4098 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4101 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4103 LValue LBLVal = CGF.EmitLValueForField(
4105 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
4107 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4108 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4109 /*IsInitializer=*/true);
4110 LValue UBLVal = CGF.EmitLValueForField(
4112 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
4114 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4115 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4116 /*IsInitializer=*/true);
4117 LValue StLVal = CGF.EmitLValueForField(
4119 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
4121 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4122 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4123 /*IsInitializer=*/true);
4124 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
4125 llvm::Value *TaskArgs[] = {
4126 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
4127 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4128 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
4129 llvm::ConstantInt::getSigned(
4130 CGF.IntTy, Data.Schedule.getPointer()
4131 ? Data.Schedule.getInt() ? NumTasks : Grainsize
4133 Data.Schedule.getPointer()
4134 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
4136 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
4138 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4140 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
4141 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4144 /// \brief Emit reduction operation for each element of array (required for
4145 /// array sections) LHS op = RHS.
4146 /// \param Type Type of array.
4147 /// \param LHSVar Variable on the left side of the reduction operation
4148 /// (references element of array in original variable).
4149 /// \param RHSVar Variable on the right side of the reduction operation
4150 /// (references element of array in original variable).
4151 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
4153 static void EmitOMPAggregateReduction(
4154 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4155 const VarDecl *RHSVar,
4156 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4157 const Expr *, const Expr *)> &RedOpGen,
4158 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4159 const Expr *UpExpr = nullptr) {
4160 // Perform element-by-element initialization.
4162 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4163 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4165 // Drill down to the base element type on both arrays.
4166 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4167 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4169 auto RHSBegin = RHSAddr.getPointer();
4170 auto LHSBegin = LHSAddr.getPointer();
4171 // Cast from pointer to array type to pointer to single element.
4172 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4173 // The basic structure here is a while-do loop.
4174 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4175 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4177 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4178 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4180 // Enter the loop body, making that address the current address.
4181 auto EntryBB = CGF.Builder.GetInsertBlock();
4182 CGF.EmitBlock(BodyBB);
4184 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4186 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4187 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4188 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4189 Address RHSElementCurrent =
4190 Address(RHSElementPHI,
4191 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4193 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4194 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4195 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4196 Address LHSElementCurrent =
4197 Address(LHSElementPHI,
4198 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4201 CodeGenFunction::OMPPrivateScope Scope(CGF);
4202 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4203 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4205 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4206 Scope.ForceCleanup();
4208 // Shift the address forward by one element.
4209 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4210 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4211 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4212 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4213 // Check whether we've reached the end.
4215 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4216 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4217 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4218 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4221 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4224 /// Emit reduction combiner. If the combiner is a simple expression emit it as
4225 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4226 /// UDR combiner function.
4227 static void emitReductionCombiner(CodeGenFunction &CGF,
4228 const Expr *ReductionOp) {
4229 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4230 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4232 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4233 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4234 std::pair<llvm::Function *, llvm::Function *> Reduction =
4235 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4236 RValue Func = RValue::get(Reduction.first);
4237 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4238 CGF.EmitIgnoredExpr(ReductionOp);
4241 CGF.EmitIgnoredExpr(ReductionOp);
4244 static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4245 llvm::Type *ArgsType,
4246 ArrayRef<const Expr *> Privates,
4247 ArrayRef<const Expr *> LHSExprs,
4248 ArrayRef<const Expr *> RHSExprs,
4249 ArrayRef<const Expr *> ReductionOps) {
4250 auto &C = CGM.getContext();
4252 // void reduction_func(void *LHSArg, void *RHSArg);
4253 FunctionArgList Args;
4254 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4256 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4258 Args.push_back(&LHSArg);
4259 Args.push_back(&RHSArg);
4260 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4261 auto *Fn = llvm::Function::Create(
4262 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4263 ".omp.reduction.reduction_func", &CGM.getModule());
4264 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
4265 CodeGenFunction CGF(CGM);
4266 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4268 // Dst = (void*[n])(LHSArg);
4269 // Src = (void*[n])(RHSArg);
4270 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4271 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4272 ArgsType), CGF.getPointerAlign());
4273 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4274 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4275 ArgsType), CGF.getPointerAlign());
4278 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4280 CodeGenFunction::OMPPrivateScope Scope(CGF);
4281 auto IPriv = Privates.begin();
4283 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
4284 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4285 Scope.addPrivate(RHSVar, [&]() -> Address {
4286 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
4288 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4289 Scope.addPrivate(LHSVar, [&]() -> Address {
4290 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
4292 QualType PrivTy = (*IPriv)->getType();
4293 if (PrivTy->isVariablyModifiedType()) {
4294 // Get array size and emit VLA type.
4297 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4298 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
4299 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4300 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
4301 CodeGenFunction::OpaqueValueMapping OpaqueMap(
4302 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
4303 CGF.EmitVariablyModifiedType(PrivTy);
4307 IPriv = Privates.begin();
4308 auto ILHS = LHSExprs.begin();
4309 auto IRHS = RHSExprs.begin();
4310 for (auto *E : ReductionOps) {
4311 if ((*IPriv)->getType()->isArrayType()) {
4312 // Emit reduction for array section.
4313 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4314 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4315 EmitOMPAggregateReduction(
4316 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4317 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4318 emitReductionCombiner(CGF, E);
4321 // Emit reduction for array subscript or single variable.
4322 emitReductionCombiner(CGF, E);
4327 Scope.ForceCleanup();
4328 CGF.FinishFunction();
4332 static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4333 const Expr *ReductionOp,
4334 const Expr *PrivateRef,
4335 const DeclRefExpr *LHS,
4336 const DeclRefExpr *RHS) {
4337 if (PrivateRef->getType()->isArrayType()) {
4338 // Emit reduction for array section.
4339 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4340 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4341 EmitOMPAggregateReduction(
4342 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4343 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4344 emitReductionCombiner(CGF, ReductionOp);
4347 // Emit reduction for array subscript or single variable.
4348 emitReductionCombiner(CGF, ReductionOp);
4351 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
4352 ArrayRef<const Expr *> Privates,
4353 ArrayRef<const Expr *> LHSExprs,
4354 ArrayRef<const Expr *> RHSExprs,
4355 ArrayRef<const Expr *> ReductionOps,
4356 bool WithNowait, bool SimpleReduction) {
4357 if (!CGF.HaveInsertPoint())
4359 // Next code should be emitted for reduction:
4361 // static kmp_critical_name lock = { 0 };
4363 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4364 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4366 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4367 // *(Type<n>-1*)rhs[<n>-1]);
4371 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4372 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4373 // RedList, reduce_func, &<lock>)) {
4376 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4378 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4382 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4384 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
4389 // if SimpleReduction is true, only the next code is generated:
4391 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4394 auto &C = CGM.getContext();
4396 if (SimpleReduction) {
4397 CodeGenFunction::RunCleanupsScope Scope(CGF);
4398 auto IPriv = Privates.begin();
4399 auto ILHS = LHSExprs.begin();
4400 auto IRHS = RHSExprs.begin();
4401 for (auto *E : ReductionOps) {
4402 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4403 cast<DeclRefExpr>(*IRHS));
4411 // 1. Build a list of reduction variables.
4412 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4413 auto Size = RHSExprs.size();
4414 for (auto *E : Privates) {
4415 if (E->getType()->isVariablyModifiedType())
4416 // Reserve place for array size.
4419 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4420 QualType ReductionArrayTy =
4421 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4422 /*IndexTypeQuals=*/0);
4423 Address ReductionList =
4424 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4425 auto IPriv = Privates.begin();
4427 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4429 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
4430 CGF.Builder.CreateStore(
4431 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4432 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4434 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4435 // Store array size.
4437 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4438 CGF.getPointerSize());
4439 llvm::Value *Size = CGF.Builder.CreateIntCast(
4441 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4443 CGF.SizeTy, /*isSigned=*/false);
4444 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4449 // 2. Emit reduce_func().
4450 auto *ReductionFn = emitReductionFunction(
4451 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4452 LHSExprs, RHSExprs, ReductionOps);
4454 // 3. Create static kmp_critical_name lock = { 0 };
4455 auto *Lock = getCriticalRegionLock(".reduction");
4457 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4458 // RedList, reduce_func, &<lock>);
4459 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
4460 auto *ThreadId = getThreadID(CGF, Loc);
4461 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4462 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4463 ReductionList.getPointer(), CGF.VoidPtrTy);
4464 llvm::Value *Args[] = {
4465 IdentTLoc, // ident_t *<loc>
4466 ThreadId, // i32 <gtid>
4467 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4468 ReductionArrayTySize, // size_type sizeof(RedList)
4469 RL, // void *RedList
4470 ReductionFn, // void (*) (void *, void *) <reduce_func>
4471 Lock // kmp_critical_name *&<lock>
4473 auto Res = CGF.EmitRuntimeCall(
4474 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4475 : OMPRTL__kmpc_reduce),
4478 // 5. Build switch(res)
4479 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4480 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4484 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4486 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4488 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4489 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4490 CGF.EmitBlock(Case1BB);
4492 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4493 llvm::Value *EndArgs[] = {
4494 IdentTLoc, // ident_t *<loc>
4495 ThreadId, // i32 <gtid>
4496 Lock // kmp_critical_name *&<lock>
4498 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4499 CodeGenFunction &CGF, PrePostActionTy &Action) {
4500 auto IPriv = Privates.begin();
4501 auto ILHS = LHSExprs.begin();
4502 auto IRHS = RHSExprs.begin();
4503 for (auto *E : ReductionOps) {
4504 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4505 cast<DeclRefExpr>(*IRHS));
4511 RegionCodeGenTy RCG(CodeGen);
4512 CommonActionTy Action(
4513 nullptr, llvm::None,
4514 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4515 : OMPRTL__kmpc_end_reduce),
4517 RCG.setAction(Action);
4520 CGF.EmitBranch(DefaultBB);
4524 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4527 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4528 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4529 CGF.EmitBlock(Case2BB);
4531 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4532 CodeGenFunction &CGF, PrePostActionTy &Action) {
4533 auto ILHS = LHSExprs.begin();
4534 auto IRHS = RHSExprs.begin();
4535 auto IPriv = Privates.begin();
4536 for (auto *E : ReductionOps) {
4537 const Expr *XExpr = nullptr;
4538 const Expr *EExpr = nullptr;
4539 const Expr *UpExpr = nullptr;
4540 BinaryOperatorKind BO = BO_Comma;
4541 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4542 if (BO->getOpcode() == BO_Assign) {
4543 XExpr = BO->getLHS();
4544 UpExpr = BO->getRHS();
4547 // Try to emit update expression as a simple atomic.
4548 auto *RHSExpr = UpExpr;
4550 // Analyze RHS part of the whole expression.
4551 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4552 RHSExpr->IgnoreParenImpCasts())) {
4553 // If this is a conditional operator, analyze its condition for
4554 // min/max reduction operator.
4555 RHSExpr = ACO->getCond();
4558 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4559 EExpr = BORHS->getRHS();
4560 BO = BORHS->getOpcode();
4564 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4565 auto &&AtomicRedGen = [BO, VD, IPriv,
4566 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4567 const Expr *EExpr, const Expr *UpExpr) {
4568 LValue X = CGF.EmitLValue(XExpr);
4571 E = CGF.EmitAnyExpr(EExpr);
4572 CGF.EmitOMPAtomicSimpleUpdateExpr(
4573 X, E, BO, /*IsXLHSInRHSPart=*/true,
4574 llvm::AtomicOrdering::Monotonic, Loc,
4575 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4576 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4577 PrivateScope.addPrivate(
4578 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4579 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4580 CGF.emitOMPSimpleStore(
4581 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4582 VD->getType().getNonReferenceType(), Loc);
4585 (void)PrivateScope.Privatize();
4586 return CGF.EmitAnyExpr(UpExpr);
4589 if ((*IPriv)->getType()->isArrayType()) {
4590 // Emit atomic reduction for array section.
4591 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4592 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4593 AtomicRedGen, XExpr, EExpr, UpExpr);
4595 // Emit atomic reduction for array subscript or single variable.
4596 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4598 // Emit as a critical region.
4599 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4600 const Expr *, const Expr *) {
4601 auto &RT = CGF.CGM.getOpenMPRuntime();
4602 RT.emitCriticalRegion(
4603 CGF, ".atomic_reduction",
4604 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4606 emitReductionCombiner(CGF, E);
4610 if ((*IPriv)->getType()->isArrayType()) {
4611 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4612 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4613 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4616 CritRedGen(CGF, nullptr, nullptr, nullptr);
4623 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4625 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4626 llvm::Value *EndArgs[] = {
4627 IdentTLoc, // ident_t *<loc>
4628 ThreadId, // i32 <gtid>
4629 Lock // kmp_critical_name *&<lock>
4631 CommonActionTy Action(nullptr, llvm::None,
4632 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4634 AtomicRCG.setAction(Action);
4639 CGF.EmitBranch(DefaultBB);
4640 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4643 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4644 SourceLocation Loc) {
4645 if (!CGF.HaveInsertPoint())
4647 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4649 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4650 // Ignore return result until untied tasks are supported.
4651 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4652 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4653 Region->emitUntiedSwitch(CGF);
4656 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
4657 OpenMPDirectiveKind InnerKind,
4658 const RegionCodeGenTy &CodeGen,
4660 if (!CGF.HaveInsertPoint())
4662 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
4663 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
4674 } // anonymous namespace
4676 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4677 RTCancelKind CancelKind = CancelNoreq;
4678 if (CancelRegion == OMPD_parallel)
4679 CancelKind = CancelParallel;
4680 else if (CancelRegion == OMPD_for)
4681 CancelKind = CancelLoop;
4682 else if (CancelRegion == OMPD_sections)
4683 CancelKind = CancelSections;
4685 assert(CancelRegion == OMPD_taskgroup);
4686 CancelKind = CancelTaskgroup;
4691 void CGOpenMPRuntime::emitCancellationPointCall(
4692 CodeGenFunction &CGF, SourceLocation Loc,
4693 OpenMPDirectiveKind CancelRegion) {
4694 if (!CGF.HaveInsertPoint())
4696 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4697 // global_tid, kmp_int32 cncl_kind);
4698 if (auto *OMPRegionInfo =
4699 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4700 if (OMPRegionInfo->hasCancel()) {
4701 llvm::Value *Args[] = {
4702 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4703 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4704 // Ignore return result until untied tasks are supported.
4705 auto *Result = CGF.EmitRuntimeCall(
4706 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4707 // if (__kmpc_cancellationpoint()) {
4708 // __kmpc_cancel_barrier();
4709 // exit from construct;
4711 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4712 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4713 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4714 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4715 CGF.EmitBlock(ExitBB);
4716 // __kmpc_cancel_barrier();
4717 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4718 // exit from construct;
4720 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4721 CGF.EmitBranchThroughCleanup(CancelDest);
4722 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4727 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
4729 OpenMPDirectiveKind CancelRegion) {
4730 if (!CGF.HaveInsertPoint())
4732 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4733 // kmp_int32 cncl_kind);
4734 if (auto *OMPRegionInfo =
4735 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4736 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4737 PrePostActionTy &) {
4738 auto &RT = CGF.CGM.getOpenMPRuntime();
4739 llvm::Value *Args[] = {
4740 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
4741 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4742 // Ignore return result until untied tasks are supported.
4743 auto *Result = CGF.EmitRuntimeCall(
4744 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4745 // if (__kmpc_cancel()) {
4746 // __kmpc_cancel_barrier();
4747 // exit from construct;
4749 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4750 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4751 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4752 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4753 CGF.EmitBlock(ExitBB);
4754 // __kmpc_cancel_barrier();
4755 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4756 // exit from construct;
4758 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4759 CGF.EmitBranchThroughCleanup(CancelDest);
4760 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4763 emitOMPIfClause(CGF, IfCond, ThenGen,
4764 [](CodeGenFunction &, PrePostActionTy &) {});
4766 RegionCodeGenTy ThenRCG(ThenGen);
4772 /// \brief Obtain information that uniquely identifies a target entry. This
4773 /// consists of the file and device IDs as well as line number associated with
4774 /// the relevant entry source location.
4775 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4776 unsigned &DeviceID, unsigned &FileID,
4777 unsigned &LineNum) {
4779 auto &SM = C.getSourceManager();
4781 // The loc should be always valid and have a file ID (the user cannot use
4782 // #pragma directives in macros)
4784 assert(Loc.isValid() && "Source location is expected to be always valid.");
4785 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4787 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4788 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4790 llvm::sys::fs::UniqueID ID;
4791 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4792 llvm_unreachable("Source file with target region no longer exists!");
4794 DeviceID = ID.getDevice();
4795 FileID = ID.getFile();
4796 LineNum = PLoc.getLine();
4799 void CGOpenMPRuntime::emitTargetOutlinedFunction(
4800 const OMPExecutableDirective &D, StringRef ParentName,
4801 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4802 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4803 assert(!ParentName.empty() && "Invalid target region parent name!");
4805 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4806 IsOffloadEntry, CodeGen);
4809 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4810 const OMPExecutableDirective &D, StringRef ParentName,
4811 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4812 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4813 // Create a unique name for the entry function using the source location
4814 // information of the current target region. The name will be something like:
4816 // __omp_offloading_DD_FFFF_PP_lBB
4818 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
4819 // mangled name of the function that encloses the target region and BB is the
4820 // line number of the target region.
4825 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
4827 SmallString<64> EntryFnName;
4829 llvm::raw_svector_ostream OS(EntryFnName);
4830 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4831 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
4834 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4836 CodeGenFunction CGF(CGM, true);
4837 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
4838 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4840 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4842 // If this target outline function is not an offload entry, we don't need to
4844 if (!IsOffloadEntry)
4847 // The target region ID is used by the runtime library to identify the current
4848 // target region, so it only has to be unique and not necessarily point to
4849 // anything. It could be the pointer to the outlined function that implements
4850 // the target region, but we aren't using that so that the compiler doesn't
4851 // need to keep that, and could therefore inline the host function if proven
4852 // worthwhile during optimization. In the other hand, if emitting code for the
4853 // device, the ID has to be the function address so that it can retrieved from
4854 // the offloading entry and launched by the runtime library. We also mark the
4855 // outlined function to have external linkage in case we are emitting code for
4856 // the device, because these functions will be entry points to the device.
4858 if (CGM.getLangOpts().OpenMPIsDevice) {
4859 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4860 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4862 OutlinedFnID = new llvm::GlobalVariable(
4863 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4864 llvm::GlobalValue::PrivateLinkage,
4865 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4867 // Register the information for the entry associated with this target region.
4868 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
4869 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4873 /// discard all CompoundStmts intervening between two constructs
4874 static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4875 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4876 Body = CS->body_front();
4881 /// \brief Emit the num_teams clause of an enclosed teams directive at the
4882 /// target region scope. If there is no teams directive associated with the
4883 /// target directive, or if there is no num_teams clause associated with the
4884 /// enclosed teams directive, return nullptr.
4885 static llvm::Value *
4886 emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4887 CodeGenFunction &CGF,
4888 const OMPExecutableDirective &D) {
4890 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4891 "teams directive expected to be "
4892 "emitted only for the host!");
4894 // FIXME: For the moment we do not support combined directives with target and
4895 // teams, so we do not expect to get any num_teams clause in the provided
4896 // directive. Once we support that, this assertion can be replaced by the
4897 // actual emission of the clause expression.
4898 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4899 "Not expecting clause in directive.");
4901 // If the current target region has a teams region enclosed, we need to get
4902 // the number of teams to pass to the runtime function call. This is done
4903 // by generating the expression in a inlined region. This is required because
4904 // the expression is captured in the enclosing target environment when the
4905 // teams directive is not combined with target.
4907 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4909 // FIXME: Accommodate other combined directives with teams when they become
4911 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4912 ignoreCompoundStmts(CS.getCapturedStmt()))) {
4913 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4914 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4915 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4916 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4917 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4921 // If we have an enclosed teams directive but no num_teams clause we use
4922 // the default value 0.
4923 return CGF.Builder.getInt32(0);
4926 // No teams associated with the directive.
4930 /// \brief Emit the thread_limit clause of an enclosed teams directive at the
4931 /// target region scope. If there is no teams directive associated with the
4932 /// target directive, or if there is no thread_limit clause associated with the
4933 /// enclosed teams directive, return nullptr.
4934 static llvm::Value *
4935 emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4936 CodeGenFunction &CGF,
4937 const OMPExecutableDirective &D) {
4939 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4940 "teams directive expected to be "
4941 "emitted only for the host!");
4943 // FIXME: For the moment we do not support combined directives with target and
4944 // teams, so we do not expect to get any thread_limit clause in the provided
4945 // directive. Once we support that, this assertion can be replaced by the
4946 // actual emission of the clause expression.
4947 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4948 "Not expecting clause in directive.");
4950 // If the current target region has a teams region enclosed, we need to get
4951 // the thread limit to pass to the runtime function call. This is done
4952 // by generating the expression in a inlined region. This is required because
4953 // the expression is captured in the enclosing target environment when the
4954 // teams directive is not combined with target.
4956 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4958 // FIXME: Accommodate other combined directives with teams when they become
4960 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4961 ignoreCompoundStmts(CS.getCapturedStmt()))) {
4962 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4963 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4964 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4965 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4966 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4970 // If we have an enclosed teams directive but no thread_limit clause we use
4971 // the default value 0.
4972 return CGF.Builder.getInt32(0);
4975 // No teams associated with the directive.
4980 // \brief Utility to handle information from clauses associated with a given
4981 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4982 // It provides a convenient interface to obtain the information and generate
4983 // code for that information.
4984 class MappableExprsHandler {
4986 /// \brief Values for bit flags used to specify the mapping type for
4988 enum OpenMPOffloadMappingFlags {
4989 /// \brief Allocate memory on the device and move data from host to device.
4991 /// \brief Allocate memory on the device and move data from device to host.
4992 OMP_MAP_FROM = 0x02,
4993 /// \brief Always perform the requested mapping action on the element, even
4994 /// if it was already mapped before.
4995 OMP_MAP_ALWAYS = 0x04,
4996 /// \brief Delete the element from the device environment, ignoring the
4997 /// current reference count associated with the element.
4998 OMP_MAP_DELETE = 0x08,
4999 /// \brief The element being mapped is a pointer, therefore the pointee
5000 /// should be mapped as well.
5001 OMP_MAP_IS_PTR = 0x10,
5002 /// \brief This flags signals that an argument is the first one relating to
5003 /// a map/private clause expression. For some cases a single
5004 /// map/privatization results in multiple arguments passed to the runtime
5006 OMP_MAP_FIRST_REF = 0x20,
5007 /// \brief Signal that the runtime library has to return the device pointer
5008 /// in the current position for the data being mapped.
5009 OMP_MAP_RETURN_PTR = 0x40,
5010 /// \brief This flag signals that the reference being passed is a pointer to
5012 OMP_MAP_PRIVATE_PTR = 0x80,
5013 /// \brief Pass the element to the device by value.
5014 OMP_MAP_PRIVATE_VAL = 0x100,
5017 /// Class that associates information with a base pointer to be passed to the
5018 /// runtime library.
5019 class BasePointerInfo {
5020 /// The base pointer.
5021 llvm::Value *Ptr = nullptr;
5022 /// The base declaration that refers to this device pointer, or null if
5024 const ValueDecl *DevPtrDecl = nullptr;
5027 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5028 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5029 llvm::Value *operator*() const { return Ptr; }
5030 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5031 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5034 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
5035 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5036 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5039 /// \brief Directive from where the map clauses were extracted.
5040 const OMPExecutableDirective &CurDir;
5042 /// \brief Function the directive is being generated for.
5043 CodeGenFunction &CGF;
5045 /// \brief Set of all first private variables in the current directive.
5046 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5048 /// Map between device pointer declarations and their expression components.
5049 /// The key value for declarations in 'this' is null.
5052 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5055 llvm::Value *getExprTypeSize(const Expr *E) const {
5056 auto ExprTy = E->getType().getCanonicalType();
5058 // Reference types are ignored for mapping purposes.
5059 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5060 ExprTy = RefTy->getPointeeType().getCanonicalType();
5062 // Given that an array section is considered a built-in type, we need to
5063 // do the calculation based on the length of the section instead of relying
5064 // on CGF.getTypeSize(E->getType()).
5065 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5066 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5067 OAE->getBase()->IgnoreParenImpCasts())
5068 .getCanonicalType();
5070 // If there is no length associated with the expression, that means we
5071 // are using the whole length of the base.
5072 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5073 return CGF.getTypeSize(BaseTy);
5075 llvm::Value *ElemSize;
5076 if (auto *PTy = BaseTy->getAs<PointerType>())
5077 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5079 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5080 assert(ATy && "Expecting array type if not a pointer type.");
5081 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5084 // If we don't have a length at this point, that is because we have an
5085 // array section with a single element.
5086 if (!OAE->getLength())
5089 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5091 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5092 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5094 return CGF.getTypeSize(ExprTy);
5097 /// \brief Return the corresponding bits for a given map clause modifier. Add
5098 /// a flag marking the map as a pointer if requested. Add a flag marking the
5099 /// map as the first one of a series of maps that relate to the same map
5101 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5102 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
5103 bool AddIsFirstFlag) const {
5106 case OMPC_MAP_alloc:
5107 case OMPC_MAP_release:
5108 // alloc and release is the default behavior in the runtime library, i.e.
5109 // if we don't pass any bits alloc/release that is what the runtime is
5110 // going to do. Therefore, we don't need to signal anything for these two
5117 Bits = OMP_MAP_FROM;
5119 case OMPC_MAP_tofrom:
5120 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5122 case OMPC_MAP_delete:
5123 Bits = OMP_MAP_DELETE;
5126 llvm_unreachable("Unexpected map type!");
5130 Bits |= OMP_MAP_IS_PTR;
5132 Bits |= OMP_MAP_FIRST_REF;
5133 if (MapTypeModifier == OMPC_MAP_always)
5134 Bits |= OMP_MAP_ALWAYS;
5138 /// \brief Return true if the provided expression is a final array section. A
5139 /// final array section, is one whose length can't be proved to be one.
5140 bool isFinalArraySectionExpression(const Expr *E) const {
5141 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5143 // It is not an array section and therefore not a unity-size one.
5147 // An array section with no colon always refer to a single element.
5148 if (OASE->getColonLoc().isInvalid())
5151 auto *Length = OASE->getLength();
5153 // If we don't have a length we have to check if the array has size 1
5154 // for this dimension. Also, we should always expect a length if the
5155 // base type is pointer.
5157 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5158 OASE->getBase()->IgnoreParenImpCasts())
5159 .getCanonicalType();
5160 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5161 return ATy->getSize().getSExtValue() != 1;
5162 // If we don't have a constant dimension length, we have to consider
5163 // the current section as having any size, so it is not necessarily
5164 // unitary. If it happen to be unity size, that's user fault.
5168 // Check if the length evaluates to 1.
5169 llvm::APSInt ConstLength;
5170 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5171 return true; // Can have more that size 1.
5173 return ConstLength.getSExtValue() != 1;
5176 /// \brief Generate the base pointers, section pointers, sizes and map type
5177 /// bits for the provided map type, map modifier, and expression components.
5178 /// \a IsFirstComponent should be set to true if the provided set of
5179 /// components is the first associated with a capture.
5180 void generateInfoForComponentList(
5181 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5182 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5183 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
5184 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5185 bool IsFirstComponentList) const {
5187 // The following summarizes what has to be generated for each map and the
5188 // types bellow. The generated information is expressed in this order:
5189 // base pointer, section pointer, size, flags
5190 // (to add to the ones that come from the map type and modifier).
5211 // &d, &d, sizeof(double), noflags
5214 // &i, &i, 100*sizeof(int), noflags
5217 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5220 // &p, &p, sizeof(float*), noflags
5223 // p, &p[1], 24*sizeof(float), noflags
5226 // &s, &s, sizeof(S2), noflags
5229 // &s, &(s.i), sizeof(int), noflags
5232 // &s, &(s.i.f), 50*sizeof(int), noflags
5235 // &s, &(s.p), sizeof(double*), noflags
5237 // map(s.p[:22], s.a s.b)
5238 // &s, &(s.p), sizeof(double*), noflags
5239 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5242 // &s, &(s.ps), sizeof(S2*), noflags
5245 // &s, &(s.ps), sizeof(S2*), noflags
5246 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5249 // &s, &(s.ps), sizeof(S2*), noflags
5250 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5252 // map(s.ps->ps->ps)
5253 // &s, &(s.ps), sizeof(S2*), noflags
5254 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5255 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5257 // map(s.ps->ps->s.f[:22])
5258 // &s, &(s.ps), sizeof(S2*), noflags
5259 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5260 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5263 // &ps, &ps, sizeof(S2*), noflags
5266 // ps, &(ps->i), sizeof(int), noflags
5269 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5272 // ps, &(ps->p), sizeof(double*), noflags
5275 // ps, &(ps->p), sizeof(double*), noflags
5276 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5279 // ps, &(ps->ps), sizeof(S2*), noflags
5282 // ps, &(ps->ps), sizeof(S2*), noflags
5283 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5286 // ps, &(ps->ps), sizeof(S2*), noflags
5287 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5289 // map(ps->ps->ps->ps)
5290 // ps, &(ps->ps), sizeof(S2*), noflags
5291 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5292 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5294 // map(ps->ps->ps->s.f[:22])
5295 // ps, &(ps->ps), sizeof(S2*), noflags
5296 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5297 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5300 // Track if the map information being generated is the first for a capture.
5301 bool IsCaptureFirstInfo = IsFirstComponentList;
5303 // Scan the components from the base to the complete expression.
5304 auto CI = Components.rbegin();
5305 auto CE = Components.rend();
5308 // Track if the map information being generated is the first for a list of
5310 bool IsExpressionFirstInfo = true;
5311 llvm::Value *BP = nullptr;
5313 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5314 // The base is the 'this' pointer. The content of the pointer is going
5315 // to be the base of the field being mapped.
5316 BP = CGF.EmitScalarExpr(ME->getBase());
5318 // The base is the reference to the variable.
5320 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5323 // If the variable is a pointer and is being dereferenced (i.e. is not
5324 // the last component), the base has to be the pointer itself, not its
5325 // reference. References are ignored for mapping purposes.
5327 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5328 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5329 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
5330 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
5331 Ty->castAs<PointerType>())
5334 // We do not need to generate individual map information for the
5335 // pointer, it can be associated with the combined storage.
5340 for (; I != CE; ++I) {
5341 auto Next = std::next(I);
5343 // We need to generate the addresses and sizes if this is the last
5344 // component, if the component is a pointer or if it is an array section
5345 // whose length can't be proved to be one. If this is a pointer, it
5346 // becomes the base address for the following components.
5348 // A final array section, is one whose length can't be proved to be one.
5349 bool IsFinalArraySection =
5350 isFinalArraySectionExpression(I->getAssociatedExpression());
5352 // Get information on whether the element is a pointer. Have to do a
5353 // special treatment for array sections given that they are built-in
5356 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5359 OMPArraySectionExpr::getBaseOriginalType(OASE)
5361 ->isAnyPointerType()) ||
5362 I->getAssociatedExpression()->getType()->isAnyPointerType();
5364 if (Next == CE || IsPointer || IsFinalArraySection) {
5366 // If this is not the last component, we expect the pointer to be
5367 // associated with an array expression or member expression.
5368 assert((Next == CE ||
5369 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5370 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5371 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5372 "Unexpected expression");
5374 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5375 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5377 // If we have a member expression and the current component is a
5378 // reference, we have to map the reference too. Whenever we have a
5379 // reference, the section that reference refers to is going to be a
5380 // load instruction from the storage assigned to the reference.
5381 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5382 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5383 auto *LI = cast<llvm::LoadInst>(LB);
5384 auto *RefAddr = LI->getPointerOperand();
5386 BasePointers.push_back(BP);
5387 Pointers.push_back(RefAddr);
5388 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5389 Types.push_back(getMapTypeBits(
5390 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5391 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5392 IsExpressionFirstInfo = false;
5393 IsCaptureFirstInfo = false;
5394 // The reference will be the next base address.
5398 BasePointers.push_back(BP);
5399 Pointers.push_back(LB);
5400 Sizes.push_back(Size);
5402 // We need to add a pointer flag for each map that comes from the
5403 // same expression except for the first one. We also need to signal
5404 // this map is the first one that relates with the current capture
5405 // (there is a set of entries for each capture).
5406 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5407 !IsExpressionFirstInfo,
5408 IsCaptureFirstInfo));
5410 // If we have a final array section, we are done with this expression.
5411 if (IsFinalArraySection)
5414 // The pointer becomes the base for the next element.
5418 IsExpressionFirstInfo = false;
5419 IsCaptureFirstInfo = false;
5425 /// \brief Return the adjusted map modifiers if the declaration a capture
5426 /// refers to appears in a first-private clause. This is expected to be used
5427 /// only with directives that start with 'target'.
5428 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5429 unsigned CurrentModifiers) {
5430 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5432 // A first private variable captured by reference will use only the
5433 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5434 // declaration is known as first-private in this handler.
5435 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5436 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5437 MappableExprsHandler::OMP_MAP_TO;
5439 // We didn't modify anything.
5440 return CurrentModifiers;
5444 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
5445 : CurDir(Dir), CGF(CGF) {
5446 // Extract firstprivate clause information.
5447 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5448 for (const auto *D : C->varlists())
5449 FirstPrivateDecls.insert(
5450 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
5451 // Extract device pointer clause information.
5452 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5453 for (auto L : C->component_lists())
5454 DevPointersMap[L.first].push_back(L.second);
5457 /// \brief Generate all the base pointers, section pointers, sizes and map
5458 /// types for the extracted mappable expressions. Also, for each item that
5459 /// relates with a device pointer, a pair of the relevant declaration and
5460 /// index where it occurs is appended to the device pointers info array.
5461 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
5462 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5463 MapFlagsArrayTy &Types) const {
5464 BasePointers.clear();
5470 /// Kind that defines how a device pointer has to be returned.
5471 enum ReturnPointerKind {
5472 // Don't have to return any pointer.
5474 // Pointer is the base of the declaration.
5476 // Pointer is a member of the base declaration - 'this'
5478 // Pointer is a reference and a member of the base declaration - 'this'
5479 RPK_MemberReference,
5481 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5482 OpenMPMapClauseKind MapType;
5483 OpenMPMapClauseKind MapTypeModifier;
5484 ReturnPointerKind ReturnDevicePointer;
5487 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5488 ReturnDevicePointer(RPK_None) {}
5490 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5491 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5492 ReturnPointerKind ReturnDevicePointer)
5493 : Components(Components), MapType(MapType),
5494 MapTypeModifier(MapTypeModifier),
5495 ReturnDevicePointer(ReturnDevicePointer) {}
5498 // We have to process the component lists that relate with the same
5499 // declaration in a single chunk so that we can generate the map flags
5500 // correctly. Therefore, we organize all lists in a map.
5501 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
5503 // Helper function to fill the information map for the different supported
5505 auto &&InfoGen = [&Info](
5507 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5508 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
5509 MapInfo::ReturnPointerKind ReturnDevicePointer) {
5510 const ValueDecl *VD =
5511 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5512 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5515 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5516 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5517 for (auto L : C->component_lists())
5518 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5520 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
5521 for (auto L : C->component_lists())
5522 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5524 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
5525 for (auto L : C->component_lists())
5526 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5529 // Look at the use_device_ptr clause information and mark the existing map
5530 // entries as such. If there is no map information for an entry in the
5531 // use_device_ptr list, we create one with map type 'alloc' and zero size
5532 // section. It is the user fault if that was not mapped before.
5533 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5534 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
5535 for (auto L : C->component_lists()) {
5536 assert(!L.second.empty() && "Not expecting empty list of components!");
5537 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5538 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5539 auto *IE = L.second.back().getAssociatedExpression();
5540 // If the first component is a member expression, we have to look into
5541 // 'this', which maps to null in the map of map information. Otherwise
5542 // look directly for the information.
5543 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5545 // We potentially have map information for this declaration already.
5546 // Look for the first set of components that refer to it.
5547 if (It != Info.end()) {
5548 auto CI = std::find_if(
5549 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5550 return MI.Components.back().getAssociatedDeclaration() == VD;
5552 // If we found a map entry, signal that the pointer has to be returned
5553 // and move on to the next declaration.
5554 if (CI != It->second.end()) {
5555 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5556 ? (VD->getType()->isReferenceType()
5557 ? MapInfo::RPK_MemberReference
5558 : MapInfo::RPK_Member)
5559 : MapInfo::RPK_Base;
5564 // We didn't find any match in our map information - generate a zero
5565 // size array section.
5566 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
5569 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
5571 BasePointers.push_back({Ptr, VD});
5572 Pointers.push_back(Ptr);
5573 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
5574 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5577 for (auto &M : Info) {
5578 // We need to know when we generate information for the first component
5579 // associated with a capture, because the mapping flags depend on it.
5580 bool IsFirstComponentList = true;
5581 for (MapInfo &L : M.second) {
5582 assert(!L.Components.empty() &&
5583 "Not expecting declaration with no component lists.");
5585 // Remember the current base pointer index.
5586 unsigned CurrentBasePointersIdx = BasePointers.size();
5587 // FIXME: MSVC 2013 seems to require this-> to find the member method.
5588 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5589 L.Components, BasePointers, Pointers,
5590 Sizes, Types, IsFirstComponentList);
5592 // If this entry relates with a device pointer, set the relevant
5593 // declaration and add the 'return pointer' flag.
5594 if (IsFirstComponentList &&
5595 L.ReturnDevicePointer != MapInfo::RPK_None) {
5596 // If the pointer is not the base of the map, we need to skip the
5597 // base. If it is a reference in a member field, we also need to skip
5598 // the map of the reference.
5599 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5600 ++CurrentBasePointersIdx;
5601 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5602 ++CurrentBasePointersIdx;
5604 assert(BasePointers.size() > CurrentBasePointersIdx &&
5605 "Unexpected number of mapped base pointers.");
5607 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5608 assert(RelevantVD &&
5609 "No relevant declaration related with device pointer??");
5611 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5612 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5614 IsFirstComponentList = false;
5619 /// \brief Generate the base pointers, section pointers, sizes and map types
5620 /// associated to a given capture.
5621 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5623 MapBaseValuesArrayTy &BasePointers,
5624 MapValuesArrayTy &Pointers,
5625 MapValuesArrayTy &Sizes,
5626 MapFlagsArrayTy &Types) const {
5627 assert(!Cap->capturesVariableArrayType() &&
5628 "Not expecting to generate map info for a variable array type!");
5630 BasePointers.clear();
5635 // We need to know when we generating information for the first component
5636 // associated with a capture, because the mapping flags depend on it.
5637 bool IsFirstComponentList = true;
5639 const ValueDecl *VD =
5642 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5644 // If this declaration appears in a is_device_ptr clause we just have to
5645 // pass the pointer by value. If it is a reference to a declaration, we just
5646 // pass its value, otherwise, if it is a member expression, we need to map
5649 auto It = DevPointersMap.find(VD);
5650 if (It != DevPointersMap.end()) {
5651 for (auto L : It->second) {
5652 generateInfoForComponentList(
5653 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5654 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5655 IsFirstComponentList = false;
5659 } else if (DevPointersMap.count(VD)) {
5660 BasePointers.push_back({Arg, VD});
5661 Pointers.push_back(Arg);
5662 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5663 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5667 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5668 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5669 for (auto L : C->decl_component_lists(VD)) {
5670 assert(L.first == VD &&
5671 "We got information for the wrong declaration??");
5672 assert(!L.second.empty() &&
5673 "Not expecting declaration with no component lists.");
5674 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5675 L.second, BasePointers, Pointers, Sizes,
5676 Types, IsFirstComponentList);
5677 IsFirstComponentList = false;
5683 /// \brief Generate the default map information for a given capture \a CI,
5684 /// record field declaration \a RI and captured value \a CV.
5685 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5686 const FieldDecl &RI, llvm::Value *CV,
5687 MapBaseValuesArrayTy &CurBasePointers,
5688 MapValuesArrayTy &CurPointers,
5689 MapValuesArrayTy &CurSizes,
5690 MapFlagsArrayTy &CurMapTypes) {
5692 // Do the default mapping.
5693 if (CI.capturesThis()) {
5694 CurBasePointers.push_back(CV);
5695 CurPointers.push_back(CV);
5696 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5697 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5698 // Default map type.
5699 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
5700 } else if (CI.capturesVariableByCopy()) {
5701 CurBasePointers.push_back(CV);
5702 CurPointers.push_back(CV);
5703 if (!RI.getType()->isAnyPointerType()) {
5704 // We have to signal to the runtime captures passed by value that are
5706 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
5707 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5709 // Pointers are implicitly mapped with a zero size and no flags
5710 // (other than first map that is added for all implicit maps).
5711 CurMapTypes.push_back(0u);
5712 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5715 assert(CI.capturesVariable() && "Expected captured reference.");
5716 CurBasePointers.push_back(CV);
5717 CurPointers.push_back(CV);
5719 const ReferenceType *PtrTy =
5720 cast<ReferenceType>(RI.getType().getTypePtr());
5721 QualType ElementType = PtrTy->getPointeeType();
5722 CurSizes.push_back(CGF.getTypeSize(ElementType));
5723 // The default map type for a scalar/complex type is 'to' because by
5724 // default the value doesn't have to be retrieved. For an aggregate
5725 // type, the default is 'tofrom'.
5726 CurMapTypes.push_back(ElementType->isAggregateType()
5727 ? (OMP_MAP_TO | OMP_MAP_FROM)
5730 // If we have a capture by reference we may need to add the private
5731 // pointer flag if the base declaration shows in some first-private
5733 CurMapTypes.back() =
5734 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5736 // Every default map produces a single argument, so, it is always the
5738 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
5742 enum OpenMPOffloadingReservedDeviceIDs {
5743 /// \brief Device ID if the device was not defined, runtime should get it
5744 /// from environment variables in the spec.
5745 OMP_DEVICEID_UNDEF = -1,
5747 } // anonymous namespace
5749 /// \brief Emit the arrays used to pass the captures and map information to the
5750 /// offloading runtime library. If there is no map or capture information,
5751 /// return nullptr by reference.
5753 emitOffloadingArrays(CodeGenFunction &CGF,
5754 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
5755 MappableExprsHandler::MapValuesArrayTy &Pointers,
5756 MappableExprsHandler::MapValuesArrayTy &Sizes,
5757 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5758 CGOpenMPRuntime::TargetDataInfo &Info) {
5759 auto &CGM = CGF.CGM;
5760 auto &Ctx = CGF.getContext();
5762 // Reset the array information.
5763 Info.clearArrayInfo();
5764 Info.NumberOfPtrs = BasePointers.size();
5766 if (Info.NumberOfPtrs) {
5767 // Detect if we have any capture size requiring runtime evaluation of the
5768 // size so that a constant array could be eventually used.
5769 bool hasRuntimeEvaluationCaptureSize = false;
5770 for (auto *S : Sizes)
5771 if (!isa<llvm::Constant>(S)) {
5772 hasRuntimeEvaluationCaptureSize = true;
5776 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
5777 QualType PointerArrayType =
5778 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5779 /*IndexTypeQuals=*/0);
5781 Info.BasePointersArray =
5782 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5783 Info.PointersArray =
5784 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5786 // If we don't have any VLA types or other types that require runtime
5787 // evaluation, we can use a constant array for the map sizes, otherwise we
5788 // need to fill up the arrays as we do for the pointers.
5789 if (hasRuntimeEvaluationCaptureSize) {
5790 QualType SizeArrayType = Ctx.getConstantArrayType(
5791 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5792 /*IndexTypeQuals=*/0);
5794 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5796 // We expect all the sizes to be constant, so we collect them to create
5797 // a constant array.
5798 SmallVector<llvm::Constant *, 16> ConstSizes;
5799 for (auto S : Sizes)
5800 ConstSizes.push_back(cast<llvm::Constant>(S));
5802 auto *SizesArrayInit = llvm::ConstantArray::get(
5803 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5804 auto *SizesArrayGbl = new llvm::GlobalVariable(
5805 CGM.getModule(), SizesArrayInit->getType(),
5806 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5807 SizesArrayInit, ".offload_sizes");
5808 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5809 Info.SizesArray = SizesArrayGbl;
5812 // The map types are always constant so we don't need to generate code to
5813 // fill arrays. Instead, we create an array constant.
5814 llvm::Constant *MapTypesArrayInit =
5815 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5816 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5817 CGM.getModule(), MapTypesArrayInit->getType(),
5818 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5819 MapTypesArrayInit, ".offload_maptypes");
5820 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5821 Info.MapTypesArray = MapTypesArrayGbl;
5823 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5824 llvm::Value *BPVal = *BasePointers[i];
5825 if (BPVal->getType()->isPointerTy())
5826 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5828 assert(BPVal->getType()->isIntegerTy() &&
5829 "If not a pointer, the value type must be an integer.");
5830 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5832 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
5833 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5834 Info.BasePointersArray, 0, i);
5835 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5836 CGF.Builder.CreateStore(BPVal, BPAddr);
5838 if (Info.requiresDevicePointerInfo())
5839 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5840 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5842 llvm::Value *PVal = Pointers[i];
5843 if (PVal->getType()->isPointerTy())
5844 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5846 assert(PVal->getType()->isIntegerTy() &&
5847 "If not a pointer, the value type must be an integer.");
5848 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5850 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
5851 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5852 Info.PointersArray, 0, i);
5853 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5854 CGF.Builder.CreateStore(PVal, PAddr);
5856 if (hasRuntimeEvaluationCaptureSize) {
5857 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
5858 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5862 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5863 CGF.Builder.CreateStore(
5864 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5870 /// \brief Emit the arguments to be passed to the runtime library based on the
5871 /// arrays of pointers, sizes and map types.
5872 static void emitOffloadingArraysArgument(
5873 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5874 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
5875 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
5876 auto &CGM = CGF.CGM;
5877 if (Info.NumberOfPtrs) {
5878 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5879 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5880 Info.BasePointersArray,
5881 /*Idx0=*/0, /*Idx1=*/0);
5882 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5883 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5887 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5888 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
5889 /*Idx0=*/0, /*Idx1=*/0);
5890 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5891 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5896 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5897 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5898 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5900 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5904 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5905 const OMPExecutableDirective &D,
5906 llvm::Value *OutlinedFn,
5907 llvm::Value *OutlinedFnID,
5908 const Expr *IfCond, const Expr *Device,
5909 ArrayRef<llvm::Value *> CapturedVars) {
5910 if (!CGF.HaveInsertPoint())
5913 assert(OutlinedFn && "Invalid outlined function!");
5915 auto &Ctx = CGF.getContext();
5917 // Fill up the arrays with all the captured variables.
5918 MappableExprsHandler::MapValuesArrayTy KernelArgs;
5919 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
5920 MappableExprsHandler::MapValuesArrayTy Pointers;
5921 MappableExprsHandler::MapValuesArrayTy Sizes;
5922 MappableExprsHandler::MapFlagsArrayTy MapTypes;
5924 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
5925 MappableExprsHandler::MapValuesArrayTy CurPointers;
5926 MappableExprsHandler::MapValuesArrayTy CurSizes;
5927 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5929 // Get mappable expression information.
5930 MappableExprsHandler MEHandler(D, CGF);
5932 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5933 auto RI = CS.getCapturedRecordDecl()->field_begin();
5934 auto CV = CapturedVars.begin();
5935 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5936 CE = CS.capture_end();
5937 CI != CE; ++CI, ++RI, ++CV) {
5941 CurBasePointers.clear();
5942 CurPointers.clear();
5944 CurMapTypes.clear();
5946 // VLA sizes are passed to the outlined region by copy and do not have map
5947 // information associated.
5948 if (CI->capturesVariableArrayType()) {
5949 CurBasePointers.push_back(*CV);
5950 CurPointers.push_back(*CV);
5951 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
5952 // Copy to the device as an argument. No need to retrieve it.
5953 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5954 MappableExprsHandler::OMP_MAP_FIRST_REF);
5956 // If we have any information in the map clause, we use it, otherwise we
5957 // just do a default mapping.
5958 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
5959 CurSizes, CurMapTypes);
5960 if (CurBasePointers.empty())
5961 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5962 CurPointers, CurSizes, CurMapTypes);
5964 // We expect to have at least an element of information for this capture.
5965 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5966 assert(CurBasePointers.size() == CurPointers.size() &&
5967 CurBasePointers.size() == CurSizes.size() &&
5968 CurBasePointers.size() == CurMapTypes.size() &&
5969 "Inconsistent map information sizes!");
5971 // The kernel args are always the first elements of the base pointers
5972 // associated with a capture.
5973 KernelArgs.push_back(*CurBasePointers.front());
5974 // We need to append the results of this capture to what we already have.
5975 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5976 Pointers.append(CurPointers.begin(), CurPointers.end());
5977 Sizes.append(CurSizes.begin(), CurSizes.end());
5978 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
5981 // Keep track on whether the host function has to be executed.
5982 auto OffloadErrorQType =
5983 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
5984 auto OffloadError = CGF.MakeAddrLValue(
5985 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5987 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5990 // Fill up the pointer arrays and transfer execution to the device.
5991 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5992 OutlinedFnID, OffloadError, OffloadErrorQType,
5993 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5994 auto &RT = CGF.CGM.getOpenMPRuntime();
5995 // Emit the offloading arrays.
5996 TargetDataInfo Info;
5997 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5998 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5999 Info.PointersArray, Info.SizesArray,
6000 Info.MapTypesArray, Info);
6002 // On top of the arrays that were filled up, the target offloading call
6003 // takes as arguments the device id as well as the host pointer. The host
6004 // pointer is used by the runtime library to identify the current target
6005 // region, so it only has to be unique and not necessarily point to
6006 // anything. It could be the pointer to the outlined function that
6007 // implements the target region, but we aren't using that so that the
6008 // compiler doesn't need to keep that, and could therefore inline the host
6009 // function if proven worthwhile during optimization.
6011 // From this point on, we need to have an ID of the target region defined.
6012 assert(OutlinedFnID && "Invalid outlined function ID!");
6014 // Emit device ID if any.
6015 llvm::Value *DeviceID;
6017 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6018 CGF.Int32Ty, /*isSigned=*/true);
6020 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6022 // Emit the number of elements in the offloading arrays.
6023 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6025 // Return value of the runtime offloading call.
6026 llvm::Value *Return;
6028 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6029 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
6031 // If we have NumTeams defined this means that we have an enclosed teams
6032 // region. Therefore we also expect to have ThreadLimit defined. These two
6033 // values should be defined in the presence of a teams directive, regardless
6034 // of having any clauses associated. If the user is using teams but no
6035 // clauses, these two values will be the default that should be passed to
6036 // the runtime library - a 32-bit integer with the value zero.
6038 assert(ThreadLimit && "Thread limit expression should be available along "
6039 "with number of teams.");
6040 llvm::Value *OffloadingArgs[] = {
6041 DeviceID, OutlinedFnID,
6042 PointerNum, Info.BasePointersArray,
6043 Info.PointersArray, Info.SizesArray,
6044 Info.MapTypesArray, NumTeams,
6046 Return = CGF.EmitRuntimeCall(
6047 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
6049 llvm::Value *OffloadingArgs[] = {
6050 DeviceID, OutlinedFnID,
6051 PointerNum, Info.BasePointersArray,
6052 Info.PointersArray, Info.SizesArray,
6053 Info.MapTypesArray};
6054 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
6058 CGF.EmitStoreOfScalar(Return, OffloadError);
6061 // Notify that the host version must be executed.
6062 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6063 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
6067 // If we have a target function ID it means that we need to support
6068 // offloading, otherwise, just execute on the host. We need to execute on host
6069 // regardless of the conditional in the if clause if, e.g., the user do not
6070 // specify target triples.
6073 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6075 RegionCodeGenTy ThenRCG(ThenGen);
6079 RegionCodeGenTy ElseRCG(ElseGen);
6083 // Check the error code and execute the host version if required.
6084 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6085 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6086 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6087 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6088 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6090 CGF.EmitBlock(OffloadFailedBlock);
6091 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
6092 CGF.EmitBranch(OffloadContBlock);
6094 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
6097 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6098 StringRef ParentName) {
6102 // If we find a OMP target directive, codegen the outline function and
6103 // register the result.
6104 // FIXME: Add other directives with target when they become supported.
6105 bool isTargetDirective = isa<OMPTargetDirective>(S);
6107 if (isTargetDirective) {
6108 auto *E = cast<OMPExecutableDirective>(S);
6112 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
6115 // Is this a target region that should not be emitted as an entry point? If
6116 // so just signal we are done with this target region.
6117 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6122 llvm::Constant *Addr;
6123 std::tie(Fn, Addr) =
6124 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6125 CGM, cast<OMPTargetDirective>(*E), ParentName,
6126 /*isOffloadEntry=*/true);
6127 assert(Fn && Addr && "Target region emission failed.");
6131 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
6132 if (!E->hasAssociatedStmt())
6135 scanForTargetRegionsFunctions(
6136 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6141 // If this is a lambda function, look into its body.
6142 if (auto *L = dyn_cast<LambdaExpr>(S))
6145 // Keep looking for target regions recursively.
6146 for (auto *II : S->children())
6147 scanForTargetRegionsFunctions(II, ParentName);
6150 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6151 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6153 // If emitting code for the host, we do not process FD here. Instead we do
6154 // the normal code generation.
6155 if (!CGM.getLangOpts().OpenMPIsDevice)
6158 // Try to detect target regions in the function.
6159 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6161 // We should not emit any function other that the ones created during the
6162 // scanning. Therefore, we signal that this function is completely dealt
6167 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6168 if (!CGM.getLangOpts().OpenMPIsDevice)
6171 // Check if there are Ctors/Dtors in this declaration and look for target
6172 // regions in it. We use the complete variant to produce the kernel name
6174 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6175 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6176 for (auto *Ctor : RD->ctors()) {
6177 StringRef ParentName =
6178 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6179 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6181 auto *Dtor = RD->getDestructor();
6183 StringRef ParentName =
6184 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6185 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6189 // If we are in target mode we do not emit any global (declare target is not
6190 // implemented yet). Therefore we signal that GD was processed in this case.
6194 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6195 auto *VD = GD.getDecl();
6196 if (isa<FunctionDecl>(VD))
6197 return emitTargetFunctions(GD);
6199 return emitTargetGlobalVariable(GD);
6202 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6203 // If we have offloading in the current module, we need to emit the entries
6204 // now and register the offloading descriptor.
6205 createOffloadEntriesAndInfoMetadata();
6207 // Create and register the offloading binary descriptors. This is the main
6208 // entity that captures all the information about offloading in the current
6209 // compilation unit.
6210 return createOffloadingBinaryDescriptorRegistration();
6213 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6214 const OMPExecutableDirective &D,
6216 llvm::Value *OutlinedFn,
6217 ArrayRef<llvm::Value *> CapturedVars) {
6218 if (!CGF.HaveInsertPoint())
6221 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6222 CodeGenFunction::RunCleanupsScope Scope(CGF);
6224 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6225 llvm::Value *Args[] = {
6227 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6228 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6229 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6230 RealArgs.append(std::begin(Args), std::end(Args));
6231 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6233 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6234 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6237 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
6238 const Expr *NumTeams,
6239 const Expr *ThreadLimit,
6240 SourceLocation Loc) {
6241 if (!CGF.HaveInsertPoint())
6244 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6246 llvm::Value *NumTeamsVal =
6248 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6249 CGF.CGM.Int32Ty, /* isSigned = */ true)
6250 : CGF.Builder.getInt32(0);
6252 llvm::Value *ThreadLimitVal =
6254 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6255 CGF.CGM.Int32Ty, /* isSigned = */ true)
6256 : CGF.Builder.getInt32(0);
6258 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
6259 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6261 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6265 void CGOpenMPRuntime::emitTargetDataCalls(
6266 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6267 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
6268 if (!CGF.HaveInsertPoint())
6271 // Action used to replace the default codegen action and turn privatization
6273 PrePostActionTy NoPrivAction;
6275 // Generate the code for the opening of the data environment. Capture all the
6276 // arguments of the runtime call by reference because they are used in the
6277 // closing of the region.
6278 auto &&BeginThenGen = [&D, &CGF, Device, &Info, &CodeGen, &NoPrivAction](
6279 CodeGenFunction &CGF, PrePostActionTy &) {
6280 // Fill up the arrays with all the mapped variables.
6281 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6282 MappableExprsHandler::MapValuesArrayTy Pointers;
6283 MappableExprsHandler::MapValuesArrayTy Sizes;
6284 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6286 // Get map clause information.
6287 MappableExprsHandler MCHandler(D, CGF);
6288 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6290 // Fill up the arrays and create the arguments.
6291 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6293 llvm::Value *BasePointersArrayArg = nullptr;
6294 llvm::Value *PointersArrayArg = nullptr;
6295 llvm::Value *SizesArrayArg = nullptr;
6296 llvm::Value *MapTypesArrayArg = nullptr;
6297 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6298 SizesArrayArg, MapTypesArrayArg, Info);
6300 // Emit device ID if any.
6301 llvm::Value *DeviceID = nullptr;
6303 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6304 CGF.Int32Ty, /*isSigned=*/true);
6306 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6308 // Emit the number of elements in the offloading arrays.
6309 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6311 llvm::Value *OffloadingArgs[] = {
6312 DeviceID, PointerNum, BasePointersArrayArg,
6313 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6314 auto &RT = CGF.CGM.getOpenMPRuntime();
6315 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6318 // If device pointer privatization is required, emit the body of the region
6319 // here. It will have to be duplicated: with and without privatization.
6320 if (!Info.CaptureDeviceAddrMap.empty())
6324 // Generate code for the closing of the data region.
6325 auto &&EndThenGen = [&CGF, Device, &Info](CodeGenFunction &CGF,
6326 PrePostActionTy &) {
6327 assert(Info.isValid() && "Invalid data environment closing arguments.");
6329 llvm::Value *BasePointersArrayArg = nullptr;
6330 llvm::Value *PointersArrayArg = nullptr;
6331 llvm::Value *SizesArrayArg = nullptr;
6332 llvm::Value *MapTypesArrayArg = nullptr;
6333 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6334 SizesArrayArg, MapTypesArrayArg, Info);
6336 // Emit device ID if any.
6337 llvm::Value *DeviceID = nullptr;
6339 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6340 CGF.Int32Ty, /*isSigned=*/true);
6342 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6344 // Emit the number of elements in the offloading arrays.
6345 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6347 llvm::Value *OffloadingArgs[] = {
6348 DeviceID, PointerNum, BasePointersArrayArg,
6349 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6350 auto &RT = CGF.CGM.getOpenMPRuntime();
6351 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6355 // If we need device pointer privatization, we need to emit the body of the
6356 // region with no privatization in the 'else' branch of the conditional.
6357 // Otherwise, we don't have to do anything.
6358 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6359 PrePostActionTy &) {
6360 if (!Info.CaptureDeviceAddrMap.empty()) {
6361 CodeGen.setAction(NoPrivAction);
6366 // We don't have to do anything to close the region if the if clause evaluates
6368 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6371 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
6373 RegionCodeGenTy RCG(BeginThenGen);
6377 // If we don't require privatization of device pointers, we emit the body in
6378 // between the runtime calls. This avoids duplicating the body code.
6379 if (Info.CaptureDeviceAddrMap.empty()) {
6380 CodeGen.setAction(NoPrivAction);
6385 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
6387 RegionCodeGenTy RCG(EndThenGen);
6392 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
6393 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6394 const Expr *Device) {
6395 if (!CGF.HaveInsertPoint())
6398 assert((isa<OMPTargetEnterDataDirective>(D) ||
6399 isa<OMPTargetExitDataDirective>(D) ||
6400 isa<OMPTargetUpdateDirective>(D)) &&
6401 "Expecting either target enter, exit data, or update directives.");
6403 // Generate the code for the opening of the data environment.
6404 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6405 // Fill up the arrays with all the mapped variables.
6406 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6407 MappableExprsHandler::MapValuesArrayTy Pointers;
6408 MappableExprsHandler::MapValuesArrayTy Sizes;
6409 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6411 // Get map clause information.
6412 MappableExprsHandler MEHandler(D, CGF);
6413 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6415 // Fill up the arrays and create the arguments.
6416 TargetDataInfo Info;
6417 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6418 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6419 Info.PointersArray, Info.SizesArray,
6420 Info.MapTypesArray, Info);
6422 // Emit device ID if any.
6423 llvm::Value *DeviceID = nullptr;
6425 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6426 CGF.Int32Ty, /*isSigned=*/true);
6428 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6430 // Emit the number of elements in the offloading arrays.
6431 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6433 llvm::Value *OffloadingArgs[] = {
6434 DeviceID, PointerNum, Info.BasePointersArray,
6435 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
6437 auto &RT = CGF.CGM.getOpenMPRuntime();
6438 // Select the right runtime function call for each expected standalone
6440 OpenMPRTLFunction RTLFn;
6441 switch (D.getDirectiveKind()) {
6443 llvm_unreachable("Unexpected standalone target data directive.");
6445 case OMPD_target_enter_data:
6446 RTLFn = OMPRTL__tgt_target_data_begin;
6448 case OMPD_target_exit_data:
6449 RTLFn = OMPRTL__tgt_target_data_end;
6451 case OMPD_target_update:
6452 RTLFn = OMPRTL__tgt_target_data_update;
6455 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
6458 // In the event we get an if clause, we don't have to take any action on the
6460 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6463 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6465 RegionCodeGenTy ThenGenRCG(ThenGen);
6471 /// Kind of parameter in a function with 'declare simd' directive.
6472 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6473 /// Attribute set of the parameter.
6474 struct ParamAttrTy {
6475 ParamKindTy Kind = Vector;
6476 llvm::APSInt StrideOrArg;
6477 llvm::APSInt Alignment;
6481 static unsigned evaluateCDTSize(const FunctionDecl *FD,
6482 ArrayRef<ParamAttrTy> ParamAttrs) {
6483 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6484 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6485 // of that clause. The VLEN value must be power of 2.
6486 // In other case the notion of the function`s "characteristic data type" (CDT)
6487 // is used to compute the vector length.
6488 // CDT is defined in the following order:
6489 // a) For non-void function, the CDT is the return type.
6490 // b) If the function has any non-uniform, non-linear parameters, then the
6491 // CDT is the type of the first such parameter.
6492 // c) If the CDT determined by a) or b) above is struct, union, or class
6493 // type which is pass-by-value (except for the type that maps to the
6494 // built-in complex data type), the characteristic data type is int.
6495 // d) If none of the above three cases is applicable, the CDT is int.
6496 // The VLEN is then determined based on the CDT and the size of vector
6497 // register of that ISA for which current vector version is generated. The
6498 // VLEN is computed using the formula below:
6499 // VLEN = sizeof(vector_register) / sizeof(CDT),
6500 // where vector register size specified in section 3.2.1 Registers and the
6501 // Stack Frame of original AMD64 ABI document.
6502 QualType RetType = FD->getReturnType();
6503 if (RetType.isNull())
6505 ASTContext &C = FD->getASTContext();
6507 if (!RetType.isNull() && !RetType->isVoidType())
6510 unsigned Offset = 0;
6511 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6512 if (ParamAttrs[Offset].Kind == Vector)
6513 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6517 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6518 if (ParamAttrs[I + Offset].Kind == Vector) {
6519 CDT = FD->getParamDecl(I)->getType();
6527 CDT = CDT->getCanonicalTypeUnqualified();
6528 if (CDT->isRecordType() || CDT->isUnionType())
6530 return C.getTypeSize(CDT);
6534 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
6535 const llvm::APSInt &VLENVal,
6536 ArrayRef<ParamAttrTy> ParamAttrs,
6537 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6540 unsigned VecRegSize;
6542 ISADataTy ISAData[] = {
6556 llvm::SmallVector<char, 2> Masked;
6558 case OMPDeclareSimdDeclAttr::BS_Undefined:
6559 Masked.push_back('N');
6560 Masked.push_back('M');
6562 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6563 Masked.push_back('N');
6565 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6566 Masked.push_back('M');
6569 for (auto Mask : Masked) {
6570 for (auto &Data : ISAData) {
6571 SmallString<256> Buffer;
6572 llvm::raw_svector_ostream Out(Buffer);
6573 Out << "_ZGV" << Data.ISA << Mask;
6575 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6576 evaluateCDTSize(FD, ParamAttrs));
6579 for (auto &ParamAttr : ParamAttrs) {
6580 switch (ParamAttr.Kind){
6581 case LinearWithVarStride:
6582 Out << 's' << ParamAttr.StrideOrArg;
6586 if (!!ParamAttr.StrideOrArg)
6587 Out << ParamAttr.StrideOrArg;
6596 if (!!ParamAttr.Alignment)
6597 Out << 'a' << ParamAttr.Alignment;
6599 Out << '_' << Fn->getName();
6600 Fn->addFnAttr(Out.str());
6605 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6606 llvm::Function *Fn) {
6607 ASTContext &C = CGM.getContext();
6608 FD = FD->getCanonicalDecl();
6609 // Map params to their positions in function decl.
6610 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6611 if (isa<CXXMethodDecl>(FD))
6612 ParamPositions.insert({FD, 0});
6613 unsigned ParamPos = ParamPositions.size();
6614 for (auto *P : FD->parameters()) {
6615 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6618 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6619 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6620 // Mark uniform parameters.
6621 for (auto *E : Attr->uniforms()) {
6622 E = E->IgnoreParenImpCasts();
6624 if (isa<CXXThisExpr>(E))
6625 Pos = ParamPositions[FD];
6627 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6628 ->getCanonicalDecl();
6629 Pos = ParamPositions[PVD];
6631 ParamAttrs[Pos].Kind = Uniform;
6633 // Get alignment info.
6634 auto NI = Attr->alignments_begin();
6635 for (auto *E : Attr->aligneds()) {
6636 E = E->IgnoreParenImpCasts();
6639 if (isa<CXXThisExpr>(E)) {
6640 Pos = ParamPositions[FD];
6641 ParmTy = E->getType();
6643 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6644 ->getCanonicalDecl();
6645 Pos = ParamPositions[PVD];
6646 ParmTy = PVD->getType();
6648 ParamAttrs[Pos].Alignment =
6649 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6650 : llvm::APSInt::getUnsigned(
6651 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6655 // Mark linear parameters.
6656 auto SI = Attr->steps_begin();
6657 auto MI = Attr->modifiers_begin();
6658 for (auto *E : Attr->linears()) {
6659 E = E->IgnoreParenImpCasts();
6661 if (isa<CXXThisExpr>(E))
6662 Pos = ParamPositions[FD];
6664 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6665 ->getCanonicalDecl();
6666 Pos = ParamPositions[PVD];
6668 auto &ParamAttr = ParamAttrs[Pos];
6669 ParamAttr.Kind = Linear;
6671 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6672 Expr::SE_AllowSideEffects)) {
6673 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6674 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6675 ParamAttr.Kind = LinearWithVarStride;
6676 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6677 ParamPositions[StridePVD->getCanonicalDecl()]);
6685 llvm::APSInt VLENVal;
6686 if (const Expr *VLEN = Attr->getSimdlen())
6687 VLENVal = VLEN->EvaluateKnownConstInt(C);
6688 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6689 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6690 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6691 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6696 /// Cleanup action for doacross support.
6697 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6699 static const int DoacrossFinArgs = 2;
6703 llvm::Value *Args[DoacrossFinArgs];
6706 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6708 assert(CallArgs.size() == DoacrossFinArgs);
6709 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6711 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6712 if (!CGF.HaveInsertPoint())
6714 CGF.EmitRuntimeCall(RTLFn, Args);
6719 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6720 const OMPLoopDirective &D) {
6721 if (!CGF.HaveInsertPoint())
6724 ASTContext &C = CGM.getContext();
6725 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6727 if (KmpDimTy.isNull()) {
6728 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6729 // kmp_int64 lo; // lower
6730 // kmp_int64 up; // upper
6731 // kmp_int64 st; // stride
6733 RD = C.buildImplicitRecord("kmp_dim");
6734 RD->startDefinition();
6735 addFieldToRecordDecl(C, RD, Int64Ty);
6736 addFieldToRecordDecl(C, RD, Int64Ty);
6737 addFieldToRecordDecl(C, RD, Int64Ty);
6738 RD->completeDefinition();
6739 KmpDimTy = C.getRecordType(RD);
6741 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6743 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6744 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6745 enum { LowerFD = 0, UpperFD, StrideFD };
6746 // Fill dims with data.
6747 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6748 // dims.upper = num_iterations;
6750 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6751 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6752 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6753 Int64Ty, D.getNumIterations()->getExprLoc());
6754 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6757 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6758 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6761 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6762 // kmp_int32 num_dims, struct kmp_dim * dims);
6763 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6764 getThreadID(CGF, D.getLocStart()),
6765 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6766 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6767 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6769 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6770 CGF.EmitRuntimeCall(RTLFn, Args);
6771 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6772 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6773 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6774 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6775 llvm::makeArrayRef(FiniArgs));
6778 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6779 const OMPDependClause *C) {
6781 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6782 const Expr *CounterVal = C->getCounterValue();
6784 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6785 CounterVal->getType(), Int64Ty,
6786 CounterVal->getExprLoc());
6787 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6788 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6789 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6790 getThreadID(CGF, C->getLocStart()),
6791 CntAddr.getPointer()};
6793 if (C->getDependencyKind() == OMPC_DEPEND_source)
6794 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6796 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6797 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6799 CGF.EmitRuntimeCall(RTLFn, Args);