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 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 ThreadIDVar(ThreadIDVar) {
106 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 /// \brief Get a variable or parameter for storing global thread id
110 /// inside OpenMP construct.
111 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
113 /// \brief Get the name of the capture helper.
114 StringRef getHelperName() const override { return ".omp_outlined."; }
116 static bool classof(const CGCapturedStmtInfo *Info) {
117 return CGOpenMPRegionInfo::classof(Info) &&
118 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
119 ParallelOutlinedRegion;
123 /// \brief A variable or parameter storing global thread id for OpenMP
125 const VarDecl *ThreadIDVar;
128 /// \brief API for captured statement code generation in OpenMP constructs.
129 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
131 class UntiedTaskActionTy final : public PrePostActionTy {
133 const VarDecl *PartIDVar;
134 const RegionCodeGenTy UntiedCodeGen;
135 llvm::SwitchInst *UntiedSwitch = nullptr;
138 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
139 const RegionCodeGenTy &UntiedCodeGen)
140 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
141 void Enter(CodeGenFunction &CGF) override {
143 // Emit task switching point.
144 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
145 CGF.GetAddrOfLocalVar(PartIDVar),
146 PartIDVar->getType()->castAs<PointerType>());
147 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
148 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
149 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
150 CGF.EmitBlock(DoneBB);
151 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
152 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
153 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
154 CGF.Builder.GetInsertBlock());
155 emitUntiedSwitch(CGF);
158 void emitUntiedSwitch(CodeGenFunction &CGF) const {
160 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
161 CGF.GetAddrOfLocalVar(PartIDVar),
162 PartIDVar->getType()->castAs<PointerType>());
163 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
166 CodeGenFunction::JumpDest CurPoint =
167 CGF.getJumpDestInCurrentScope(".untied.next.");
168 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
169 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
170 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
171 CGF.Builder.GetInsertBlock());
172 CGF.EmitBranchThroughCleanup(CurPoint);
173 CGF.EmitBlock(CurPoint.getBlock());
176 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
178 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
179 const VarDecl *ThreadIDVar,
180 const RegionCodeGenTy &CodeGen,
181 OpenMPDirectiveKind Kind, bool HasCancel,
182 const UntiedTaskActionTy &Action)
183 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
184 ThreadIDVar(ThreadIDVar), Action(Action) {
185 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
188 /// \brief Get a variable or parameter for storing global thread id
189 /// inside OpenMP construct.
190 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
192 /// \brief Get an LValue for the current ThreadID variable.
193 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
195 /// \brief Get the name of the capture helper.
196 StringRef getHelperName() const override { return ".omp_outlined."; }
198 void emitUntiedSwitch(CodeGenFunction &CGF) override {
199 Action.emitUntiedSwitch(CGF);
202 static bool classof(const CGCapturedStmtInfo *Info) {
203 return CGOpenMPRegionInfo::classof(Info) &&
204 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
209 /// \brief A variable or parameter storing global thread id for OpenMP
211 const VarDecl *ThreadIDVar;
212 /// Action for emitting code for untied tasks.
213 const UntiedTaskActionTy &Action;
216 /// \brief API for inlined captured statement code generation in OpenMP
218 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
220 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
221 const RegionCodeGenTy &CodeGen,
222 OpenMPDirectiveKind Kind, bool HasCancel)
223 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
225 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
227 // \brief Retrieve the value of the context parameter.
228 llvm::Value *getContextValue() const override {
230 return OuterRegionInfo->getContextValue();
231 llvm_unreachable("No context value for inlined OpenMP region");
234 void setContextValue(llvm::Value *V) override {
235 if (OuterRegionInfo) {
236 OuterRegionInfo->setContextValue(V);
239 llvm_unreachable("No context value for inlined OpenMP region");
242 /// \brief Lookup the captured field decl for a variable.
243 const FieldDecl *lookup(const VarDecl *VD) const override {
245 return OuterRegionInfo->lookup(VD);
246 // If there is no outer outlined region,no need to lookup in a list of
247 // captured variables, we can use the original one.
251 FieldDecl *getThisFieldDecl() const override {
253 return OuterRegionInfo->getThisFieldDecl();
257 /// \brief Get a variable or parameter for storing global thread id
258 /// inside OpenMP construct.
259 const VarDecl *getThreadIDVariable() const override {
261 return OuterRegionInfo->getThreadIDVariable();
265 /// \brief Get the name of the capture helper.
266 StringRef getHelperName() const override {
267 if (auto *OuterRegionInfo = getOldCSI())
268 return OuterRegionInfo->getHelperName();
269 llvm_unreachable("No helper name for inlined OpenMP construct");
272 void emitUntiedSwitch(CodeGenFunction &CGF) override {
274 OuterRegionInfo->emitUntiedSwitch(CGF);
277 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
279 static bool classof(const CGCapturedStmtInfo *Info) {
280 return CGOpenMPRegionInfo::classof(Info) &&
281 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
284 ~CGOpenMPInlinedRegionInfo() override = default;
287 /// \brief CodeGen info about outer OpenMP region.
288 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
289 CGOpenMPRegionInfo *OuterRegionInfo;
292 /// \brief API for captured statement code generation in OpenMP target
293 /// constructs. For this captures, implicit parameters are used instead of the
294 /// captured fields. The name of the target region has to be unique in a given
295 /// application so it is provided by the client, because only the client has
296 /// the information to generate that.
297 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
299 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
300 const RegionCodeGenTy &CodeGen, StringRef HelperName)
301 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
302 /*HasCancel=*/false),
303 HelperName(HelperName) {}
305 /// \brief This is unused for target regions because each starts executing
306 /// with a single thread.
307 const VarDecl *getThreadIDVariable() const override { return nullptr; }
309 /// \brief Get the name of the capture helper.
310 StringRef getHelperName() const override { return HelperName; }
312 static bool classof(const CGCapturedStmtInfo *Info) {
313 return CGOpenMPRegionInfo::classof(Info) &&
314 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
318 StringRef HelperName;
321 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
322 llvm_unreachable("No codegen for expressions");
324 /// \brief API for generation of expressions captured in a innermost OpenMP
326 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
328 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
329 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
331 /*HasCancel=*/false),
333 // Make sure the globals captured in the provided statement are local by
334 // using the privatization logic. We assume the same variable is not
335 // captured more than once.
336 for (auto &C : CS.captures()) {
337 if (!C.capturesVariable() && !C.capturesVariableByCopy())
340 const VarDecl *VD = C.getCapturedVar();
341 if (VD->isLocalVarDeclOrParm())
344 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
345 /*RefersToEnclosingVariableOrCapture=*/false,
346 VD->getType().getNonReferenceType(), VK_LValue,
348 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
349 return CGF.EmitLValue(&DRE).getAddress();
352 (void)PrivScope.Privatize();
355 /// \brief Lookup the captured field decl for a variable.
356 const FieldDecl *lookup(const VarDecl *VD) const override {
357 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
362 /// \brief Emit the captured statement body.
363 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
364 llvm_unreachable("No body for expressions");
367 /// \brief Get a variable or parameter for storing global thread id
368 /// inside OpenMP construct.
369 const VarDecl *getThreadIDVariable() const override {
370 llvm_unreachable("No thread id for expressions");
373 /// \brief Get the name of the capture helper.
374 StringRef getHelperName() const override {
375 llvm_unreachable("No helper name for expressions");
378 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
381 /// Private scope to capture global variables.
382 CodeGenFunction::OMPPrivateScope PrivScope;
385 /// \brief RAII for emitting code of OpenMP constructs.
386 class InlinedOpenMPRegionRAII {
387 CodeGenFunction &CGF;
388 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
389 FieldDecl *LambdaThisCaptureField = nullptr;
392 /// \brief Constructs region for combined constructs.
393 /// \param CodeGen Code generation sequence for combined directives. Includes
394 /// a list of functions used for code generation of implicitly inlined
396 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
397 OpenMPDirectiveKind Kind, bool HasCancel)
399 // Start emission for the construct.
400 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
401 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
402 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
403 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
404 CGF.LambdaThisCaptureField = nullptr;
407 ~InlinedOpenMPRegionRAII() {
408 // Restore original CapturedStmtInfo only if we're done with code emission.
410 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
411 delete CGF.CapturedStmtInfo;
412 CGF.CapturedStmtInfo = OldCSI;
413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
418 /// \brief Values for bit flags used in the ident_t to describe the fields.
419 /// All enumeric elements are named and described in accordance with the code
420 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
421 enum OpenMPLocationFlags {
422 /// \brief Use trampoline for internal microtask.
423 OMP_IDENT_IMD = 0x01,
424 /// \brief Use c-style ident structure.
425 OMP_IDENT_KMPC = 0x02,
426 /// \brief Atomic reduction option for kmpc_reduce.
427 OMP_ATOMIC_REDUCE = 0x10,
428 /// \brief Explicit 'barrier' directive.
429 OMP_IDENT_BARRIER_EXPL = 0x20,
430 /// \brief Implicit barrier in code.
431 OMP_IDENT_BARRIER_IMPL = 0x40,
432 /// \brief Implicit barrier in 'for' directive.
433 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
434 /// \brief Implicit barrier in 'sections' directive.
435 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
436 /// \brief Implicit barrier in 'single' directive.
437 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
440 /// \brief Describes ident structure that describes a source location.
441 /// All descriptions are taken from
442 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
443 /// Original structure:
444 /// typedef struct ident {
445 /// kmp_int32 reserved_1; /**< might be used in Fortran;
447 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
448 /// KMP_IDENT_KMPC identifies this union
450 /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
453 /// /* but currently used for storing
454 /// region-specific ITT */
455 /// /* contextual information. */
456 ///#endif /* USE_ITT_BUILD */
457 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
459 /// char const *psource; /**< String describing the source location.
460 /// The string is composed of semi-colon separated
461 // fields which describe the source file,
462 /// the function and a pair of line numbers that
463 /// delimit the construct.
466 enum IdentFieldIndex {
467 /// \brief might be used in Fortran
468 IdentField_Reserved_1,
469 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
471 /// \brief Not really used in Fortran any more
472 IdentField_Reserved_2,
473 /// \brief Source[4] in Fortran, do not use for C++
474 IdentField_Reserved_3,
475 /// \brief String describing the source location. The string is composed of
476 /// semi-colon separated fields which describe the source file, the function
477 /// and a pair of line numbers that delimit the construct.
481 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
482 /// the enum sched_type in kmp.h).
483 enum OpenMPSchedType {
484 /// \brief Lower bound for default (unordered) versions.
486 OMP_sch_static_chunked = 33,
488 OMP_sch_dynamic_chunked = 35,
489 OMP_sch_guided_chunked = 36,
490 OMP_sch_runtime = 37,
492 /// static with chunk adjustment (e.g., simd)
493 OMP_sch_static_balanced_chunked = 45,
494 /// \brief Lower bound for 'ordered' versions.
496 OMP_ord_static_chunked = 65,
498 OMP_ord_dynamic_chunked = 67,
499 OMP_ord_guided_chunked = 68,
500 OMP_ord_runtime = 69,
502 OMP_sch_default = OMP_sch_static,
503 /// \brief dist_schedule types
504 OMP_dist_sch_static_chunked = 91,
505 OMP_dist_sch_static = 92,
506 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
507 /// Set if the monotonic schedule modifier was present.
508 OMP_sch_modifier_monotonic = (1 << 29),
509 /// Set if the nonmonotonic schedule modifier was present.
510 OMP_sch_modifier_nonmonotonic = (1 << 30),
513 enum OpenMPRTLFunction {
514 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
515 /// kmpc_micro microtask, ...);
516 OMPRTL__kmpc_fork_call,
517 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
518 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
519 OMPRTL__kmpc_threadprivate_cached,
520 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
521 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
522 OMPRTL__kmpc_threadprivate_register,
523 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
524 OMPRTL__kmpc_global_thread_num,
525 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
526 // kmp_critical_name *crit);
527 OMPRTL__kmpc_critical,
528 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
529 // global_tid, kmp_critical_name *crit, uintptr_t hint);
530 OMPRTL__kmpc_critical_with_hint,
531 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
532 // kmp_critical_name *crit);
533 OMPRTL__kmpc_end_critical,
534 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
536 OMPRTL__kmpc_cancel_barrier,
537 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
538 OMPRTL__kmpc_barrier,
539 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_for_static_fini,
541 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
543 OMPRTL__kmpc_serialized_parallel,
544 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
546 OMPRTL__kmpc_end_serialized_parallel,
547 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
548 // kmp_int32 num_threads);
549 OMPRTL__kmpc_push_num_threads,
550 // Call to void __kmpc_flush(ident_t *loc);
552 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
554 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_end_master,
556 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
558 OMPRTL__kmpc_omp_taskyield,
559 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
561 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_end_single,
563 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
564 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
565 // kmp_routine_entry_t *task_entry);
566 OMPRTL__kmpc_omp_task_alloc,
567 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
569 OMPRTL__kmpc_omp_task,
570 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
571 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
573 OMPRTL__kmpc_copyprivate,
574 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
575 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
576 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
578 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
579 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
580 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
582 OMPRTL__kmpc_reduce_nowait,
583 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
584 // kmp_critical_name *lck);
585 OMPRTL__kmpc_end_reduce,
586 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
587 // kmp_critical_name *lck);
588 OMPRTL__kmpc_end_reduce_nowait,
589 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
590 // kmp_task_t * new_task);
591 OMPRTL__kmpc_omp_task_begin_if0,
592 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
593 // kmp_task_t * new_task);
594 OMPRTL__kmpc_omp_task_complete_if0,
595 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
596 OMPRTL__kmpc_ordered,
597 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_end_ordered,
599 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
601 OMPRTL__kmpc_omp_taskwait,
602 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
603 OMPRTL__kmpc_taskgroup,
604 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_end_taskgroup,
606 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
608 OMPRTL__kmpc_push_proc_bind,
609 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
610 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
611 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
612 OMPRTL__kmpc_omp_task_with_deps,
613 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
614 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
615 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
616 OMPRTL__kmpc_omp_wait_deps,
617 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
618 // global_tid, kmp_int32 cncl_kind);
619 OMPRTL__kmpc_cancellationpoint,
620 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
621 // kmp_int32 cncl_kind);
623 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
624 // kmp_int32 num_teams, kmp_int32 thread_limit);
625 OMPRTL__kmpc_push_num_teams,
626 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
628 OMPRTL__kmpc_fork_teams,
629 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
630 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
631 // sched, kmp_uint64 grainsize, void *task_dup);
632 OMPRTL__kmpc_taskloop,
633 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
634 // num_dims, struct kmp_dim *dims);
635 OMPRTL__kmpc_doacross_init,
636 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
637 OMPRTL__kmpc_doacross_fini,
638 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
640 OMPRTL__kmpc_doacross_post,
641 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
643 OMPRTL__kmpc_doacross_wait,
646 // Offloading related calls
648 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
649 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
652 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
653 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
654 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
655 OMPRTL__tgt_target_teams,
656 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
657 OMPRTL__tgt_register_lib,
658 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_unregister_lib,
660 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
661 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
662 OMPRTL__tgt_target_data_begin,
663 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
664 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
665 OMPRTL__tgt_target_data_end,
666 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
667 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
668 OMPRTL__tgt_target_data_update,
671 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
673 class CleanupTy final : public EHScopeStack::Cleanup {
674 PrePostActionTy *Action;
677 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
678 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
679 if (!CGF.HaveInsertPoint())
685 } // anonymous namespace
687 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
688 CodeGenFunction::RunCleanupsScope Scope(CGF);
690 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
691 Callback(CodeGen, CGF, *PrePostAction);
693 PrePostActionTy Action;
694 Callback(CodeGen, CGF, Action);
698 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
699 return CGF.EmitLoadOfPointerLValue(
700 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
701 getThreadIDVariable()->getType()->castAs<PointerType>());
704 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
705 if (!CGF.HaveInsertPoint())
707 // 1.2.2 OpenMP Language Terminology
708 // Structured block - An executable statement with a single entry at the
709 // top and a single exit at the bottom.
710 // The point of exit cannot be a branch out of the structured block.
711 // longjmp() and throw() must not violate the entry/exit criteria.
712 CGF.EHStack.pushTerminate();
714 CGF.EHStack.popTerminate();
717 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
718 CodeGenFunction &CGF) {
719 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
720 getThreadIDVariable()->getType(),
721 AlignmentSource::Decl);
724 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
725 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
726 IdentTy = llvm::StructType::create(
727 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
728 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
729 CGM.Int8PtrTy /* psource */, nullptr);
730 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
732 loadOffloadInfoMetadata();
735 void CGOpenMPRuntime::clear() {
736 InternalVars.clear();
739 static llvm::Function *
740 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
741 const Expr *CombinerInitializer, const VarDecl *In,
742 const VarDecl *Out, bool IsCombiner) {
743 // void .omp_combiner.(Ty *in, Ty *out);
744 auto &C = CGM.getContext();
745 QualType PtrTy = C.getPointerType(Ty).withRestrict();
746 FunctionArgList Args;
747 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
748 /*Id=*/nullptr, PtrTy);
749 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
750 /*Id=*/nullptr, PtrTy);
751 Args.push_back(&OmpOutParm);
752 Args.push_back(&OmpInParm);
754 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
755 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
756 auto *Fn = llvm::Function::Create(
757 FnTy, llvm::GlobalValue::InternalLinkage,
758 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
759 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
760 Fn->removeFnAttr(llvm::Attribute::NoInline);
761 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
762 CodeGenFunction CGF(CGM);
763 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
764 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
765 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
766 CodeGenFunction::OMPPrivateScope Scope(CGF);
767 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
768 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
769 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
772 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
773 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
774 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
777 (void)Scope.Privatize();
778 CGF.EmitIgnoredExpr(CombinerInitializer);
779 Scope.ForceCleanup();
780 CGF.FinishFunction();
784 void CGOpenMPRuntime::emitUserDefinedReduction(
785 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
786 if (UDRMap.count(D) > 0)
788 auto &C = CGM.getContext();
790 In = &C.Idents.get("omp_in");
791 Out = &C.Idents.get("omp_out");
793 llvm::Function *Combiner = emitCombinerOrInitializer(
794 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
795 cast<VarDecl>(D->lookup(Out).front()),
796 /*IsCombiner=*/true);
797 llvm::Function *Initializer = nullptr;
798 if (auto *Init = D->getInitializer()) {
799 if (!Priv || !Orig) {
800 Priv = &C.Idents.get("omp_priv");
801 Orig = &C.Idents.get("omp_orig");
803 Initializer = emitCombinerOrInitializer(
804 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
805 cast<VarDecl>(D->lookup(Priv).front()),
806 /*IsCombiner=*/false);
808 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
810 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
811 Decls.second.push_back(D);
815 std::pair<llvm::Function *, llvm::Function *>
816 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
817 auto I = UDRMap.find(D);
818 if (I != UDRMap.end())
820 emitUserDefinedReduction(/*CGF=*/nullptr, D);
821 return UDRMap.lookup(D);
824 // Layout information for ident_t.
825 static CharUnits getIdentAlign(CodeGenModule &CGM) {
826 return CGM.getPointerAlign();
828 static CharUnits getIdentSize(CodeGenModule &CGM) {
829 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
830 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
832 static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
833 // All the fields except the last are i32, so this works beautifully.
834 return unsigned(Field) * CharUnits::fromQuantity(4);
836 static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
837 IdentFieldIndex Field,
838 const llvm::Twine &Name = "") {
839 auto Offset = getOffsetOfIdentField(Field);
840 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
843 llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
844 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
845 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
846 assert(ThreadIDVar->getType()->isPointerType() &&
847 "thread id variable must be of type kmp_int32 *");
848 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
849 CodeGenFunction CGF(CGM, true);
850 bool HasCancel = false;
851 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
852 HasCancel = OPD->hasCancel();
853 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
854 HasCancel = OPSD->hasCancel();
855 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
856 HasCancel = OPFD->hasCancel();
857 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
859 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
860 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
863 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
864 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
865 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
866 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
867 bool Tied, unsigned &NumberOfParts) {
868 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
870 auto *ThreadID = getThreadID(CGF, D.getLocStart());
871 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
872 llvm::Value *TaskArgs[] = {
874 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
875 TaskTVar->getType()->castAs<PointerType>())
877 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
879 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
881 CodeGen.setAction(Action);
882 assert(!ThreadIDVar->getType()->isPointerType() &&
883 "thread id variable must be of type kmp_int32 for tasks");
884 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
885 auto *TD = dyn_cast<OMPTaskDirective>(&D);
886 CodeGenFunction CGF(CGM, true);
887 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
889 TD ? TD->hasCancel() : false, Action);
890 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
891 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
893 NumberOfParts = Action.getNumberOfParts();
897 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
898 CharUnits Align = getIdentAlign(CGM);
899 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
901 if (!DefaultOpenMPPSource) {
902 // Initialize default location for psource field of ident_t structure of
903 // all ident_t objects. Format is ";file;function;line;column;;".
905 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
906 DefaultOpenMPPSource =
907 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
908 DefaultOpenMPPSource =
909 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
912 ConstantInitBuilder builder(CGM);
913 auto fields = builder.beginStruct(IdentTy);
914 fields.addInt(CGM.Int32Ty, 0);
915 fields.addInt(CGM.Int32Ty, Flags);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.addInt(CGM.Int32Ty, 0);
918 fields.add(DefaultOpenMPPSource);
919 auto DefaultOpenMPLocation =
920 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
921 llvm::GlobalValue::PrivateLinkage);
922 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
924 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
926 return Address(Entry, Align);
929 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
932 Flags |= OMP_IDENT_KMPC;
933 // If no debug info is generated - return global default location.
934 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
936 return getOrCreateDefaultLocation(Flags).getPointer();
938 assert(CGF.CurFn && "No function in current CodeGenFunction.");
940 Address LocValue = Address::invalid();
941 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
942 if (I != OpenMPLocThreadIDMap.end())
943 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
945 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
946 // GetOpenMPThreadID was called before this routine.
947 if (!LocValue.isValid()) {
948 // Generate "ident_t .kmpc_loc.addr;"
949 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
951 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
952 Elem.second.DebugLoc = AI.getPointer();
955 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
956 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
957 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
958 CGM.getSize(getIdentSize(CGF.CGM)));
961 // char **psource = &.kmpc_loc_<flags>.addr.psource;
962 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
964 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
965 if (OMPDebugLoc == nullptr) {
966 SmallString<128> Buffer2;
967 llvm::raw_svector_ostream OS2(Buffer2);
968 // Build debug location
969 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
970 OS2 << ";" << PLoc.getFilename() << ";";
971 if (const FunctionDecl *FD =
972 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
973 OS2 << FD->getQualifiedNameAsString();
975 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
976 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
977 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
979 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
980 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
982 // Our callers always pass this to a runtime function, so for
983 // convenience, go ahead and return a naked pointer.
984 return LocValue.getPointer();
987 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
988 SourceLocation Loc) {
989 assert(CGF.CurFn && "No function in current CodeGenFunction.");
991 llvm::Value *ThreadID = nullptr;
992 // Check whether we've already cached a load of the thread id in this
994 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
995 if (I != OpenMPLocThreadIDMap.end()) {
996 ThreadID = I->second.ThreadID;
997 if (ThreadID != nullptr)
1000 if (auto *OMPRegionInfo =
1001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1002 if (OMPRegionInfo->getThreadIDVariable()) {
1003 // Check if this an outlined function with thread id passed as argument.
1004 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1005 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1006 // If value loaded in entry block, cache it and use it everywhere in
1008 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1009 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1010 Elem.second.ThreadID = ThreadID;
1016 // This is not an outlined function region - need to call __kmpc_int32
1017 // kmpc_global_thread_num(ident_t *loc).
1018 // Generate thread id value and cache this value for use across the
1020 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1021 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1023 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1024 emitUpdateLocation(CGF, Loc));
1025 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1026 Elem.second.ThreadID = ThreadID;
1030 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1031 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1032 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1033 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1034 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1035 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1038 FunctionUDRMap.erase(CGF.CurFn);
1042 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1045 return llvm::PointerType::getUnqual(IdentTy);
1048 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1049 if (!Kmpc_MicroTy) {
1050 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1051 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1052 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1053 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1055 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1059 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1060 llvm::Constant *RTLFn = nullptr;
1061 switch (static_cast<OpenMPRTLFunction>(Function)) {
1062 case OMPRTL__kmpc_fork_call: {
1063 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1065 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1066 getKmpc_MicroPointerTy()};
1067 llvm::FunctionType *FnTy =
1068 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1069 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1072 case OMPRTL__kmpc_global_thread_num: {
1073 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1074 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1075 llvm::FunctionType *FnTy =
1076 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1080 case OMPRTL__kmpc_threadprivate_cached: {
1081 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1082 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1084 CGM.VoidPtrTy, CGM.SizeTy,
1085 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1086 llvm::FunctionType *FnTy =
1087 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1091 case OMPRTL__kmpc_critical: {
1092 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1093 // kmp_critical_name *crit);
1094 llvm::Type *TypeParams[] = {
1095 getIdentTyPointerTy(), CGM.Int32Ty,
1096 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1097 llvm::FunctionType *FnTy =
1098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1102 case OMPRTL__kmpc_critical_with_hint: {
1103 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1104 // kmp_critical_name *crit, uintptr_t hint);
1105 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1106 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1108 llvm::FunctionType *FnTy =
1109 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1110 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1113 case OMPRTL__kmpc_threadprivate_register: {
1114 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1115 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1116 // typedef void *(*kmpc_ctor)(void *);
1118 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1119 /*isVarArg*/ false)->getPointerTo();
1120 // typedef void *(*kmpc_cctor)(void *, void *);
1121 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1122 auto KmpcCopyCtorTy =
1123 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1124 /*isVarArg*/ false)->getPointerTo();
1125 // typedef void (*kmpc_dtor)(void *);
1127 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1129 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1130 KmpcCopyCtorTy, KmpcDtorTy};
1131 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1132 /*isVarArg*/ false);
1133 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1136 case OMPRTL__kmpc_end_critical: {
1137 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1138 // kmp_critical_name *crit);
1139 llvm::Type *TypeParams[] = {
1140 getIdentTyPointerTy(), CGM.Int32Ty,
1141 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1142 llvm::FunctionType *FnTy =
1143 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1144 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1147 case OMPRTL__kmpc_cancel_barrier: {
1148 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1150 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1151 llvm::FunctionType *FnTy =
1152 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1153 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1156 case OMPRTL__kmpc_barrier: {
1157 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1158 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1159 llvm::FunctionType *FnTy =
1160 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1161 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1164 case OMPRTL__kmpc_for_static_fini: {
1165 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1166 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1167 llvm::FunctionType *FnTy =
1168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1172 case OMPRTL__kmpc_push_num_threads: {
1173 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1174 // kmp_int32 num_threads)
1175 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1177 llvm::FunctionType *FnTy =
1178 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1179 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1182 case OMPRTL__kmpc_serialized_parallel: {
1183 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1191 case OMPRTL__kmpc_end_serialized_parallel: {
1192 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1195 llvm::FunctionType *FnTy =
1196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1200 case OMPRTL__kmpc_flush: {
1201 // Build void __kmpc_flush(ident_t *loc);
1202 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1203 llvm::FunctionType *FnTy =
1204 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1208 case OMPRTL__kmpc_master: {
1209 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1210 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1211 llvm::FunctionType *FnTy =
1212 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1213 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1216 case OMPRTL__kmpc_end_master: {
1217 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1218 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1219 llvm::FunctionType *FnTy =
1220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1221 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1224 case OMPRTL__kmpc_omp_taskyield: {
1225 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1227 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1228 llvm::FunctionType *FnTy =
1229 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1230 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1233 case OMPRTL__kmpc_single: {
1234 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1235 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1236 llvm::FunctionType *FnTy =
1237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1238 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1241 case OMPRTL__kmpc_end_single: {
1242 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1243 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1244 llvm::FunctionType *FnTy =
1245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1246 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1249 case OMPRTL__kmpc_omp_task_alloc: {
1250 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1251 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1252 // kmp_routine_entry_t *task_entry);
1253 assert(KmpRoutineEntryPtrTy != nullptr &&
1254 "Type kmp_routine_entry_t must be created.");
1255 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1256 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1257 // Return void * and then cast to particular kmp_task_t type.
1258 llvm::FunctionType *FnTy =
1259 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1260 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1263 case OMPRTL__kmpc_omp_task: {
1264 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1266 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1268 llvm::FunctionType *FnTy =
1269 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1270 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1273 case OMPRTL__kmpc_copyprivate: {
1274 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1275 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1276 // kmp_int32 didit);
1277 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1279 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1280 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1281 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1283 llvm::FunctionType *FnTy =
1284 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1285 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1288 case OMPRTL__kmpc_reduce: {
1289 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1290 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1291 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1292 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1293 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1294 /*isVarArg=*/false);
1295 llvm::Type *TypeParams[] = {
1296 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1297 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1298 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1299 llvm::FunctionType *FnTy =
1300 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1301 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1304 case OMPRTL__kmpc_reduce_nowait: {
1305 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1306 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1307 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1309 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1310 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1311 /*isVarArg=*/false);
1312 llvm::Type *TypeParams[] = {
1313 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1314 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1315 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1316 llvm::FunctionType *FnTy =
1317 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1318 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1321 case OMPRTL__kmpc_end_reduce: {
1322 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1323 // kmp_critical_name *lck);
1324 llvm::Type *TypeParams[] = {
1325 getIdentTyPointerTy(), CGM.Int32Ty,
1326 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1327 llvm::FunctionType *FnTy =
1328 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1329 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1332 case OMPRTL__kmpc_end_reduce_nowait: {
1333 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1334 // kmp_critical_name *lck);
1335 llvm::Type *TypeParams[] = {
1336 getIdentTyPointerTy(), CGM.Int32Ty,
1337 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1338 llvm::FunctionType *FnTy =
1339 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1341 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1344 case OMPRTL__kmpc_omp_task_begin_if0: {
1345 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1347 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1349 llvm::FunctionType *FnTy =
1350 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1352 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1355 case OMPRTL__kmpc_omp_task_complete_if0: {
1356 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1358 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1360 llvm::FunctionType *FnTy =
1361 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1362 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1363 /*Name=*/"__kmpc_omp_task_complete_if0");
1366 case OMPRTL__kmpc_ordered: {
1367 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1368 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1369 llvm::FunctionType *FnTy =
1370 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1371 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1374 case OMPRTL__kmpc_end_ordered: {
1375 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1376 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1377 llvm::FunctionType *FnTy =
1378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1382 case OMPRTL__kmpc_omp_taskwait: {
1383 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1384 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1385 llvm::FunctionType *FnTy =
1386 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1387 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1390 case OMPRTL__kmpc_taskgroup: {
1391 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1392 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1393 llvm::FunctionType *FnTy =
1394 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1395 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1398 case OMPRTL__kmpc_end_taskgroup: {
1399 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1400 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1401 llvm::FunctionType *FnTy =
1402 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1406 case OMPRTL__kmpc_push_proc_bind: {
1407 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1409 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1410 llvm::FunctionType *FnTy =
1411 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1412 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1415 case OMPRTL__kmpc_omp_task_with_deps: {
1416 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1417 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1418 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1419 llvm::Type *TypeParams[] = {
1420 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1421 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1422 llvm::FunctionType *FnTy =
1423 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1425 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1428 case OMPRTL__kmpc_omp_wait_deps: {
1429 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1430 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1431 // kmp_depend_info_t *noalias_dep_list);
1432 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1433 CGM.Int32Ty, CGM.VoidPtrTy,
1434 CGM.Int32Ty, CGM.VoidPtrTy};
1435 llvm::FunctionType *FnTy =
1436 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1437 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1440 case OMPRTL__kmpc_cancellationpoint: {
1441 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1442 // global_tid, kmp_int32 cncl_kind)
1443 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1444 llvm::FunctionType *FnTy =
1445 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1446 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1449 case OMPRTL__kmpc_cancel: {
1450 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1451 // kmp_int32 cncl_kind)
1452 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1453 llvm::FunctionType *FnTy =
1454 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1455 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1458 case OMPRTL__kmpc_push_num_teams: {
1459 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1460 // kmp_int32 num_teams, kmp_int32 num_threads)
1461 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1468 case OMPRTL__kmpc_fork_teams: {
1469 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1472 getKmpc_MicroPointerTy()};
1473 llvm::FunctionType *FnTy =
1474 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1475 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1478 case OMPRTL__kmpc_taskloop: {
1479 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1480 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1481 // sched, kmp_uint64 grainsize, void *task_dup);
1482 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1486 CGM.Int64Ty->getPointerTo(),
1487 CGM.Int64Ty->getPointerTo(),
1493 llvm::FunctionType *FnTy =
1494 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1495 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1498 case OMPRTL__kmpc_doacross_init: {
1499 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1500 // num_dims, struct kmp_dim *dims);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1505 llvm::FunctionType *FnTy =
1506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1510 case OMPRTL__kmpc_doacross_fini: {
1511 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1512 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1513 llvm::FunctionType *FnTy =
1514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1515 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1518 case OMPRTL__kmpc_doacross_post: {
1519 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1521 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1522 CGM.Int64Ty->getPointerTo()};
1523 llvm::FunctionType *FnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1525 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1528 case OMPRTL__kmpc_doacross_wait: {
1529 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1532 CGM.Int64Ty->getPointerTo()};
1533 llvm::FunctionType *FnTy =
1534 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1535 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1538 case OMPRTL__tgt_target: {
1539 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1540 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1542 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1547 CGM.SizeTy->getPointerTo(),
1548 CGM.Int32Ty->getPointerTo()};
1549 llvm::FunctionType *FnTy =
1550 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1554 case OMPRTL__tgt_target_teams: {
1555 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1556 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1557 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1558 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1563 CGM.SizeTy->getPointerTo(),
1564 CGM.Int32Ty->getPointerTo(),
1567 llvm::FunctionType *FnTy =
1568 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1572 case OMPRTL__tgt_register_lib: {
1573 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1575 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1576 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1577 llvm::FunctionType *FnTy =
1578 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1582 case OMPRTL__tgt_unregister_lib: {
1583 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1585 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1586 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1587 llvm::FunctionType *FnTy =
1588 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1592 case OMPRTL__tgt_target_data_begin: {
1593 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1594 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1595 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1599 CGM.SizeTy->getPointerTo(),
1600 CGM.Int32Ty->getPointerTo()};
1601 llvm::FunctionType *FnTy =
1602 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1606 case OMPRTL__tgt_target_data_end: {
1607 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1608 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1609 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1613 CGM.SizeTy->getPointerTo(),
1614 CGM.Int32Ty->getPointerTo()};
1615 llvm::FunctionType *FnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1620 case OMPRTL__tgt_target_data_update: {
1621 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1622 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1623 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1627 CGM.SizeTy->getPointerTo(),
1628 CGM.Int32Ty->getPointerTo()};
1629 llvm::FunctionType *FnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1631 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1635 assert(RTLFn && "Unable to find OpenMP runtime function");
1639 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1641 assert((IVSize == 32 || IVSize == 64) &&
1642 "IV size is not compatible with the omp runtime");
1643 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1644 : "__kmpc_for_static_init_4u")
1645 : (IVSigned ? "__kmpc_for_static_init_8"
1646 : "__kmpc_for_static_init_8u");
1647 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1648 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1649 llvm::Type *TypeParams[] = {
1650 getIdentTyPointerTy(), // loc
1652 CGM.Int32Ty, // schedtype
1653 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1660 llvm::FunctionType *FnTy =
1661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1662 return CGM.CreateRuntimeFunction(FnTy, Name);
1665 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1667 assert((IVSize == 32 || IVSize == 64) &&
1668 "IV size is not compatible with the omp runtime");
1671 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1672 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1673 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1674 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1676 CGM.Int32Ty, // schedtype
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1684 return CGM.CreateRuntimeFunction(FnTy, Name);
1687 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1689 assert((IVSize == 32 || IVSize == 64) &&
1690 "IV size is not compatible with the omp runtime");
1693 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1694 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1695 llvm::Type *TypeParams[] = {
1696 getIdentTyPointerTy(), // loc
1699 llvm::FunctionType *FnTy =
1700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1701 return CGM.CreateRuntimeFunction(FnTy, Name);
1704 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1706 assert((IVSize == 32 || IVSize == 64) &&
1707 "IV size is not compatible with the omp runtime");
1710 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1711 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1712 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1713 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1717 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1722 llvm::FunctionType *FnTy =
1723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1724 return CGM.CreateRuntimeFunction(FnTy, Name);
1728 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1729 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1730 !CGM.getContext().getTargetInfo().isTLSSupported());
1731 // Lookup the entry, lazily creating it if necessary.
1732 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
1733 Twine(CGM.getMangledName(VD)) + ".cache.");
1736 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1739 SourceLocation Loc) {
1740 if (CGM.getLangOpts().OpenMPUseTLS &&
1741 CGM.getContext().getTargetInfo().isTLSSupported())
1744 auto VarTy = VDAddr.getElementType();
1745 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1746 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1748 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1749 getOrCreateThreadPrivateCache(VD)};
1750 return Address(CGF.EmitRuntimeCall(
1751 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1752 VDAddr.getAlignment());
1755 void CGOpenMPRuntime::emitThreadPrivateVarInit(
1756 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1757 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1758 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1760 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1761 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1763 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1764 // to register constructor/destructor for variable.
1765 llvm::Value *Args[] = {OMPLoc,
1766 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1768 Ctor, CopyCtor, Dtor};
1769 CGF.EmitRuntimeCall(
1770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
1773 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1774 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1775 bool PerformInit, CodeGenFunction *CGF) {
1776 if (CGM.getLangOpts().OpenMPUseTLS &&
1777 CGM.getContext().getTargetInfo().isTLSSupported())
1780 VD = VD->getDefinition(CGM.getContext());
1781 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1782 ThreadPrivateWithDefinition.insert(VD);
1783 QualType ASTTy = VD->getType();
1785 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1786 auto Init = VD->getAnyInitializer();
1787 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1788 // Generate function that re-emits the declaration's initializer into the
1789 // threadprivate copy of the variable VD
1790 CodeGenFunction CtorCGF(CGM);
1791 FunctionArgList Args;
1792 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1793 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1794 Args.push_back(&Dst);
1796 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1797 CGM.getContext().VoidPtrTy, Args);
1798 auto FTy = CGM.getTypes().GetFunctionType(FI);
1799 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1800 FTy, ".__kmpc_global_ctor_.", FI, Loc);
1801 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1802 Args, SourceLocation());
1803 auto ArgVal = CtorCGF.EmitLoadOfScalar(
1804 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1805 CGM.getContext().VoidPtrTy, Dst.getLocation());
1806 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1807 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1808 CtorCGF.ConvertTypeForMem(ASTTy));
1809 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1810 /*IsInitializer=*/true);
1811 ArgVal = CtorCGF.EmitLoadOfScalar(
1812 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1813 CGM.getContext().VoidPtrTy, Dst.getLocation());
1814 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1815 CtorCGF.FinishFunction();
1818 if (VD->getType().isDestructedType() != QualType::DK_none) {
1819 // Generate function that emits destructor call for the threadprivate copy
1820 // of the variable VD
1821 CodeGenFunction DtorCGF(CGM);
1822 FunctionArgList Args;
1823 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1824 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1825 Args.push_back(&Dst);
1827 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1828 CGM.getContext().VoidTy, Args);
1829 auto FTy = CGM.getTypes().GetFunctionType(FI);
1830 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1831 FTy, ".__kmpc_global_dtor_.", FI, Loc);
1832 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1833 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1835 // Create a scope with an artificial location for the body of this function.
1836 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1837 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1838 DtorCGF.GetAddrOfLocalVar(&Dst),
1839 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1840 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
1841 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1842 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1843 DtorCGF.FinishFunction();
1846 // Do not emit init function if it is not required.
1850 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1852 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1853 /*isVarArg=*/false)->getPointerTo();
1854 // Copying constructor for the threadprivate variable.
1855 // Must be NULL - reserved by runtime, but currently it requires that this
1856 // parameter is always NULL. Otherwise it fires assertion.
1857 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1858 if (Ctor == nullptr) {
1859 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1860 /*isVarArg=*/false)->getPointerTo();
1861 Ctor = llvm::Constant::getNullValue(CtorTy);
1863 if (Dtor == nullptr) {
1864 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1865 /*isVarArg=*/false)->getPointerTo();
1866 Dtor = llvm::Constant::getNullValue(DtorTy);
1869 auto InitFunctionTy =
1870 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1871 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1872 InitFunctionTy, ".__omp_threadprivate_init_.",
1873 CGM.getTypes().arrangeNullaryFunction());
1874 CodeGenFunction InitCGF(CGM);
1875 FunctionArgList ArgList;
1876 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1877 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1879 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1880 InitCGF.FinishFunction();
1881 return InitFunction;
1883 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1888 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1889 /// function. Here is the logic:
1895 static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1896 const RegionCodeGenTy &ThenGen,
1897 const RegionCodeGenTy &ElseGen) {
1898 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1900 // If the condition constant folds and can be elided, try to avoid emitting
1901 // the condition and the dead arm of the if/else.
1903 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1911 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1912 // emit the conditional branch.
1913 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1914 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1915 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1916 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1918 // Emit the 'then' code.
1919 CGF.EmitBlock(ThenBlock);
1921 CGF.EmitBranch(ContBlock);
1922 // Emit the 'else' code if present.
1923 // There is no need to emit line number for unconditional branch.
1924 (void)ApplyDebugLocation::CreateEmpty(CGF);
1925 CGF.EmitBlock(ElseBlock);
1927 // There is no need to emit line number for unconditional branch.
1928 (void)ApplyDebugLocation::CreateEmpty(CGF);
1929 CGF.EmitBranch(ContBlock);
1930 // Emit the continuation block for code after the if.
1931 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
1934 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1935 llvm::Value *OutlinedFn,
1936 ArrayRef<llvm::Value *> CapturedVars,
1937 const Expr *IfCond) {
1938 if (!CGF.HaveInsertPoint())
1940 auto *RTLoc = emitUpdateLocation(CGF, Loc);
1941 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1942 PrePostActionTy &) {
1943 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1944 auto &RT = CGF.CGM.getOpenMPRuntime();
1945 llvm::Value *Args[] = {
1947 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1948 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
1949 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1950 RealArgs.append(std::begin(Args), std::end(Args));
1951 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1953 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
1954 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1956 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1957 PrePostActionTy &) {
1958 auto &RT = CGF.CGM.getOpenMPRuntime();
1959 auto ThreadID = RT.getThreadID(CGF, Loc);
1961 // __kmpc_serialized_parallel(&Loc, GTid);
1962 llvm::Value *Args[] = {RTLoc, ThreadID};
1963 CGF.EmitRuntimeCall(
1964 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
1966 // OutlinedFn(>id, &zero, CapturedStruct);
1967 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
1969 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1970 /*Name*/ ".zero.addr");
1971 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1972 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1973 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1974 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1975 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1976 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
1978 // __kmpc_end_serialized_parallel(&Loc, GTid);
1979 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
1980 CGF.EmitRuntimeCall(
1981 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1985 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1987 RegionCodeGenTy ThenRCG(ThenGen);
1992 // If we're inside an (outlined) parallel region, use the region info's
1993 // thread-ID variable (it is passed in a first argument of the outlined function
1994 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1995 // regular serial code region, get thread ID by calling kmp_int32
1996 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1997 // return the address of that temp.
1998 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1999 SourceLocation Loc) {
2000 if (auto *OMPRegionInfo =
2001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2002 if (OMPRegionInfo->getThreadIDVariable())
2003 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2005 auto ThreadID = getThreadID(CGF, Loc);
2007 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2008 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2009 CGF.EmitStoreOfScalar(ThreadID,
2010 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2012 return ThreadIDTemp;
2016 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2017 const llvm::Twine &Name) {
2018 SmallString<256> Buffer;
2019 llvm::raw_svector_ostream Out(Buffer);
2021 auto RuntimeName = Out.str();
2022 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2024 assert(Elem.second->getType()->getPointerElementType() == Ty &&
2025 "OMP internal variable has different type than requested");
2026 return &*Elem.second;
2029 return Elem.second = new llvm::GlobalVariable(
2030 CGM.getModule(), Ty, /*IsConstant*/ false,
2031 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2035 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2036 llvm::Twine Name(".gomp_critical_user_", CriticalName);
2037 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
2041 /// Common pre(post)-action for different OpenMP constructs.
2042 class CommonActionTy final : public PrePostActionTy {
2043 llvm::Value *EnterCallee;
2044 ArrayRef<llvm::Value *> EnterArgs;
2045 llvm::Value *ExitCallee;
2046 ArrayRef<llvm::Value *> ExitArgs;
2048 llvm::BasicBlock *ContBlock = nullptr;
2051 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2052 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2053 bool Conditional = false)
2054 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2055 ExitArgs(ExitArgs), Conditional(Conditional) {}
2056 void Enter(CodeGenFunction &CGF) override {
2057 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2059 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2060 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2061 ContBlock = CGF.createBasicBlock("omp_if.end");
2062 // Generate the branch (If-stmt)
2063 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2064 CGF.EmitBlock(ThenBlock);
2067 void Done(CodeGenFunction &CGF) {
2068 // Emit the rest of blocks/branches
2069 CGF.EmitBranch(ContBlock);
2070 CGF.EmitBlock(ContBlock, true);
2072 void Exit(CodeGenFunction &CGF) override {
2073 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2076 } // anonymous namespace
2078 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2079 StringRef CriticalName,
2080 const RegionCodeGenTy &CriticalOpGen,
2081 SourceLocation Loc, const Expr *Hint) {
2082 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2084 // __kmpc_end_critical(ident_t *, gtid, Lock);
2085 // Prepare arguments and build a call to __kmpc_critical
2086 if (!CGF.HaveInsertPoint())
2088 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2089 getCriticalRegionLock(CriticalName)};
2090 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2093 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2094 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2096 CommonActionTy Action(
2097 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2098 : OMPRTL__kmpc_critical),
2099 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2100 CriticalOpGen.setAction(Action);
2101 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2104 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2105 const RegionCodeGenTy &MasterOpGen,
2106 SourceLocation Loc) {
2107 if (!CGF.HaveInsertPoint())
2109 // if(__kmpc_master(ident_t *, gtid)) {
2111 // __kmpc_end_master(ident_t *, gtid);
2113 // Prepare arguments and build a call to __kmpc_master
2114 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2115 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2116 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2117 /*Conditional=*/true);
2118 MasterOpGen.setAction(Action);
2119 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2123 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2124 SourceLocation Loc) {
2125 if (!CGF.HaveInsertPoint())
2127 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2128 llvm::Value *Args[] = {
2129 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2130 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2131 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
2132 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2133 Region->emitUntiedSwitch(CGF);
2136 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2137 const RegionCodeGenTy &TaskgroupOpGen,
2138 SourceLocation Loc) {
2139 if (!CGF.HaveInsertPoint())
2141 // __kmpc_taskgroup(ident_t *, gtid);
2142 // TaskgroupOpGen();
2143 // __kmpc_end_taskgroup(ident_t *, gtid);
2144 // Prepare arguments and build a call to __kmpc_taskgroup
2145 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2146 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2147 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2149 TaskgroupOpGen.setAction(Action);
2150 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2153 /// Given an array of pointers to variables, project the address of a
2155 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2156 unsigned Index, const VarDecl *Var) {
2157 // Pull out the pointer to the variable.
2159 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
2160 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2162 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2163 Addr = CGF.Builder.CreateElementBitCast(
2164 Addr, CGF.ConvertTypeForMem(Var->getType()));
2168 static llvm::Value *emitCopyprivateCopyFunction(
2169 CodeGenModule &CGM, llvm::Type *ArgsType,
2170 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2171 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
2172 auto &C = CGM.getContext();
2173 // void copy_func(void *LHSArg, void *RHSArg);
2174 FunctionArgList Args;
2175 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2177 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2179 Args.push_back(&LHSArg);
2180 Args.push_back(&RHSArg);
2181 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2182 auto *Fn = llvm::Function::Create(
2183 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2184 ".omp.copyprivate.copy_func", &CGM.getModule());
2185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
2186 CodeGenFunction CGF(CGM);
2187 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2188 // Dest = (void*[n])(LHSArg);
2189 // Src = (void*[n])(RHSArg);
2190 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2191 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2192 ArgsType), CGF.getPointerAlign());
2193 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2194 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2195 ArgsType), CGF.getPointerAlign());
2196 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2197 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2199 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2200 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2201 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2202 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2204 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2205 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2207 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2208 QualType Type = VD->getType();
2209 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2211 CGF.FinishFunction();
2215 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2216 const RegionCodeGenTy &SingleOpGen,
2218 ArrayRef<const Expr *> CopyprivateVars,
2219 ArrayRef<const Expr *> SrcExprs,
2220 ArrayRef<const Expr *> DstExprs,
2221 ArrayRef<const Expr *> AssignmentOps) {
2222 if (!CGF.HaveInsertPoint())
2224 assert(CopyprivateVars.size() == SrcExprs.size() &&
2225 CopyprivateVars.size() == DstExprs.size() &&
2226 CopyprivateVars.size() == AssignmentOps.size());
2227 auto &C = CGM.getContext();
2228 // int32 did_it = 0;
2229 // if(__kmpc_single(ident_t *, gtid)) {
2231 // __kmpc_end_single(ident_t *, gtid);
2234 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2235 // <copy_func>, did_it);
2237 Address DidIt = Address::invalid();
2238 if (!CopyprivateVars.empty()) {
2239 // int32 did_it = 0;
2240 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2241 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2242 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2244 // Prepare arguments and build a call to __kmpc_single
2245 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2246 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2247 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2248 /*Conditional=*/true);
2249 SingleOpGen.setAction(Action);
2250 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2251 if (DidIt.isValid()) {
2253 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2256 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2257 // <copy_func>, did_it);
2258 if (DidIt.isValid()) {
2259 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2260 auto CopyprivateArrayTy =
2261 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2262 /*IndexTypeQuals=*/0);
2263 // Create a list of all private variables for copyprivate.
2264 Address CopyprivateList =
2265 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2266 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2267 Address Elem = CGF.Builder.CreateConstArrayGEP(
2268 CopyprivateList, I, CGF.getPointerSize());
2269 CGF.Builder.CreateStore(
2270 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2271 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2274 // Build function that copies private values from single region to all other
2275 // threads in the corresponding parallel region.
2276 auto *CpyFn = emitCopyprivateCopyFunction(
2277 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2278 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
2279 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2281 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2283 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
2284 llvm::Value *Args[] = {
2285 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2286 getThreadID(CGF, Loc), // i32 <gtid>
2287 BufSize, // size_t <buf_size>
2288 CL.getPointer(), // void *<copyprivate list>
2289 CpyFn, // void (*) (void *, void *) <copy_func>
2290 DidItVal // i32 did_it
2292 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2296 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2297 const RegionCodeGenTy &OrderedOpGen,
2298 SourceLocation Loc, bool IsThreads) {
2299 if (!CGF.HaveInsertPoint())
2301 // __kmpc_ordered(ident_t *, gtid);
2303 // __kmpc_end_ordered(ident_t *, gtid);
2304 // Prepare arguments and build a call to __kmpc_ordered
2306 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2307 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2308 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2310 OrderedOpGen.setAction(Action);
2311 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2314 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2317 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2318 OpenMPDirectiveKind Kind, bool EmitChecks,
2319 bool ForceSimpleCall) {
2320 if (!CGF.HaveInsertPoint())
2322 // Build call __kmpc_cancel_barrier(loc, thread_id);
2323 // Build call __kmpc_barrier(loc, thread_id);
2325 if (Kind == OMPD_for)
2326 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2327 else if (Kind == OMPD_sections)
2328 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2329 else if (Kind == OMPD_single)
2330 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2331 else if (Kind == OMPD_barrier)
2332 Flags = OMP_IDENT_BARRIER_EXPL;
2334 Flags = OMP_IDENT_BARRIER_IMPL;
2335 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2337 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2338 getThreadID(CGF, Loc)};
2339 if (auto *OMPRegionInfo =
2340 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2341 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2342 auto *Result = CGF.EmitRuntimeCall(
2343 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
2345 // if (__kmpc_cancel_barrier()) {
2346 // exit from construct;
2348 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2349 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2350 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2351 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2352 CGF.EmitBlock(ExitBB);
2353 // exit from construct;
2354 auto CancelDestination =
2355 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2356 CGF.EmitBranchThroughCleanup(CancelDestination);
2357 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2365 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
2366 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2367 bool Chunked, bool Ordered) {
2368 switch (ScheduleKind) {
2369 case OMPC_SCHEDULE_static:
2370 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2371 : (Ordered ? OMP_ord_static : OMP_sch_static);
2372 case OMPC_SCHEDULE_dynamic:
2373 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2374 case OMPC_SCHEDULE_guided:
2375 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2376 case OMPC_SCHEDULE_runtime:
2377 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2378 case OMPC_SCHEDULE_auto:
2379 return Ordered ? OMP_ord_auto : OMP_sch_auto;
2380 case OMPC_SCHEDULE_unknown:
2381 assert(!Chunked && "chunk was specified but schedule kind not known");
2382 return Ordered ? OMP_ord_static : OMP_sch_static;
2384 llvm_unreachable("Unexpected runtime schedule");
2387 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2388 static OpenMPSchedType
2389 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2390 // only static is allowed for dist_schedule
2391 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2394 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2395 bool Chunked) const {
2396 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2397 return Schedule == OMP_sch_static;
2400 bool CGOpenMPRuntime::isStaticNonchunked(
2401 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2402 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2403 return Schedule == OMP_dist_sch_static;
2407 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2409 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2410 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2411 return Schedule != OMP_sch_static;
2414 static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2415 OpenMPScheduleClauseModifier M1,
2416 OpenMPScheduleClauseModifier M2) {
2419 case OMPC_SCHEDULE_MODIFIER_monotonic:
2420 Modifier = OMP_sch_modifier_monotonic;
2422 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2423 Modifier = OMP_sch_modifier_nonmonotonic;
2425 case OMPC_SCHEDULE_MODIFIER_simd:
2426 if (Schedule == OMP_sch_static_chunked)
2427 Schedule = OMP_sch_static_balanced_chunked;
2429 case OMPC_SCHEDULE_MODIFIER_last:
2430 case OMPC_SCHEDULE_MODIFIER_unknown:
2434 case OMPC_SCHEDULE_MODIFIER_monotonic:
2435 Modifier = OMP_sch_modifier_monotonic;
2437 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2438 Modifier = OMP_sch_modifier_nonmonotonic;
2440 case OMPC_SCHEDULE_MODIFIER_simd:
2441 if (Schedule == OMP_sch_static_chunked)
2442 Schedule = OMP_sch_static_balanced_chunked;
2444 case OMPC_SCHEDULE_MODIFIER_last:
2445 case OMPC_SCHEDULE_MODIFIER_unknown:
2448 return Schedule | Modifier;
2451 void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2453 const OpenMPScheduleTy &ScheduleKind,
2454 unsigned IVSize, bool IVSigned,
2455 bool Ordered, llvm::Value *UB,
2456 llvm::Value *Chunk) {
2457 if (!CGF.HaveInsertPoint())
2459 OpenMPSchedType Schedule =
2460 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
2462 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2463 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2464 Schedule != OMP_sch_static_balanced_chunked));
2465 // Call __kmpc_dispatch_init(
2466 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2467 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2468 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
2470 // If the Chunk was not specified in the clause - use default value 1.
2471 if (Chunk == nullptr)
2472 Chunk = CGF.Builder.getIntN(IVSize, 1);
2473 llvm::Value *Args[] = {
2474 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2475 CGF.Builder.getInt32(addMonoNonMonoModifier(
2476 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2477 CGF.Builder.getIntN(IVSize, 0), // Lower
2479 CGF.Builder.getIntN(IVSize, 1), // Stride
2482 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2485 static void emitForStaticInitCall(
2486 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2487 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2488 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2489 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2490 Address ST, llvm::Value *Chunk) {
2491 if (!CGF.HaveInsertPoint())
2495 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2496 Schedule == OMP_sch_static_balanced_chunked ||
2497 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2498 Schedule == OMP_dist_sch_static ||
2499 Schedule == OMP_dist_sch_static_chunked);
2501 // Call __kmpc_for_static_init(
2502 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2503 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2504 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2505 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2506 if (Chunk == nullptr) {
2507 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2508 Schedule == OMP_dist_sch_static) &&
2509 "expected static non-chunked schedule");
2510 // If the Chunk was not specified in the clause - use default value 1.
2511 Chunk = CGF.Builder.getIntN(IVSize, 1);
2513 assert((Schedule == OMP_sch_static_chunked ||
2514 Schedule == OMP_sch_static_balanced_chunked ||
2515 Schedule == OMP_ord_static_chunked ||
2516 Schedule == OMP_dist_sch_static_chunked) &&
2517 "expected static chunked schedule");
2519 llvm::Value *Args[] = {
2520 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2521 Schedule, M1, M2)), // Schedule type
2522 IL.getPointer(), // &isLastIter
2523 LB.getPointer(), // &LB
2524 UB.getPointer(), // &UB
2525 ST.getPointer(), // &Stride
2526 CGF.Builder.getIntN(IVSize, 1), // Incr
2529 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2532 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2534 const OpenMPScheduleTy &ScheduleKind,
2535 unsigned IVSize, bool IVSigned,
2536 bool Ordered, Address IL, Address LB,
2537 Address UB, Address ST,
2538 llvm::Value *Chunk) {
2539 OpenMPSchedType ScheduleNum =
2540 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
2541 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2542 auto *ThreadId = getThreadID(CGF, Loc);
2543 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2544 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2545 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2546 Ordered, IL, LB, UB, ST, Chunk);
2549 void CGOpenMPRuntime::emitDistributeStaticInit(
2550 CodeGenFunction &CGF, SourceLocation Loc,
2551 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2552 bool Ordered, Address IL, Address LB, Address UB, Address ST,
2553 llvm::Value *Chunk) {
2554 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2555 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2556 auto *ThreadId = getThreadID(CGF, Loc);
2557 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2558 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2559 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2560 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2564 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2565 SourceLocation Loc) {
2566 if (!CGF.HaveInsertPoint())
2568 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2569 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2570 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2574 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2578 if (!CGF.HaveInsertPoint())
2580 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2581 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2582 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2585 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2586 SourceLocation Loc, unsigned IVSize,
2587 bool IVSigned, Address IL,
2588 Address LB, Address UB,
2590 // Call __kmpc_dispatch_next(
2591 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2592 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2593 // kmp_int[32|64] *p_stride);
2594 llvm::Value *Args[] = {
2595 emitUpdateLocation(CGF, Loc),
2596 getThreadID(CGF, Loc),
2597 IL.getPointer(), // &isLastIter
2598 LB.getPointer(), // &Lower
2599 UB.getPointer(), // &Upper
2600 ST.getPointer() // &Stride
2603 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2604 return CGF.EmitScalarConversion(
2605 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
2606 CGF.getContext().BoolTy, Loc);
2609 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2610 llvm::Value *NumThreads,
2611 SourceLocation Loc) {
2612 if (!CGF.HaveInsertPoint())
2614 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2615 llvm::Value *Args[] = {
2616 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2617 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2618 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2622 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2623 OpenMPProcBindClauseKind ProcBind,
2624 SourceLocation Loc) {
2625 if (!CGF.HaveInsertPoint())
2627 // Constants for proc bind value accepted by the runtime.
2638 case OMPC_PROC_BIND_master:
2639 RuntimeProcBind = ProcBindMaster;
2641 case OMPC_PROC_BIND_close:
2642 RuntimeProcBind = ProcBindClose;
2644 case OMPC_PROC_BIND_spread:
2645 RuntimeProcBind = ProcBindSpread;
2647 case OMPC_PROC_BIND_unknown:
2648 llvm_unreachable("Unsupported proc_bind value.");
2650 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2651 llvm::Value *Args[] = {
2652 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2653 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2654 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2657 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2658 SourceLocation Loc) {
2659 if (!CGF.HaveInsertPoint())
2661 // Build call void __kmpc_flush(ident_t *loc)
2662 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2663 emitUpdateLocation(CGF, Loc));
2667 /// \brief Indexes of fields for type kmp_task_t.
2668 enum KmpTaskTFields {
2669 /// \brief List of shared variables.
2671 /// \brief Task routine.
2673 /// \brief Partition id for the untied tasks.
2675 /// Function with call of destructors for private variables.
2679 /// (Taskloops only) Lower bound.
2681 /// (Taskloops only) Upper bound.
2683 /// (Taskloops only) Stride.
2685 /// (Taskloops only) Is last iteration flag.
2688 } // anonymous namespace
2690 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2691 // FIXME: Add other entries type when they become supported.
2692 return OffloadEntriesTargetRegion.empty();
2695 /// \brief Initialize target region entry.
2696 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2697 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2698 StringRef ParentName, unsigned LineNum,
2700 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2701 "only required for the device "
2702 "code generation.");
2703 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
2704 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2706 ++OffloadingEntriesNum;
2709 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2710 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2711 StringRef ParentName, unsigned LineNum,
2712 llvm::Constant *Addr, llvm::Constant *ID,
2714 // If we are emitting code for a target, the entry is already initialized,
2715 // only has to be registered.
2716 if (CGM.getLangOpts().OpenMPIsDevice) {
2717 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
2718 "Entry must exist.");
2720 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
2721 assert(Entry.isValid() && "Entry not initialized!");
2722 Entry.setAddress(Addr);
2724 Entry.setFlags(Flags);
2727 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
2728 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
2732 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
2733 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2734 unsigned LineNum) const {
2735 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2736 if (PerDevice == OffloadEntriesTargetRegion.end())
2738 auto PerFile = PerDevice->second.find(FileID);
2739 if (PerFile == PerDevice->second.end())
2741 auto PerParentName = PerFile->second.find(ParentName);
2742 if (PerParentName == PerFile->second.end())
2744 auto PerLine = PerParentName->second.find(LineNum);
2745 if (PerLine == PerParentName->second.end())
2747 // Fail if this entry is already registered.
2748 if (PerLine->second.getAddress() || PerLine->second.getID())
2753 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2754 const OffloadTargetRegionEntryInfoActTy &Action) {
2755 // Scan all target region entries and perform the provided action.
2756 for (auto &D : OffloadEntriesTargetRegion)
2757 for (auto &F : D.second)
2758 for (auto &P : F.second)
2759 for (auto &L : P.second)
2760 Action(D.first, F.first, P.first(), L.first, L.second);
2763 /// \brief Create a Ctor/Dtor-like function whose body is emitted through
2764 /// \a Codegen. This is used to emit the two functions that register and
2765 /// unregister the descriptor of the current compilation unit.
2766 static llvm::Function *
2767 createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2768 const RegionCodeGenTy &Codegen) {
2769 auto &C = CGM.getContext();
2770 FunctionArgList Args;
2771 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2772 /*Id=*/nullptr, C.VoidPtrTy);
2773 Args.push_back(&DummyPtr);
2775 CodeGenFunction CGF(CGM);
2776 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2777 auto FTy = CGM.getTypes().GetFunctionType(FI);
2779 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2780 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2782 CGF.FinishFunction();
2787 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2789 // If we don't have entries or if we are emitting code for the device, we
2790 // don't need to do anything.
2791 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2794 auto &M = CGM.getModule();
2795 auto &C = CGM.getContext();
2797 // Get list of devices we care about
2798 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2800 // We should be creating an offloading descriptor only if there are devices
2802 assert(!Devices.empty() && "No OpenMP offloading devices??");
2804 // Create the external variables that will point to the begin and end of the
2805 // host entries section. These will be defined by the linker.
2806 auto *OffloadEntryTy =
2807 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2808 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2809 M, OffloadEntryTy, /*isConstant=*/true,
2810 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2811 ".omp_offloading.entries_begin");
2812 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2813 M, OffloadEntryTy, /*isConstant=*/true,
2814 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2815 ".omp_offloading.entries_end");
2817 // Create all device images
2818 auto *DeviceImageTy = cast<llvm::StructType>(
2819 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2820 ConstantInitBuilder DeviceImagesBuilder(CGM);
2821 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
2823 for (unsigned i = 0; i < Devices.size(); ++i) {
2824 StringRef T = Devices[i].getTriple();
2825 auto *ImgBegin = new llvm::GlobalVariable(
2826 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2827 /*Initializer=*/nullptr,
2828 Twine(".omp_offloading.img_start.") + Twine(T));
2829 auto *ImgEnd = new llvm::GlobalVariable(
2830 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2831 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
2833 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2836 Dev.add(HostEntriesBegin);
2837 Dev.add(HostEntriesEnd);
2838 Dev.finishAndAddTo(DeviceImagesEntries);
2841 // Create device images global array.
2842 llvm::GlobalVariable *DeviceImages =
2843 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2844 CGM.getPointerAlign(),
2845 /*isConstant=*/true);
2846 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2848 // This is a Zero array to be used in the creation of the constant expressions
2849 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2850 llvm::Constant::getNullValue(CGM.Int32Ty)};
2852 // Create the target region descriptor.
2853 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2854 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2855 ConstantInitBuilder DescBuilder(CGM);
2856 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2857 DescInit.addInt(CGM.Int32Ty, Devices.size());
2858 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2861 DescInit.add(HostEntriesBegin);
2862 DescInit.add(HostEntriesEnd);
2864 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2865 CGM.getPointerAlign(),
2866 /*isConstant=*/true);
2868 // Emit code to register or unregister the descriptor at execution
2869 // startup or closing, respectively.
2871 // Create a variable to drive the registration and unregistration of the
2872 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2873 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2874 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2875 IdentInfo, C.CharTy);
2877 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2878 CGM, ".omp_offloading.descriptor_unreg",
2879 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2880 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2883 auto *RegFn = createOffloadingBinaryDescriptorFunction(
2884 CGM, ".omp_offloading.descriptor_reg",
2885 [&](CodeGenFunction &CGF, PrePostActionTy &) {
2886 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2888 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2893 void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2894 llvm::Constant *Addr, uint64_t Size,
2896 StringRef Name = Addr->getName();
2897 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2898 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2899 llvm::LLVMContext &C = CGM.getModule().getContext();
2900 llvm::Module &M = CGM.getModule();
2902 // Make sure the address has the right type.
2903 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
2905 // Create constant string with the name.
2906 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2908 llvm::GlobalVariable *Str =
2909 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2910 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2911 ".omp_offloading.entry_name");
2912 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2913 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2915 // We can't have any padding between symbols, so we need to have 1-byte
2917 auto Align = CharUnits::fromQuantity(1);
2919 // Create the entry struct.
2920 ConstantInitBuilder EntryBuilder(CGM);
2921 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2922 EntryInit.add(AddrPtr);
2923 EntryInit.add(StrPtr);
2924 EntryInit.addInt(CGM.SizeTy, Size);
2925 EntryInit.addInt(CGM.Int32Ty, Flags);
2926 EntryInit.addInt(CGM.Int32Ty, 0);
2927 llvm::GlobalVariable *Entry =
2928 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2931 llvm::GlobalValue::ExternalLinkage);
2933 // The entry has to be created in the section the linker expects it to be.
2934 Entry->setSection(".omp_offloading.entries");
2937 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2938 // Emit the offloading entries and metadata so that the device codegen side
2939 // can easily figure out what to emit. The produced metadata looks like
2942 // !omp_offload.info = !{!1, ...}
2944 // Right now we only generate metadata for function that contain target
2947 // If we do not have entries, we dont need to do anything.
2948 if (OffloadEntriesInfoManager.empty())
2951 llvm::Module &M = CGM.getModule();
2952 llvm::LLVMContext &C = M.getContext();
2953 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2954 OrderedEntries(OffloadEntriesInfoManager.size());
2956 // Create the offloading info metadata node.
2957 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2959 // Auxiliar methods to create metadata values and strings.
2960 auto getMDInt = [&](unsigned v) {
2961 return llvm::ConstantAsMetadata::get(
2962 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2965 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2967 // Create function that emits metadata for each target region entry;
2968 auto &&TargetRegionMetadataEmitter = [&](
2969 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
2970 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2971 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2972 // Generate metadata for target regions. Each entry of this metadata
2974 // - Entry 0 -> Kind of this type of metadata (0).
2975 // - Entry 1 -> Device ID of the file where the entry was identified.
2976 // - Entry 2 -> File ID of the file where the entry was identified.
2977 // - Entry 3 -> Mangled name of the function where the entry was identified.
2978 // - Entry 4 -> Line in the file where the entry was identified.
2979 // - Entry 5 -> Order the entry was created.
2980 // The first element of the metadata node is the kind.
2981 Ops.push_back(getMDInt(E.getKind()));
2982 Ops.push_back(getMDInt(DeviceID));
2983 Ops.push_back(getMDInt(FileID));
2984 Ops.push_back(getMDString(ParentName));
2985 Ops.push_back(getMDInt(Line));
2986 Ops.push_back(getMDInt(E.getOrder()));
2988 // Save this entry in the right position of the ordered entries array.
2989 OrderedEntries[E.getOrder()] = &E;
2991 // Add metadata to the named metadata node.
2992 MD->addOperand(llvm::MDNode::get(C, Ops));
2995 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2996 TargetRegionMetadataEmitter);
2998 for (auto *E : OrderedEntries) {
2999 assert(E && "All ordered entries must exist!");
3001 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3003 assert(CE->getID() && CE->getAddress() &&
3004 "Entry ID and Addr are invalid!");
3005 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
3007 llvm_unreachable("Unsupported entry kind.");
3011 /// \brief Loads all the offload entries information from the host IR
3013 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3014 // If we are in target mode, load the metadata from the host IR. This code has
3015 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3017 if (!CGM.getLangOpts().OpenMPIsDevice)
3020 if (CGM.getLangOpts().OMPHostIRFile.empty())
3023 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3027 llvm::LLVMContext C;
3028 auto ME = expectedToErrorOrAndEmitErrors(
3029 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3034 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3038 for (auto I : MD->operands()) {
3039 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3041 auto getMDInt = [&](unsigned Idx) {
3042 llvm::ConstantAsMetadata *V =
3043 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3044 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3047 auto getMDString = [&](unsigned Idx) {
3048 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3049 return V->getString();
3052 switch (getMDInt(0)) {
3054 llvm_unreachable("Unexpected metadata!");
3056 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3057 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3058 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3059 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3060 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
3061 /*Order=*/getMDInt(5));
3067 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3068 if (!KmpRoutineEntryPtrTy) {
3069 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3070 auto &C = CGM.getContext();
3071 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3072 FunctionProtoType::ExtProtoInfo EPI;
3073 KmpRoutineEntryPtrQTy = C.getPointerType(
3074 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3075 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3079 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3081 auto *Field = FieldDecl::Create(
3082 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3083 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3084 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3085 Field->setAccess(AS_public);
3090 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3092 // Make sure the type of the entry is already created. This is the type we
3094 // struct __tgt_offload_entry{
3095 // void *addr; // Pointer to the offload entry info.
3096 // // (function or global)
3097 // char *name; // Name of the function or global.
3098 // size_t size; // Size of the entry info (0 if it a function).
3099 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3100 // int32_t reserved; // Reserved, to use by the runtime library.
3102 if (TgtOffloadEntryQTy.isNull()) {
3103 ASTContext &C = CGM.getContext();
3104 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3105 RD->startDefinition();
3106 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3107 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3108 addFieldToRecordDecl(C, RD, C.getSizeType());
3109 addFieldToRecordDecl(
3110 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3111 addFieldToRecordDecl(
3112 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3113 RD->completeDefinition();
3114 TgtOffloadEntryQTy = C.getRecordType(RD);
3116 return TgtOffloadEntryQTy;
3119 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3120 // These are the types we need to build:
3121 // struct __tgt_device_image{
3122 // void *ImageStart; // Pointer to the target code start.
3123 // void *ImageEnd; // Pointer to the target code end.
3124 // // We also add the host entries to the device image, as it may be useful
3125 // // for the target runtime to have access to that information.
3126 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3128 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3129 // // entries (non inclusive).
3131 if (TgtDeviceImageQTy.isNull()) {
3132 ASTContext &C = CGM.getContext();
3133 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3134 RD->startDefinition();
3135 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3136 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3137 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3138 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3139 RD->completeDefinition();
3140 TgtDeviceImageQTy = C.getRecordType(RD);
3142 return TgtDeviceImageQTy;
3145 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3146 // struct __tgt_bin_desc{
3147 // int32_t NumDevices; // Number of devices supported.
3148 // __tgt_device_image *DeviceImages; // Arrays of device images
3149 // // (one per device).
3150 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3152 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3153 // // entries (non inclusive).
3155 if (TgtBinaryDescriptorQTy.isNull()) {
3156 ASTContext &C = CGM.getContext();
3157 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3158 RD->startDefinition();
3159 addFieldToRecordDecl(
3160 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3161 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3162 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3163 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3164 RD->completeDefinition();
3165 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3167 return TgtBinaryDescriptorQTy;
3171 struct PrivateHelpersTy {
3172 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3173 const VarDecl *PrivateElemInit)
3174 : Original(Original), PrivateCopy(PrivateCopy),
3175 PrivateElemInit(PrivateElemInit) {}
3176 const VarDecl *Original;
3177 const VarDecl *PrivateCopy;
3178 const VarDecl *PrivateElemInit;
3180 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3181 } // anonymous namespace
3184 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3185 if (!Privates.empty()) {
3186 auto &C = CGM.getContext();
3187 // Build struct .kmp_privates_t. {
3188 // /* private vars */
3190 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3191 RD->startDefinition();
3192 for (auto &&Pair : Privates) {
3193 auto *VD = Pair.second.Original;
3194 auto Type = VD->getType();
3195 Type = Type.getNonReferenceType();
3196 auto *FD = addFieldToRecordDecl(C, RD, Type);
3197 if (VD->hasAttrs()) {
3198 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3199 E(VD->getAttrs().end());
3204 RD->completeDefinition();
3211 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3212 QualType KmpInt32Ty,
3213 QualType KmpRoutineEntryPointerQTy) {
3214 auto &C = CGM.getContext();
3215 // Build struct kmp_task_t {
3217 // kmp_routine_entry_t routine;
3218 // kmp_int32 part_id;
3219 // kmp_cmplrdata_t data1;
3220 // kmp_cmplrdata_t data2;
3221 // For taskloops additional fields:
3227 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3228 UD->startDefinition();
3229 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3230 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3231 UD->completeDefinition();
3232 QualType KmpCmplrdataTy = C.getRecordType(UD);
3233 auto *RD = C.buildImplicitRecord("kmp_task_t");
3234 RD->startDefinition();
3235 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3236 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3237 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3238 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3239 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3240 if (isOpenMPTaskLoopDirective(Kind)) {
3241 QualType KmpUInt64Ty =
3242 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3243 QualType KmpInt64Ty =
3244 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3245 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3246 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3247 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3248 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3250 RD->completeDefinition();
3255 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3256 ArrayRef<PrivateDataTy> Privates) {
3257 auto &C = CGM.getContext();
3258 // Build struct kmp_task_t_with_privates {
3259 // kmp_task_t task_data;
3260 // .kmp_privates_t. privates;
3262 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3263 RD->startDefinition();
3264 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3265 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3266 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3268 RD->completeDefinition();
3272 /// \brief Emit a proxy function which accepts kmp_task_t as the second
3275 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3276 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3278 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3283 static llvm::Value *
3284 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3285 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3286 QualType KmpTaskTWithPrivatesPtrQTy,
3287 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3288 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3289 llvm::Value *TaskPrivatesMap) {
3290 auto &C = CGM.getContext();
3291 FunctionArgList Args;
3292 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3293 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
3295 KmpTaskTWithPrivatesPtrQTy.withRestrict());
3296 Args.push_back(&GtidArg);
3297 Args.push_back(&TaskTypeArg);
3298 auto &TaskEntryFnInfo =
3299 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3300 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3302 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3303 ".omp_task_entry.", &CGM.getModule());
3304 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
3305 CodeGenFunction CGF(CGM);
3306 CGF.disableDebugInfo();
3307 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3309 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3312 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3313 // tt->task_data.shareds);
3314 auto *GtidParam = CGF.EmitLoadOfScalar(
3315 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3316 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3317 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3318 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3319 auto *KmpTaskTWithPrivatesQTyRD =
3320 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3322 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3323 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3324 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3325 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3326 auto *PartidParam = PartIdLVal.getPointer();
3328 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3329 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3330 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3331 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
3332 CGF.ConvertTypeForMem(SharedsPtrTy));
3334 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3335 llvm::Value *PrivatesParam;
3336 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3337 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3338 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3339 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
3341 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3343 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3346 .CreatePointerBitCastOrAddrSpaceCast(
3347 TDBase.getAddress(), CGF.VoidPtrTy)
3349 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3350 std::end(CommonArgs));
3351 if (isOpenMPTaskLoopDirective(Kind)) {
3352 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3353 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3354 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3355 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3356 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3357 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3358 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3359 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3360 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3361 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3362 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3363 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3364 CallArgs.push_back(LBParam);
3365 CallArgs.push_back(UBParam);
3366 CallArgs.push_back(StParam);
3367 CallArgs.push_back(LIParam);
3369 CallArgs.push_back(SharedsParam);
3371 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3372 CGF.EmitStoreThroughLValue(
3373 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3374 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3375 CGF.FinishFunction();
3379 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3381 QualType KmpInt32Ty,
3382 QualType KmpTaskTWithPrivatesPtrQTy,
3383 QualType KmpTaskTWithPrivatesQTy) {
3384 auto &C = CGM.getContext();
3385 FunctionArgList Args;
3386 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3387 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
3389 KmpTaskTWithPrivatesPtrQTy.withRestrict());
3390 Args.push_back(&GtidArg);
3391 Args.push_back(&TaskTypeArg);
3392 FunctionType::ExtInfo Info;
3393 auto &DestructorFnInfo =
3394 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3395 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3396 auto *DestructorFn =
3397 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3398 ".omp_task_destructor.", &CGM.getModule());
3399 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3401 CodeGenFunction CGF(CGM);
3402 CGF.disableDebugInfo();
3403 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3406 LValue Base = CGF.EmitLoadOfPointerLValue(
3407 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3408 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3409 auto *KmpTaskTWithPrivatesQTyRD =
3410 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3411 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3412 Base = CGF.EmitLValueForField(Base, *FI);
3414 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3415 if (auto DtorKind = Field->getType().isDestructedType()) {
3416 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3417 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3420 CGF.FinishFunction();
3421 return DestructorFn;
3424 /// \brief Emit a privates mapping function for correct handling of private and
3425 /// firstprivate variables.
3427 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3428 /// **noalias priv1,..., <tyn> **noalias privn) {
3429 /// *priv1 = &.privates.priv1;
3431 /// *privn = &.privates.privn;
3434 static llvm::Value *
3435 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3436 ArrayRef<const Expr *> PrivateVars,
3437 ArrayRef<const Expr *> FirstprivateVars,
3438 ArrayRef<const Expr *> LastprivateVars,
3439 QualType PrivatesQTy,
3440 ArrayRef<PrivateDataTy> Privates) {
3441 auto &C = CGM.getContext();
3442 FunctionArgList Args;
3443 ImplicitParamDecl TaskPrivatesArg(
3444 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3445 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3446 Args.push_back(&TaskPrivatesArg);
3447 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3448 unsigned Counter = 1;
3449 for (auto *E: PrivateVars) {
3450 Args.push_back(ImplicitParamDecl::Create(
3451 C, /*DC=*/nullptr, Loc,
3452 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3455 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3456 PrivateVarsPos[VD] = Counter;
3459 for (auto *E : FirstprivateVars) {
3460 Args.push_back(ImplicitParamDecl::Create(
3461 C, /*DC=*/nullptr, Loc,
3462 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3465 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3466 PrivateVarsPos[VD] = Counter;
3469 for (auto *E: LastprivateVars) {
3470 Args.push_back(ImplicitParamDecl::Create(
3471 C, /*DC=*/nullptr, Loc,
3472 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3475 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3476 PrivateVarsPos[VD] = Counter;
3479 auto &TaskPrivatesMapFnInfo =
3480 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3481 auto *TaskPrivatesMapTy =
3482 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3483 auto *TaskPrivatesMap = llvm::Function::Create(
3484 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3485 ".omp_task_privates_map.", &CGM.getModule());
3486 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3487 TaskPrivatesMapFnInfo);
3488 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3489 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3490 CodeGenFunction CGF(CGM);
3491 CGF.disableDebugInfo();
3492 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3493 TaskPrivatesMapFnInfo, Args);
3495 // *privi = &.privates.privi;
3496 LValue Base = CGF.EmitLoadOfPointerLValue(
3497 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3498 TaskPrivatesArg.getType()->castAs<PointerType>());
3499 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3501 for (auto *Field : PrivatesQTyRD->fields()) {
3502 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3503 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3504 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3505 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3506 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
3507 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
3510 CGF.FinishFunction();
3511 return TaskPrivatesMap;
3514 static int array_pod_sort_comparator(const PrivateDataTy *P1,
3515 const PrivateDataTy *P2) {
3516 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3519 /// Emit initialization for private variables in task-based directives.
3520 static void emitPrivatesInit(CodeGenFunction &CGF,
3521 const OMPExecutableDirective &D,
3522 Address KmpTaskSharedsPtr, LValue TDBase,
3523 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3524 QualType SharedsTy, QualType SharedsPtrTy,
3525 const OMPTaskDataTy &Data,
3526 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3527 auto &C = CGF.getContext();
3528 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3529 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3531 if (!Data.FirstprivateVars.empty()) {
3532 SrcBase = CGF.MakeAddrLValue(
3533 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3534 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3537 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3538 cast<CapturedStmt>(*D.getAssociatedStmt()));
3539 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3540 for (auto &&Pair : Privates) {
3541 auto *VD = Pair.second.PrivateCopy;
3542 auto *Init = VD->getAnyInitializer();
3543 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3544 !CGF.isTrivialInitializer(Init)))) {
3545 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3546 if (auto *Elem = Pair.second.PrivateElemInit) {
3547 auto *OriginalVD = Pair.second.Original;
3548 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3549 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3550 SharedRefLValue = CGF.MakeAddrLValue(
3551 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3552 SharedRefLValue.getType(), AlignmentSource::Decl);
3553 QualType Type = OriginalVD->getType();
3554 if (Type->isArrayType()) {
3555 // Initialize firstprivate array.
3556 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3557 // Perform simple memcpy.
3558 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3559 SharedRefLValue.getAddress(), Type);
3561 // Initialize firstprivate array using element-by-element
3563 CGF.EmitOMPAggregateAssign(
3564 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3565 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3566 Address SrcElement) {
3567 // Clean up any temporaries needed by the initialization.
3568 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3569 InitScope.addPrivate(
3570 Elem, [SrcElement]() -> Address { return SrcElement; });
3571 (void)InitScope.Privatize();
3572 // Emit initialization for single element.
3573 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3574 CGF, &CapturesInfo);
3575 CGF.EmitAnyExprToMem(Init, DestElement,
3576 Init->getType().getQualifiers(),
3577 /*IsInitializer=*/false);
3581 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3582 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3583 return SharedRefLValue.getAddress();
3585 (void)InitScope.Privatize();
3586 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3587 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3588 /*capturedByInit=*/false);
3591 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3597 /// Check if duplication function is required for taskloops.
3598 static bool checkInitIsRequired(CodeGenFunction &CGF,
3599 ArrayRef<PrivateDataTy> Privates) {
3600 bool InitRequired = false;
3601 for (auto &&Pair : Privates) {
3602 auto *VD = Pair.second.PrivateCopy;
3603 auto *Init = VD->getAnyInitializer();
3604 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3605 !CGF.isTrivialInitializer(Init));
3607 return InitRequired;
3611 /// Emit task_dup function (for initialization of
3612 /// private/firstprivate/lastprivate vars and last_iter flag)
3614 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3616 /// // setup lastprivate flag
3617 /// task_dst->last = lastpriv;
3618 /// // could be constructor calls here...
3621 static llvm::Value *
3622 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3623 const OMPExecutableDirective &D,
3624 QualType KmpTaskTWithPrivatesPtrQTy,
3625 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3626 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3627 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3628 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3629 auto &C = CGM.getContext();
3630 FunctionArgList Args;
3631 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3632 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3633 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3634 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3635 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3636 /*Id=*/nullptr, C.IntTy);
3637 Args.push_back(&DstArg);
3638 Args.push_back(&SrcArg);
3639 Args.push_back(&LastprivArg);
3640 auto &TaskDupFnInfo =
3641 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3642 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3644 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3645 ".omp_task_dup.", &CGM.getModule());
3646 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3647 CodeGenFunction CGF(CGM);
3648 CGF.disableDebugInfo();
3649 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3651 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3652 CGF.GetAddrOfLocalVar(&DstArg),
3653 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3654 // task_dst->liter = lastpriv;
3656 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3657 LValue Base = CGF.EmitLValueForField(
3658 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3659 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3660 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3661 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3662 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3665 // Emit initial values for private copies (if any).
3666 assert(!Privates.empty());
3667 Address KmpTaskSharedsPtr = Address::invalid();
3668 if (!Data.FirstprivateVars.empty()) {
3669 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3670 CGF.GetAddrOfLocalVar(&SrcArg),
3671 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3672 LValue Base = CGF.EmitLValueForField(
3673 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3674 KmpTaskSharedsPtr = Address(
3675 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3676 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3679 CGF.getNaturalTypeAlignment(SharedsTy));
3681 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3682 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
3683 CGF.FinishFunction();
3687 /// Checks if destructor function is required to be generated.
3688 /// \return true if cleanups are required, false otherwise.
3690 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3691 bool NeedsCleanup = false;
3692 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3693 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3694 for (auto *FD : PrivateRD->fields()) {
3695 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3699 return NeedsCleanup;
3702 CGOpenMPRuntime::TaskResultTy
3703 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3704 const OMPExecutableDirective &D,
3705 llvm::Value *TaskFunction, QualType SharedsTy,
3706 Address Shareds, const OMPTaskDataTy &Data) {
3707 auto &C = CGM.getContext();
3708 llvm::SmallVector<PrivateDataTy, 4> Privates;
3709 // Aggregate privates and sort them by the alignment.
3710 auto I = Data.PrivateCopies.begin();
3711 for (auto *E : Data.PrivateVars) {
3712 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3713 Privates.push_back(std::make_pair(
3715 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3716 /*PrivateElemInit=*/nullptr)));
3719 I = Data.FirstprivateCopies.begin();
3720 auto IElemInitRef = Data.FirstprivateInits.begin();
3721 for (auto *E : Data.FirstprivateVars) {
3722 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3723 Privates.push_back(std::make_pair(
3726 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3727 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
3731 I = Data.LastprivateCopies.begin();
3732 for (auto *E : Data.LastprivateVars) {
3733 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3734 Privates.push_back(std::make_pair(
3736 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3737 /*PrivateElemInit=*/nullptr)));
3740 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3741 array_pod_sort_comparator);
3742 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3743 // Build type kmp_routine_entry_t (if not built yet).
3744 emitKmpRoutineEntryT(KmpInt32Ty);
3745 // Build type kmp_task_t (if not built yet).
3746 if (KmpTaskTQTy.isNull()) {
3747 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3748 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3750 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3751 // Build particular struct kmp_task_t for the given task.
3752 auto *KmpTaskTWithPrivatesQTyRD =
3753 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3754 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3755 QualType KmpTaskTWithPrivatesPtrQTy =
3756 C.getPointerType(KmpTaskTWithPrivatesQTy);
3757 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3758 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
3759 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3760 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3762 // Emit initial values for private copies (if any).
3763 llvm::Value *TaskPrivatesMap = nullptr;
3764 auto *TaskPrivatesMapTy =
3765 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3768 if (!Privates.empty()) {
3769 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3770 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3771 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3772 FI->getType(), Privates);
3773 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3774 TaskPrivatesMap, TaskPrivatesMapTy);
3776 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3777 cast<llvm::PointerType>(TaskPrivatesMapTy));
3779 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3781 auto *TaskEntry = emitProxyTaskFunction(
3782 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3783 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3786 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3787 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3788 // kmp_routine_entry_t *task_entry);
3789 // Task flags. Format is taken from
3790 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3791 // description of kmp_tasking_flags struct.
3795 DestructorsFlag = 0x8,
3798 unsigned Flags = Data.Tied ? TiedFlag : 0;
3799 bool NeedsCleanup = false;
3800 if (!Privates.empty()) {
3801 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3803 Flags = Flags | DestructorsFlag;
3805 if (Data.Priority.getInt())
3806 Flags = Flags | PriorityFlag;
3808 Data.Final.getPointer()
3809 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
3810 CGF.Builder.getInt32(FinalFlag),
3811 CGF.Builder.getInt32(/*C=*/0))
3812 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
3813 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3814 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3815 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3816 getThreadID(CGF, Loc), TaskFlags,
3817 KmpTaskTWithPrivatesTySize, SharedsSize,
3818 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3819 TaskEntry, KmpRoutineEntryPtrTy)};
3820 auto *NewTask = CGF.EmitRuntimeCall(
3821 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
3822 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3823 NewTask, KmpTaskTWithPrivatesPtrTy);
3824 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3825 KmpTaskTWithPrivatesQTy);
3827 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
3828 // Fill the data in the resulting kmp_task_t record.
3829 // Copy shareds if there are any.
3830 Address KmpTaskSharedsPtr = Address::invalid();
3831 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
3833 Address(CGF.EmitLoadOfScalar(
3834 CGF.EmitLValueForField(
3835 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3838 CGF.getNaturalTypeAlignment(SharedsTy));
3839 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
3841 // Emit initial values for private copies (if any).
3842 TaskResultTy Result;
3843 if (!Privates.empty()) {
3844 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3845 SharedsTy, SharedsPtrTy, Data, Privates,
3847 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3848 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3849 Result.TaskDupFn = emitTaskDupFunction(
3850 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3851 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3852 /*WithLastIter=*/!Data.LastprivateVars.empty());
3855 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3856 enum { Priority = 0, Destructors = 1 };
3857 // Provide pointer to function with destructors for privates.
3858 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3859 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3861 llvm::Value *DestructorFn = emitDestructorsFunction(
3862 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3863 KmpTaskTWithPrivatesQTy);
3864 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3865 LValue DestructorsLV = CGF.EmitLValueForField(
3866 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3867 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3868 DestructorFn, KmpRoutineEntryPtrTy),
3872 if (Data.Priority.getInt()) {
3873 LValue Data2LV = CGF.EmitLValueForField(
3874 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3875 LValue PriorityLV = CGF.EmitLValueForField(
3876 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3877 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3879 Result.NewTask = NewTask;
3880 Result.TaskEntry = TaskEntry;
3881 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3882 Result.TDBase = TDBase;
3883 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3887 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3888 const OMPExecutableDirective &D,
3889 llvm::Value *TaskFunction,
3890 QualType SharedsTy, Address Shareds,
3892 const OMPTaskDataTy &Data) {
3893 if (!CGF.HaveInsertPoint())
3896 TaskResultTy Result =
3897 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3898 llvm::Value *NewTask = Result.NewTask;
3899 llvm::Value *TaskEntry = Result.TaskEntry;
3900 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3901 LValue TDBase = Result.TDBase;
3902 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
3903 auto &C = CGM.getContext();
3904 // Process list of dependences.
3905 Address DependenciesArray = Address::invalid();
3906 unsigned NumDependencies = Data.Dependences.size();
3907 if (NumDependencies) {
3908 // Dependence kind for RTL.
3909 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
3910 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3911 RecordDecl *KmpDependInfoRD;
3913 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
3914 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3915 if (KmpDependInfoTy.isNull()) {
3916 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3917 KmpDependInfoRD->startDefinition();
3918 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3919 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3920 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3921 KmpDependInfoRD->completeDefinition();
3922 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3924 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3925 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
3926 // Define type kmp_depend_info[<Dependences.size()>];
3927 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
3928 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
3929 ArrayType::Normal, /*IndexTypeQuals=*/0);
3930 // kmp_depend_info[<Dependences.size()>] deps;
3932 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
3933 for (unsigned i = 0; i < NumDependencies; ++i) {
3934 const Expr *E = Data.Dependences[i].second;
3935 auto Addr = CGF.EmitLValue(E);
3937 QualType Ty = E->getType();
3938 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3940 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3941 llvm::Value *UpAddr =
3942 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
3943 llvm::Value *LowIntPtr =
3944 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
3945 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3946 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3948 Size = CGF.getTypeSize(Ty);
3949 auto Base = CGF.MakeAddrLValue(
3950 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
3952 // deps[i].base_addr = &<Dependences[i].second>;
3953 auto BaseAddrLVal = CGF.EmitLValueForField(
3954 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
3955 CGF.EmitStoreOfScalar(
3956 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3958 // deps[i].len = sizeof(<Dependences[i].second>);
3959 auto LenLVal = CGF.EmitLValueForField(
3960 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3961 CGF.EmitStoreOfScalar(Size, LenLVal);
3962 // deps[i].flags = <Dependences[i].first>;
3963 RTLDependenceKindTy DepKind;
3964 switch (Data.Dependences[i].first) {
3965 case OMPC_DEPEND_in:
3968 // Out and InOut dependencies must use the same code.
3969 case OMPC_DEPEND_out:
3970 case OMPC_DEPEND_inout:
3973 case OMPC_DEPEND_source:
3974 case OMPC_DEPEND_sink:
3975 case OMPC_DEPEND_unknown:
3976 llvm_unreachable("Unknown task dependence type");
3978 auto FlagsLVal = CGF.EmitLValueForField(
3979 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3980 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3983 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3984 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
3988 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3990 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3991 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3992 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3993 // list is not empty
3994 auto *ThreadID = getThreadID(CGF, Loc);
3995 auto *UpLoc = emitUpdateLocation(CGF, Loc);
3996 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3997 llvm::Value *DepTaskArgs[7];
3998 if (NumDependencies) {
3999 DepTaskArgs[0] = UpLoc;
4000 DepTaskArgs[1] = ThreadID;
4001 DepTaskArgs[2] = NewTask;
4002 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4003 DepTaskArgs[4] = DependenciesArray.getPointer();
4004 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4005 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4007 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
4008 NumDependencies, &TaskArgs,
4009 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4011 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4012 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4013 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4015 if (NumDependencies) {
4016 CGF.EmitRuntimeCall(
4017 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
4019 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
4022 // Check if parent region is untied and build return for untied task;
4024 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4025 Region->emitUntiedSwitch(CGF);
4028 llvm::Value *DepWaitTaskArgs[6];
4029 if (NumDependencies) {
4030 DepWaitTaskArgs[0] = UpLoc;
4031 DepWaitTaskArgs[1] = ThreadID;
4032 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4033 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4034 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4035 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4037 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4038 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4039 PrePostActionTy &) {
4040 auto &RT = CGF.CGM.getOpenMPRuntime();
4041 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4042 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4043 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4044 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4046 if (NumDependencies)
4047 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
4049 // Call proxy_task_entry(gtid, new_task);
4050 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4051 CodeGenFunction &CGF, PrePostActionTy &Action) {
4053 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4054 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4057 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4058 // kmp_task_t *new_task);
4059 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4060 // kmp_task_t *new_task);
4061 RegionCodeGenTy RCG(CodeGen);
4062 CommonActionTy Action(
4063 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4064 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4065 RCG.setAction(Action);
4070 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
4072 RegionCodeGenTy ThenRCG(ThenCodeGen);
4077 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4078 const OMPLoopDirective &D,
4079 llvm::Value *TaskFunction,
4080 QualType SharedsTy, Address Shareds,
4082 const OMPTaskDataTy &Data) {
4083 if (!CGF.HaveInsertPoint())
4085 TaskResultTy Result =
4086 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4087 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4089 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4090 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4091 // sched, kmp_uint64 grainsize, void *task_dup);
4092 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4093 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4096 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4099 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4101 LValue LBLVal = CGF.EmitLValueForField(
4103 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
4105 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4106 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4107 /*IsInitializer=*/true);
4108 LValue UBLVal = CGF.EmitLValueForField(
4110 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
4112 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4113 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4114 /*IsInitializer=*/true);
4115 LValue StLVal = CGF.EmitLValueForField(
4117 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
4119 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4120 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4121 /*IsInitializer=*/true);
4122 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
4123 llvm::Value *TaskArgs[] = {
4124 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
4125 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4126 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
4127 llvm::ConstantInt::getSigned(
4128 CGF.IntTy, Data.Schedule.getPointer()
4129 ? Data.Schedule.getInt() ? NumTasks : Grainsize
4131 Data.Schedule.getPointer()
4132 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
4134 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
4136 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4138 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
4139 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4142 /// \brief Emit reduction operation for each element of array (required for
4143 /// array sections) LHS op = RHS.
4144 /// \param Type Type of array.
4145 /// \param LHSVar Variable on the left side of the reduction operation
4146 /// (references element of array in original variable).
4147 /// \param RHSVar Variable on the right side of the reduction operation
4148 /// (references element of array in original variable).
4149 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
4151 static void EmitOMPAggregateReduction(
4152 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4153 const VarDecl *RHSVar,
4154 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4155 const Expr *, const Expr *)> &RedOpGen,
4156 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4157 const Expr *UpExpr = nullptr) {
4158 // Perform element-by-element initialization.
4160 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4161 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4163 // Drill down to the base element type on both arrays.
4164 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4165 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4167 auto RHSBegin = RHSAddr.getPointer();
4168 auto LHSBegin = LHSAddr.getPointer();
4169 // Cast from pointer to array type to pointer to single element.
4170 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4171 // The basic structure here is a while-do loop.
4172 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4173 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4175 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4176 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4178 // Enter the loop body, making that address the current address.
4179 auto EntryBB = CGF.Builder.GetInsertBlock();
4180 CGF.EmitBlock(BodyBB);
4182 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4184 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4185 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4186 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4187 Address RHSElementCurrent =
4188 Address(RHSElementPHI,
4189 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4191 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4192 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4193 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4194 Address LHSElementCurrent =
4195 Address(LHSElementPHI,
4196 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4199 CodeGenFunction::OMPPrivateScope Scope(CGF);
4200 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4201 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4203 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4204 Scope.ForceCleanup();
4206 // Shift the address forward by one element.
4207 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4208 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4209 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4210 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4211 // Check whether we've reached the end.
4213 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4214 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4215 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4216 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4219 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4222 /// Emit reduction combiner. If the combiner is a simple expression emit it as
4223 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4224 /// UDR combiner function.
4225 static void emitReductionCombiner(CodeGenFunction &CGF,
4226 const Expr *ReductionOp) {
4227 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4228 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4230 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4231 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4232 std::pair<llvm::Function *, llvm::Function *> Reduction =
4233 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4234 RValue Func = RValue::get(Reduction.first);
4235 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4236 CGF.EmitIgnoredExpr(ReductionOp);
4239 CGF.EmitIgnoredExpr(ReductionOp);
4242 static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4243 llvm::Type *ArgsType,
4244 ArrayRef<const Expr *> Privates,
4245 ArrayRef<const Expr *> LHSExprs,
4246 ArrayRef<const Expr *> RHSExprs,
4247 ArrayRef<const Expr *> ReductionOps) {
4248 auto &C = CGM.getContext();
4250 // void reduction_func(void *LHSArg, void *RHSArg);
4251 FunctionArgList Args;
4252 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4254 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4256 Args.push_back(&LHSArg);
4257 Args.push_back(&RHSArg);
4258 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4259 auto *Fn = llvm::Function::Create(
4260 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4261 ".omp.reduction.reduction_func", &CGM.getModule());
4262 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
4263 CodeGenFunction CGF(CGM);
4264 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4266 // Dst = (void*[n])(LHSArg);
4267 // Src = (void*[n])(RHSArg);
4268 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4269 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4270 ArgsType), CGF.getPointerAlign());
4271 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4272 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4273 ArgsType), CGF.getPointerAlign());
4276 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4278 CodeGenFunction::OMPPrivateScope Scope(CGF);
4279 auto IPriv = Privates.begin();
4281 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
4282 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4283 Scope.addPrivate(RHSVar, [&]() -> Address {
4284 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
4286 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4287 Scope.addPrivate(LHSVar, [&]() -> Address {
4288 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
4290 QualType PrivTy = (*IPriv)->getType();
4291 if (PrivTy->isVariablyModifiedType()) {
4292 // Get array size and emit VLA type.
4295 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4296 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
4297 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4298 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
4299 CodeGenFunction::OpaqueValueMapping OpaqueMap(
4300 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
4301 CGF.EmitVariablyModifiedType(PrivTy);
4305 IPriv = Privates.begin();
4306 auto ILHS = LHSExprs.begin();
4307 auto IRHS = RHSExprs.begin();
4308 for (auto *E : ReductionOps) {
4309 if ((*IPriv)->getType()->isArrayType()) {
4310 // Emit reduction for array section.
4311 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4312 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4313 EmitOMPAggregateReduction(
4314 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4315 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4316 emitReductionCombiner(CGF, E);
4319 // Emit reduction for array subscript or single variable.
4320 emitReductionCombiner(CGF, E);
4325 Scope.ForceCleanup();
4326 CGF.FinishFunction();
4330 static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4331 const Expr *ReductionOp,
4332 const Expr *PrivateRef,
4333 const DeclRefExpr *LHS,
4334 const DeclRefExpr *RHS) {
4335 if (PrivateRef->getType()->isArrayType()) {
4336 // Emit reduction for array section.
4337 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4338 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4339 EmitOMPAggregateReduction(
4340 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4341 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4342 emitReductionCombiner(CGF, ReductionOp);
4345 // Emit reduction for array subscript or single variable.
4346 emitReductionCombiner(CGF, ReductionOp);
4349 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
4350 ArrayRef<const Expr *> Privates,
4351 ArrayRef<const Expr *> LHSExprs,
4352 ArrayRef<const Expr *> RHSExprs,
4353 ArrayRef<const Expr *> ReductionOps,
4354 bool WithNowait, bool SimpleReduction) {
4355 if (!CGF.HaveInsertPoint())
4357 // Next code should be emitted for reduction:
4359 // static kmp_critical_name lock = { 0 };
4361 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4362 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4364 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4365 // *(Type<n>-1*)rhs[<n>-1]);
4369 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4370 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4371 // RedList, reduce_func, &<lock>)) {
4374 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4376 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4380 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4382 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
4387 // if SimpleReduction is true, only the next code is generated:
4389 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4392 auto &C = CGM.getContext();
4394 if (SimpleReduction) {
4395 CodeGenFunction::RunCleanupsScope Scope(CGF);
4396 auto IPriv = Privates.begin();
4397 auto ILHS = LHSExprs.begin();
4398 auto IRHS = RHSExprs.begin();
4399 for (auto *E : ReductionOps) {
4400 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4401 cast<DeclRefExpr>(*IRHS));
4409 // 1. Build a list of reduction variables.
4410 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4411 auto Size = RHSExprs.size();
4412 for (auto *E : Privates) {
4413 if (E->getType()->isVariablyModifiedType())
4414 // Reserve place for array size.
4417 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4418 QualType ReductionArrayTy =
4419 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4420 /*IndexTypeQuals=*/0);
4421 Address ReductionList =
4422 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4423 auto IPriv = Privates.begin();
4425 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4427 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
4428 CGF.Builder.CreateStore(
4429 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4430 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4432 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4433 // Store array size.
4435 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4436 CGF.getPointerSize());
4437 llvm::Value *Size = CGF.Builder.CreateIntCast(
4439 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4441 CGF.SizeTy, /*isSigned=*/false);
4442 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4447 // 2. Emit reduce_func().
4448 auto *ReductionFn = emitReductionFunction(
4449 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4450 LHSExprs, RHSExprs, ReductionOps);
4452 // 3. Create static kmp_critical_name lock = { 0 };
4453 auto *Lock = getCriticalRegionLock(".reduction");
4455 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4456 // RedList, reduce_func, &<lock>);
4457 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
4458 auto *ThreadId = getThreadID(CGF, Loc);
4459 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4460 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4461 ReductionList.getPointer(), CGF.VoidPtrTy);
4462 llvm::Value *Args[] = {
4463 IdentTLoc, // ident_t *<loc>
4464 ThreadId, // i32 <gtid>
4465 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4466 ReductionArrayTySize, // size_type sizeof(RedList)
4467 RL, // void *RedList
4468 ReductionFn, // void (*) (void *, void *) <reduce_func>
4469 Lock // kmp_critical_name *&<lock>
4471 auto Res = CGF.EmitRuntimeCall(
4472 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4473 : OMPRTL__kmpc_reduce),
4476 // 5. Build switch(res)
4477 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4478 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4482 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4484 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4486 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4487 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4488 CGF.EmitBlock(Case1BB);
4490 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4491 llvm::Value *EndArgs[] = {
4492 IdentTLoc, // ident_t *<loc>
4493 ThreadId, // i32 <gtid>
4494 Lock // kmp_critical_name *&<lock>
4496 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4497 CodeGenFunction &CGF, PrePostActionTy &Action) {
4498 auto IPriv = Privates.begin();
4499 auto ILHS = LHSExprs.begin();
4500 auto IRHS = RHSExprs.begin();
4501 for (auto *E : ReductionOps) {
4502 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4503 cast<DeclRefExpr>(*IRHS));
4509 RegionCodeGenTy RCG(CodeGen);
4510 CommonActionTy Action(
4511 nullptr, llvm::None,
4512 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4513 : OMPRTL__kmpc_end_reduce),
4515 RCG.setAction(Action);
4518 CGF.EmitBranch(DefaultBB);
4522 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4525 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4526 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4527 CGF.EmitBlock(Case2BB);
4529 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4530 CodeGenFunction &CGF, PrePostActionTy &Action) {
4531 auto ILHS = LHSExprs.begin();
4532 auto IRHS = RHSExprs.begin();
4533 auto IPriv = Privates.begin();
4534 for (auto *E : ReductionOps) {
4535 const Expr *XExpr = nullptr;
4536 const Expr *EExpr = nullptr;
4537 const Expr *UpExpr = nullptr;
4538 BinaryOperatorKind BO = BO_Comma;
4539 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4540 if (BO->getOpcode() == BO_Assign) {
4541 XExpr = BO->getLHS();
4542 UpExpr = BO->getRHS();
4545 // Try to emit update expression as a simple atomic.
4546 auto *RHSExpr = UpExpr;
4548 // Analyze RHS part of the whole expression.
4549 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4550 RHSExpr->IgnoreParenImpCasts())) {
4551 // If this is a conditional operator, analyze its condition for
4552 // min/max reduction operator.
4553 RHSExpr = ACO->getCond();
4556 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4557 EExpr = BORHS->getRHS();
4558 BO = BORHS->getOpcode();
4562 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4563 auto &&AtomicRedGen = [BO, VD, IPriv,
4564 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4565 const Expr *EExpr, const Expr *UpExpr) {
4566 LValue X = CGF.EmitLValue(XExpr);
4569 E = CGF.EmitAnyExpr(EExpr);
4570 CGF.EmitOMPAtomicSimpleUpdateExpr(
4571 X, E, BO, /*IsXLHSInRHSPart=*/true,
4572 llvm::AtomicOrdering::Monotonic, Loc,
4573 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4574 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4575 PrivateScope.addPrivate(
4576 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4577 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4578 CGF.emitOMPSimpleStore(
4579 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4580 VD->getType().getNonReferenceType(), Loc);
4583 (void)PrivateScope.Privatize();
4584 return CGF.EmitAnyExpr(UpExpr);
4587 if ((*IPriv)->getType()->isArrayType()) {
4588 // Emit atomic reduction for array section.
4589 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4590 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4591 AtomicRedGen, XExpr, EExpr, UpExpr);
4593 // Emit atomic reduction for array subscript or single variable.
4594 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4596 // Emit as a critical region.
4597 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4598 const Expr *, const Expr *) {
4599 auto &RT = CGF.CGM.getOpenMPRuntime();
4600 RT.emitCriticalRegion(
4601 CGF, ".atomic_reduction",
4602 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4604 emitReductionCombiner(CGF, E);
4608 if ((*IPriv)->getType()->isArrayType()) {
4609 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4610 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4611 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4614 CritRedGen(CGF, nullptr, nullptr, nullptr);
4621 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4623 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4624 llvm::Value *EndArgs[] = {
4625 IdentTLoc, // ident_t *<loc>
4626 ThreadId, // i32 <gtid>
4627 Lock // kmp_critical_name *&<lock>
4629 CommonActionTy Action(nullptr, llvm::None,
4630 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4632 AtomicRCG.setAction(Action);
4637 CGF.EmitBranch(DefaultBB);
4638 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4641 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4642 SourceLocation Loc) {
4643 if (!CGF.HaveInsertPoint())
4645 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4647 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4648 // Ignore return result until untied tasks are supported.
4649 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4650 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4651 Region->emitUntiedSwitch(CGF);
4654 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
4655 OpenMPDirectiveKind InnerKind,
4656 const RegionCodeGenTy &CodeGen,
4658 if (!CGF.HaveInsertPoint())
4660 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
4661 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
4672 } // anonymous namespace
4674 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4675 RTCancelKind CancelKind = CancelNoreq;
4676 if (CancelRegion == OMPD_parallel)
4677 CancelKind = CancelParallel;
4678 else if (CancelRegion == OMPD_for)
4679 CancelKind = CancelLoop;
4680 else if (CancelRegion == OMPD_sections)
4681 CancelKind = CancelSections;
4683 assert(CancelRegion == OMPD_taskgroup);
4684 CancelKind = CancelTaskgroup;
4689 void CGOpenMPRuntime::emitCancellationPointCall(
4690 CodeGenFunction &CGF, SourceLocation Loc,
4691 OpenMPDirectiveKind CancelRegion) {
4692 if (!CGF.HaveInsertPoint())
4694 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4695 // global_tid, kmp_int32 cncl_kind);
4696 if (auto *OMPRegionInfo =
4697 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4698 if (OMPRegionInfo->hasCancel()) {
4699 llvm::Value *Args[] = {
4700 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4701 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4702 // Ignore return result until untied tasks are supported.
4703 auto *Result = CGF.EmitRuntimeCall(
4704 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4705 // if (__kmpc_cancellationpoint()) {
4706 // __kmpc_cancel_barrier();
4707 // exit from construct;
4709 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4710 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4711 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4712 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4713 CGF.EmitBlock(ExitBB);
4714 // __kmpc_cancel_barrier();
4715 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4716 // exit from construct;
4718 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4719 CGF.EmitBranchThroughCleanup(CancelDest);
4720 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4725 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
4727 OpenMPDirectiveKind CancelRegion) {
4728 if (!CGF.HaveInsertPoint())
4730 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4731 // kmp_int32 cncl_kind);
4732 if (auto *OMPRegionInfo =
4733 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4734 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4735 PrePostActionTy &) {
4736 auto &RT = CGF.CGM.getOpenMPRuntime();
4737 llvm::Value *Args[] = {
4738 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
4739 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4740 // Ignore return result until untied tasks are supported.
4741 auto *Result = CGF.EmitRuntimeCall(
4742 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4743 // if (__kmpc_cancel()) {
4744 // __kmpc_cancel_barrier();
4745 // exit from construct;
4747 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4748 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4749 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4750 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4751 CGF.EmitBlock(ExitBB);
4752 // __kmpc_cancel_barrier();
4753 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4754 // exit from construct;
4756 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4757 CGF.EmitBranchThroughCleanup(CancelDest);
4758 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4761 emitOMPIfClause(CGF, IfCond, ThenGen,
4762 [](CodeGenFunction &, PrePostActionTy &) {});
4764 RegionCodeGenTy ThenRCG(ThenGen);
4770 /// \brief Obtain information that uniquely identifies a target entry. This
4771 /// consists of the file and device IDs as well as line number associated with
4772 /// the relevant entry source location.
4773 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4774 unsigned &DeviceID, unsigned &FileID,
4775 unsigned &LineNum) {
4777 auto &SM = C.getSourceManager();
4779 // The loc should be always valid and have a file ID (the user cannot use
4780 // #pragma directives in macros)
4782 assert(Loc.isValid() && "Source location is expected to be always valid.");
4783 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4785 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4786 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4788 llvm::sys::fs::UniqueID ID;
4789 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4790 llvm_unreachable("Source file with target region no longer exists!");
4792 DeviceID = ID.getDevice();
4793 FileID = ID.getFile();
4794 LineNum = PLoc.getLine();
4797 void CGOpenMPRuntime::emitTargetOutlinedFunction(
4798 const OMPExecutableDirective &D, StringRef ParentName,
4799 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4800 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4801 assert(!ParentName.empty() && "Invalid target region parent name!");
4803 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4804 IsOffloadEntry, CodeGen);
4807 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4808 const OMPExecutableDirective &D, StringRef ParentName,
4809 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4810 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4811 // Create a unique name for the entry function using the source location
4812 // information of the current target region. The name will be something like:
4814 // __omp_offloading_DD_FFFF_PP_lBB
4816 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
4817 // mangled name of the function that encloses the target region and BB is the
4818 // line number of the target region.
4823 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
4825 SmallString<64> EntryFnName;
4827 llvm::raw_svector_ostream OS(EntryFnName);
4828 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4829 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
4832 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4834 CodeGenFunction CGF(CGM, true);
4835 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
4836 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4838 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4840 // If this target outline function is not an offload entry, we don't need to
4842 if (!IsOffloadEntry)
4845 // The target region ID is used by the runtime library to identify the current
4846 // target region, so it only has to be unique and not necessarily point to
4847 // anything. It could be the pointer to the outlined function that implements
4848 // the target region, but we aren't using that so that the compiler doesn't
4849 // need to keep that, and could therefore inline the host function if proven
4850 // worthwhile during optimization. In the other hand, if emitting code for the
4851 // device, the ID has to be the function address so that it can retrieved from
4852 // the offloading entry and launched by the runtime library. We also mark the
4853 // outlined function to have external linkage in case we are emitting code for
4854 // the device, because these functions will be entry points to the device.
4856 if (CGM.getLangOpts().OpenMPIsDevice) {
4857 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4858 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4860 OutlinedFnID = new llvm::GlobalVariable(
4861 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4862 llvm::GlobalValue::PrivateLinkage,
4863 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4865 // Register the information for the entry associated with this target region.
4866 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
4867 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4871 /// discard all CompoundStmts intervening between two constructs
4872 static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4873 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4874 Body = CS->body_front();
4879 /// \brief Emit the num_teams clause of an enclosed teams directive at the
4880 /// target region scope. If there is no teams directive associated with the
4881 /// target directive, or if there is no num_teams clause associated with the
4882 /// enclosed teams directive, return nullptr.
4883 static llvm::Value *
4884 emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4885 CodeGenFunction &CGF,
4886 const OMPExecutableDirective &D) {
4888 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4889 "teams directive expected to be "
4890 "emitted only for the host!");
4892 // FIXME: For the moment we do not support combined directives with target and
4893 // teams, so we do not expect to get any num_teams clause in the provided
4894 // directive. Once we support that, this assertion can be replaced by the
4895 // actual emission of the clause expression.
4896 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4897 "Not expecting clause in directive.");
4899 // If the current target region has a teams region enclosed, we need to get
4900 // the number of teams to pass to the runtime function call. This is done
4901 // by generating the expression in a inlined region. This is required because
4902 // the expression is captured in the enclosing target environment when the
4903 // teams directive is not combined with target.
4905 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4907 // FIXME: Accommodate other combined directives with teams when they become
4909 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4910 ignoreCompoundStmts(CS.getCapturedStmt()))) {
4911 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4912 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4913 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4914 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4915 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4919 // If we have an enclosed teams directive but no num_teams clause we use
4920 // the default value 0.
4921 return CGF.Builder.getInt32(0);
4924 // No teams associated with the directive.
4928 /// \brief Emit the thread_limit clause of an enclosed teams directive at the
4929 /// target region scope. If there is no teams directive associated with the
4930 /// target directive, or if there is no thread_limit clause associated with the
4931 /// enclosed teams directive, return nullptr.
4932 static llvm::Value *
4933 emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4934 CodeGenFunction &CGF,
4935 const OMPExecutableDirective &D) {
4937 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4938 "teams directive expected to be "
4939 "emitted only for the host!");
4941 // FIXME: For the moment we do not support combined directives with target and
4942 // teams, so we do not expect to get any thread_limit clause in the provided
4943 // directive. Once we support that, this assertion can be replaced by the
4944 // actual emission of the clause expression.
4945 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4946 "Not expecting clause in directive.");
4948 // If the current target region has a teams region enclosed, we need to get
4949 // the thread limit to pass to the runtime function call. This is done
4950 // by generating the expression in a inlined region. This is required because
4951 // the expression is captured in the enclosing target environment when the
4952 // teams directive is not combined with target.
4954 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4956 // FIXME: Accommodate other combined directives with teams when they become
4958 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4959 ignoreCompoundStmts(CS.getCapturedStmt()))) {
4960 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4961 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4962 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4963 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4964 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4968 // If we have an enclosed teams directive but no thread_limit clause we use
4969 // the default value 0.
4970 return CGF.Builder.getInt32(0);
4973 // No teams associated with the directive.
4978 // \brief Utility to handle information from clauses associated with a given
4979 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4980 // It provides a convenient interface to obtain the information and generate
4981 // code for that information.
4982 class MappableExprsHandler {
4984 /// \brief Values for bit flags used to specify the mapping type for
4986 enum OpenMPOffloadMappingFlags {
4987 /// \brief Allocate memory on the device and move data from host to device.
4989 /// \brief Allocate memory on the device and move data from device to host.
4990 OMP_MAP_FROM = 0x02,
4991 /// \brief Always perform the requested mapping action on the element, even
4992 /// if it was already mapped before.
4993 OMP_MAP_ALWAYS = 0x04,
4994 /// \brief Delete the element from the device environment, ignoring the
4995 /// current reference count associated with the element.
4996 OMP_MAP_DELETE = 0x08,
4997 /// \brief The element being mapped is a pointer, therefore the pointee
4998 /// should be mapped as well.
4999 OMP_MAP_IS_PTR = 0x10,
5000 /// \brief This flags signals that an argument is the first one relating to
5001 /// a map/private clause expression. For some cases a single
5002 /// map/privatization results in multiple arguments passed to the runtime
5004 OMP_MAP_FIRST_REF = 0x20,
5005 /// \brief Signal that the runtime library has to return the device pointer
5006 /// in the current position for the data being mapped.
5007 OMP_MAP_RETURN_PTR = 0x40,
5008 /// \brief This flag signals that the reference being passed is a pointer to
5010 OMP_MAP_PRIVATE_PTR = 0x80,
5011 /// \brief Pass the element to the device by value.
5012 OMP_MAP_PRIVATE_VAL = 0x100,
5015 /// Class that associates information with a base pointer to be passed to the
5016 /// runtime library.
5017 class BasePointerInfo {
5018 /// The base pointer.
5019 llvm::Value *Ptr = nullptr;
5020 /// The base declaration that refers to this device pointer, or null if
5022 const ValueDecl *DevPtrDecl = nullptr;
5025 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5026 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5027 llvm::Value *operator*() const { return Ptr; }
5028 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5029 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5032 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
5033 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5034 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5037 /// \brief Directive from where the map clauses were extracted.
5038 const OMPExecutableDirective &CurDir;
5040 /// \brief Function the directive is being generated for.
5041 CodeGenFunction &CGF;
5043 /// \brief Set of all first private variables in the current directive.
5044 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5046 /// Map between device pointer declarations and their expression components.
5047 /// The key value for declarations in 'this' is null.
5050 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5053 llvm::Value *getExprTypeSize(const Expr *E) const {
5054 auto ExprTy = E->getType().getCanonicalType();
5056 // Reference types are ignored for mapping purposes.
5057 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5058 ExprTy = RefTy->getPointeeType().getCanonicalType();
5060 // Given that an array section is considered a built-in type, we need to
5061 // do the calculation based on the length of the section instead of relying
5062 // on CGF.getTypeSize(E->getType()).
5063 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5064 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5065 OAE->getBase()->IgnoreParenImpCasts())
5066 .getCanonicalType();
5068 // If there is no length associated with the expression, that means we
5069 // are using the whole length of the base.
5070 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5071 return CGF.getTypeSize(BaseTy);
5073 llvm::Value *ElemSize;
5074 if (auto *PTy = BaseTy->getAs<PointerType>())
5075 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5077 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5078 assert(ATy && "Expecting array type if not a pointer type.");
5079 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5082 // If we don't have a length at this point, that is because we have an
5083 // array section with a single element.
5084 if (!OAE->getLength())
5087 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5089 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5090 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5092 return CGF.getTypeSize(ExprTy);
5095 /// \brief Return the corresponding bits for a given map clause modifier. Add
5096 /// a flag marking the map as a pointer if requested. Add a flag marking the
5097 /// map as the first one of a series of maps that relate to the same map
5099 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5100 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
5101 bool AddIsFirstFlag) const {
5104 case OMPC_MAP_alloc:
5105 case OMPC_MAP_release:
5106 // alloc and release is the default behavior in the runtime library, i.e.
5107 // if we don't pass any bits alloc/release that is what the runtime is
5108 // going to do. Therefore, we don't need to signal anything for these two
5115 Bits = OMP_MAP_FROM;
5117 case OMPC_MAP_tofrom:
5118 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5120 case OMPC_MAP_delete:
5121 Bits = OMP_MAP_DELETE;
5124 llvm_unreachable("Unexpected map type!");
5128 Bits |= OMP_MAP_IS_PTR;
5130 Bits |= OMP_MAP_FIRST_REF;
5131 if (MapTypeModifier == OMPC_MAP_always)
5132 Bits |= OMP_MAP_ALWAYS;
5136 /// \brief Return true if the provided expression is a final array section. A
5137 /// final array section, is one whose length can't be proved to be one.
5138 bool isFinalArraySectionExpression(const Expr *E) const {
5139 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5141 // It is not an array section and therefore not a unity-size one.
5145 // An array section with no colon always refer to a single element.
5146 if (OASE->getColonLoc().isInvalid())
5149 auto *Length = OASE->getLength();
5151 // If we don't have a length we have to check if the array has size 1
5152 // for this dimension. Also, we should always expect a length if the
5153 // base type is pointer.
5155 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5156 OASE->getBase()->IgnoreParenImpCasts())
5157 .getCanonicalType();
5158 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5159 return ATy->getSize().getSExtValue() != 1;
5160 // If we don't have a constant dimension length, we have to consider
5161 // the current section as having any size, so it is not necessarily
5162 // unitary. If it happen to be unity size, that's user fault.
5166 // Check if the length evaluates to 1.
5167 llvm::APSInt ConstLength;
5168 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5169 return true; // Can have more that size 1.
5171 return ConstLength.getSExtValue() != 1;
5174 /// \brief Generate the base pointers, section pointers, sizes and map type
5175 /// bits for the provided map type, map modifier, and expression components.
5176 /// \a IsFirstComponent should be set to true if the provided set of
5177 /// components is the first associated with a capture.
5178 void generateInfoForComponentList(
5179 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5180 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5181 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
5182 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5183 bool IsFirstComponentList) const {
5185 // The following summarizes what has to be generated for each map and the
5186 // types bellow. The generated information is expressed in this order:
5187 // base pointer, section pointer, size, flags
5188 // (to add to the ones that come from the map type and modifier).
5209 // &d, &d, sizeof(double), noflags
5212 // &i, &i, 100*sizeof(int), noflags
5215 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5218 // &p, &p, sizeof(float*), noflags
5221 // p, &p[1], 24*sizeof(float), noflags
5224 // &s, &s, sizeof(S2), noflags
5227 // &s, &(s.i), sizeof(int), noflags
5230 // &s, &(s.i.f), 50*sizeof(int), noflags
5233 // &s, &(s.p), sizeof(double*), noflags
5235 // map(s.p[:22], s.a s.b)
5236 // &s, &(s.p), sizeof(double*), noflags
5237 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5240 // &s, &(s.ps), sizeof(S2*), noflags
5243 // &s, &(s.ps), sizeof(S2*), noflags
5244 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5247 // &s, &(s.ps), sizeof(S2*), noflags
5248 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5250 // map(s.ps->ps->ps)
5251 // &s, &(s.ps), sizeof(S2*), noflags
5252 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5253 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5255 // map(s.ps->ps->s.f[:22])
5256 // &s, &(s.ps), sizeof(S2*), noflags
5257 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5258 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5261 // &ps, &ps, sizeof(S2*), noflags
5264 // ps, &(ps->i), sizeof(int), noflags
5267 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5270 // ps, &(ps->p), sizeof(double*), noflags
5273 // ps, &(ps->p), sizeof(double*), noflags
5274 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5277 // ps, &(ps->ps), sizeof(S2*), noflags
5280 // ps, &(ps->ps), sizeof(S2*), noflags
5281 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5284 // ps, &(ps->ps), sizeof(S2*), noflags
5285 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5287 // map(ps->ps->ps->ps)
5288 // ps, &(ps->ps), sizeof(S2*), noflags
5289 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5290 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5292 // map(ps->ps->ps->s.f[:22])
5293 // ps, &(ps->ps), sizeof(S2*), noflags
5294 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5295 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5298 // Track if the map information being generated is the first for a capture.
5299 bool IsCaptureFirstInfo = IsFirstComponentList;
5301 // Scan the components from the base to the complete expression.
5302 auto CI = Components.rbegin();
5303 auto CE = Components.rend();
5306 // Track if the map information being generated is the first for a list of
5308 bool IsExpressionFirstInfo = true;
5309 llvm::Value *BP = nullptr;
5311 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5312 // The base is the 'this' pointer. The content of the pointer is going
5313 // to be the base of the field being mapped.
5314 BP = CGF.EmitScalarExpr(ME->getBase());
5316 // The base is the reference to the variable.
5318 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5321 // If the variable is a pointer and is being dereferenced (i.e. is not
5322 // the last component), the base has to be the pointer itself, not its
5323 // reference. References are ignored for mapping purposes.
5325 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5326 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5327 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
5328 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
5329 Ty->castAs<PointerType>())
5332 // We do not need to generate individual map information for the
5333 // pointer, it can be associated with the combined storage.
5338 for (; I != CE; ++I) {
5339 auto Next = std::next(I);
5341 // We need to generate the addresses and sizes if this is the last
5342 // component, if the component is a pointer or if it is an array section
5343 // whose length can't be proved to be one. If this is a pointer, it
5344 // becomes the base address for the following components.
5346 // A final array section, is one whose length can't be proved to be one.
5347 bool IsFinalArraySection =
5348 isFinalArraySectionExpression(I->getAssociatedExpression());
5350 // Get information on whether the element is a pointer. Have to do a
5351 // special treatment for array sections given that they are built-in
5354 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5357 OMPArraySectionExpr::getBaseOriginalType(OASE)
5359 ->isAnyPointerType()) ||
5360 I->getAssociatedExpression()->getType()->isAnyPointerType();
5362 if (Next == CE || IsPointer || IsFinalArraySection) {
5364 // If this is not the last component, we expect the pointer to be
5365 // associated with an array expression or member expression.
5366 assert((Next == CE ||
5367 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5368 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5369 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5370 "Unexpected expression");
5372 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5373 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5375 // If we have a member expression and the current component is a
5376 // reference, we have to map the reference too. Whenever we have a
5377 // reference, the section that reference refers to is going to be a
5378 // load instruction from the storage assigned to the reference.
5379 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5380 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5381 auto *LI = cast<llvm::LoadInst>(LB);
5382 auto *RefAddr = LI->getPointerOperand();
5384 BasePointers.push_back(BP);
5385 Pointers.push_back(RefAddr);
5386 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5387 Types.push_back(getMapTypeBits(
5388 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5389 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5390 IsExpressionFirstInfo = false;
5391 IsCaptureFirstInfo = false;
5392 // The reference will be the next base address.
5396 BasePointers.push_back(BP);
5397 Pointers.push_back(LB);
5398 Sizes.push_back(Size);
5400 // We need to add a pointer flag for each map that comes from the
5401 // same expression except for the first one. We also need to signal
5402 // this map is the first one that relates with the current capture
5403 // (there is a set of entries for each capture).
5404 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5405 !IsExpressionFirstInfo,
5406 IsCaptureFirstInfo));
5408 // If we have a final array section, we are done with this expression.
5409 if (IsFinalArraySection)
5412 // The pointer becomes the base for the next element.
5416 IsExpressionFirstInfo = false;
5417 IsCaptureFirstInfo = false;
5423 /// \brief Return the adjusted map modifiers if the declaration a capture
5424 /// refers to appears in a first-private clause. This is expected to be used
5425 /// only with directives that start with 'target'.
5426 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5427 unsigned CurrentModifiers) {
5428 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5430 // A first private variable captured by reference will use only the
5431 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5432 // declaration is known as first-private in this handler.
5433 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5434 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5435 MappableExprsHandler::OMP_MAP_TO;
5437 // We didn't modify anything.
5438 return CurrentModifiers;
5442 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
5443 : CurDir(Dir), CGF(CGF) {
5444 // Extract firstprivate clause information.
5445 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5446 for (const auto *D : C->varlists())
5447 FirstPrivateDecls.insert(
5448 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
5449 // Extract device pointer clause information.
5450 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5451 for (auto L : C->component_lists())
5452 DevPointersMap[L.first].push_back(L.second);
5455 /// \brief Generate all the base pointers, section pointers, sizes and map
5456 /// types for the extracted mappable expressions. Also, for each item that
5457 /// relates with a device pointer, a pair of the relevant declaration and
5458 /// index where it occurs is appended to the device pointers info array.
5459 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
5460 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5461 MapFlagsArrayTy &Types) const {
5462 BasePointers.clear();
5468 /// Kind that defines how a device pointer has to be returned.
5469 enum ReturnPointerKind {
5470 // Don't have to return any pointer.
5472 // Pointer is the base of the declaration.
5474 // Pointer is a member of the base declaration - 'this'
5476 // Pointer is a reference and a member of the base declaration - 'this'
5477 RPK_MemberReference,
5479 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5480 OpenMPMapClauseKind MapType;
5481 OpenMPMapClauseKind MapTypeModifier;
5482 ReturnPointerKind ReturnDevicePointer;
5485 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5486 ReturnDevicePointer(RPK_None) {}
5488 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5489 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5490 ReturnPointerKind ReturnDevicePointer)
5491 : Components(Components), MapType(MapType),
5492 MapTypeModifier(MapTypeModifier),
5493 ReturnDevicePointer(ReturnDevicePointer) {}
5496 // We have to process the component lists that relate with the same
5497 // declaration in a single chunk so that we can generate the map flags
5498 // correctly. Therefore, we organize all lists in a map.
5499 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
5501 // Helper function to fill the information map for the different supported
5503 auto &&InfoGen = [&Info](
5505 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5506 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
5507 MapInfo::ReturnPointerKind ReturnDevicePointer) {
5508 const ValueDecl *VD =
5509 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5510 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5513 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5514 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5515 for (auto L : C->component_lists())
5516 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5518 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
5519 for (auto L : C->component_lists())
5520 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5522 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
5523 for (auto L : C->component_lists())
5524 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5527 // Look at the use_device_ptr clause information and mark the existing map
5528 // entries as such. If there is no map information for an entry in the
5529 // use_device_ptr list, we create one with map type 'alloc' and zero size
5530 // section. It is the user fault if that was not mapped before.
5531 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5532 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
5533 for (auto L : C->component_lists()) {
5534 assert(!L.second.empty() && "Not expecting empty list of components!");
5535 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5536 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5537 auto *IE = L.second.back().getAssociatedExpression();
5538 // If the first component is a member expression, we have to look into
5539 // 'this', which maps to null in the map of map information. Otherwise
5540 // look directly for the information.
5541 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5543 // We potentially have map information for this declaration already.
5544 // Look for the first set of components that refer to it.
5545 if (It != Info.end()) {
5546 auto CI = std::find_if(
5547 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5548 return MI.Components.back().getAssociatedDeclaration() == VD;
5550 // If we found a map entry, signal that the pointer has to be returned
5551 // and move on to the next declaration.
5552 if (CI != It->second.end()) {
5553 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5554 ? (VD->getType()->isReferenceType()
5555 ? MapInfo::RPK_MemberReference
5556 : MapInfo::RPK_Member)
5557 : MapInfo::RPK_Base;
5562 // We didn't find any match in our map information - generate a zero
5563 // size array section.
5564 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
5567 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
5569 BasePointers.push_back({Ptr, VD});
5570 Pointers.push_back(Ptr);
5571 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
5572 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5575 for (auto &M : Info) {
5576 // We need to know when we generate information for the first component
5577 // associated with a capture, because the mapping flags depend on it.
5578 bool IsFirstComponentList = true;
5579 for (MapInfo &L : M.second) {
5580 assert(!L.Components.empty() &&
5581 "Not expecting declaration with no component lists.");
5583 // Remember the current base pointer index.
5584 unsigned CurrentBasePointersIdx = BasePointers.size();
5585 // FIXME: MSVC 2013 seems to require this-> to find the member method.
5586 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5587 L.Components, BasePointers, Pointers,
5588 Sizes, Types, IsFirstComponentList);
5590 // If this entry relates with a device pointer, set the relevant
5591 // declaration and add the 'return pointer' flag.
5592 if (IsFirstComponentList &&
5593 L.ReturnDevicePointer != MapInfo::RPK_None) {
5594 // If the pointer is not the base of the map, we need to skip the
5595 // base. If it is a reference in a member field, we also need to skip
5596 // the map of the reference.
5597 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5598 ++CurrentBasePointersIdx;
5599 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5600 ++CurrentBasePointersIdx;
5602 assert(BasePointers.size() > CurrentBasePointersIdx &&
5603 "Unexpected number of mapped base pointers.");
5605 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5606 assert(RelevantVD &&
5607 "No relevant declaration related with device pointer??");
5609 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5610 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5612 IsFirstComponentList = false;
5617 /// \brief Generate the base pointers, section pointers, sizes and map types
5618 /// associated to a given capture.
5619 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5621 MapBaseValuesArrayTy &BasePointers,
5622 MapValuesArrayTy &Pointers,
5623 MapValuesArrayTy &Sizes,
5624 MapFlagsArrayTy &Types) const {
5625 assert(!Cap->capturesVariableArrayType() &&
5626 "Not expecting to generate map info for a variable array type!");
5628 BasePointers.clear();
5633 // We need to know when we generating information for the first component
5634 // associated with a capture, because the mapping flags depend on it.
5635 bool IsFirstComponentList = true;
5637 const ValueDecl *VD =
5640 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5642 // If this declaration appears in a is_device_ptr clause we just have to
5643 // pass the pointer by value. If it is a reference to a declaration, we just
5644 // pass its value, otherwise, if it is a member expression, we need to map
5647 auto It = DevPointersMap.find(VD);
5648 if (It != DevPointersMap.end()) {
5649 for (auto L : It->second) {
5650 generateInfoForComponentList(
5651 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5652 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5653 IsFirstComponentList = false;
5657 } else if (DevPointersMap.count(VD)) {
5658 BasePointers.push_back({Arg, VD});
5659 Pointers.push_back(Arg);
5660 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5661 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5665 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
5666 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
5667 for (auto L : C->decl_component_lists(VD)) {
5668 assert(L.first == VD &&
5669 "We got information for the wrong declaration??");
5670 assert(!L.second.empty() &&
5671 "Not expecting declaration with no component lists.");
5672 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5673 L.second, BasePointers, Pointers, Sizes,
5674 Types, IsFirstComponentList);
5675 IsFirstComponentList = false;
5681 /// \brief Generate the default map information for a given capture \a CI,
5682 /// record field declaration \a RI and captured value \a CV.
5683 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5684 const FieldDecl &RI, llvm::Value *CV,
5685 MapBaseValuesArrayTy &CurBasePointers,
5686 MapValuesArrayTy &CurPointers,
5687 MapValuesArrayTy &CurSizes,
5688 MapFlagsArrayTy &CurMapTypes) {
5690 // Do the default mapping.
5691 if (CI.capturesThis()) {
5692 CurBasePointers.push_back(CV);
5693 CurPointers.push_back(CV);
5694 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5695 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5696 // Default map type.
5697 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
5698 } else if (CI.capturesVariableByCopy()) {
5699 CurBasePointers.push_back(CV);
5700 CurPointers.push_back(CV);
5701 if (!RI.getType()->isAnyPointerType()) {
5702 // We have to signal to the runtime captures passed by value that are
5704 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
5705 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5707 // Pointers are implicitly mapped with a zero size and no flags
5708 // (other than first map that is added for all implicit maps).
5709 CurMapTypes.push_back(0u);
5710 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5713 assert(CI.capturesVariable() && "Expected captured reference.");
5714 CurBasePointers.push_back(CV);
5715 CurPointers.push_back(CV);
5717 const ReferenceType *PtrTy =
5718 cast<ReferenceType>(RI.getType().getTypePtr());
5719 QualType ElementType = PtrTy->getPointeeType();
5720 CurSizes.push_back(CGF.getTypeSize(ElementType));
5721 // The default map type for a scalar/complex type is 'to' because by
5722 // default the value doesn't have to be retrieved. For an aggregate
5723 // type, the default is 'tofrom'.
5724 CurMapTypes.push_back(ElementType->isAggregateType()
5725 ? (OMP_MAP_TO | OMP_MAP_FROM)
5728 // If we have a capture by reference we may need to add the private
5729 // pointer flag if the base declaration shows in some first-private
5731 CurMapTypes.back() =
5732 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5734 // Every default map produces a single argument, so, it is always the
5736 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
5740 enum OpenMPOffloadingReservedDeviceIDs {
5741 /// \brief Device ID if the device was not defined, runtime should get it
5742 /// from environment variables in the spec.
5743 OMP_DEVICEID_UNDEF = -1,
5745 } // anonymous namespace
5747 /// \brief Emit the arrays used to pass the captures and map information to the
5748 /// offloading runtime library. If there is no map or capture information,
5749 /// return nullptr by reference.
5751 emitOffloadingArrays(CodeGenFunction &CGF,
5752 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
5753 MappableExprsHandler::MapValuesArrayTy &Pointers,
5754 MappableExprsHandler::MapValuesArrayTy &Sizes,
5755 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5756 CGOpenMPRuntime::TargetDataInfo &Info) {
5757 auto &CGM = CGF.CGM;
5758 auto &Ctx = CGF.getContext();
5760 // Reset the array information.
5761 Info.clearArrayInfo();
5762 Info.NumberOfPtrs = BasePointers.size();
5764 if (Info.NumberOfPtrs) {
5765 // Detect if we have any capture size requiring runtime evaluation of the
5766 // size so that a constant array could be eventually used.
5767 bool hasRuntimeEvaluationCaptureSize = false;
5768 for (auto *S : Sizes)
5769 if (!isa<llvm::Constant>(S)) {
5770 hasRuntimeEvaluationCaptureSize = true;
5774 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
5775 QualType PointerArrayType =
5776 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5777 /*IndexTypeQuals=*/0);
5779 Info.BasePointersArray =
5780 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5781 Info.PointersArray =
5782 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5784 // If we don't have any VLA types or other types that require runtime
5785 // evaluation, we can use a constant array for the map sizes, otherwise we
5786 // need to fill up the arrays as we do for the pointers.
5787 if (hasRuntimeEvaluationCaptureSize) {
5788 QualType SizeArrayType = Ctx.getConstantArrayType(
5789 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5790 /*IndexTypeQuals=*/0);
5792 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5794 // We expect all the sizes to be constant, so we collect them to create
5795 // a constant array.
5796 SmallVector<llvm::Constant *, 16> ConstSizes;
5797 for (auto S : Sizes)
5798 ConstSizes.push_back(cast<llvm::Constant>(S));
5800 auto *SizesArrayInit = llvm::ConstantArray::get(
5801 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5802 auto *SizesArrayGbl = new llvm::GlobalVariable(
5803 CGM.getModule(), SizesArrayInit->getType(),
5804 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5805 SizesArrayInit, ".offload_sizes");
5806 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5807 Info.SizesArray = SizesArrayGbl;
5810 // The map types are always constant so we don't need to generate code to
5811 // fill arrays. Instead, we create an array constant.
5812 llvm::Constant *MapTypesArrayInit =
5813 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5814 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5815 CGM.getModule(), MapTypesArrayInit->getType(),
5816 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5817 MapTypesArrayInit, ".offload_maptypes");
5818 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5819 Info.MapTypesArray = MapTypesArrayGbl;
5821 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5822 llvm::Value *BPVal = *BasePointers[i];
5823 if (BPVal->getType()->isPointerTy())
5824 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5826 assert(BPVal->getType()->isIntegerTy() &&
5827 "If not a pointer, the value type must be an integer.");
5828 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5830 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
5831 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5832 Info.BasePointersArray, 0, i);
5833 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5834 CGF.Builder.CreateStore(BPVal, BPAddr);
5836 if (Info.requiresDevicePointerInfo())
5837 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5838 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5840 llvm::Value *PVal = Pointers[i];
5841 if (PVal->getType()->isPointerTy())
5842 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5844 assert(PVal->getType()->isIntegerTy() &&
5845 "If not a pointer, the value type must be an integer.");
5846 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5848 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
5849 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5850 Info.PointersArray, 0, i);
5851 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5852 CGF.Builder.CreateStore(PVal, PAddr);
5854 if (hasRuntimeEvaluationCaptureSize) {
5855 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
5856 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5860 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5861 CGF.Builder.CreateStore(
5862 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5868 /// \brief Emit the arguments to be passed to the runtime library based on the
5869 /// arrays of pointers, sizes and map types.
5870 static void emitOffloadingArraysArgument(
5871 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5872 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
5873 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
5874 auto &CGM = CGF.CGM;
5875 if (Info.NumberOfPtrs) {
5876 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5877 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5878 Info.BasePointersArray,
5879 /*Idx0=*/0, /*Idx1=*/0);
5880 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5881 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5885 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5886 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
5887 /*Idx0=*/0, /*Idx1=*/0);
5888 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
5889 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5894 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5895 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5896 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5898 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5902 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5903 const OMPExecutableDirective &D,
5904 llvm::Value *OutlinedFn,
5905 llvm::Value *OutlinedFnID,
5906 const Expr *IfCond, const Expr *Device,
5907 ArrayRef<llvm::Value *> CapturedVars) {
5908 if (!CGF.HaveInsertPoint())
5911 assert(OutlinedFn && "Invalid outlined function!");
5913 auto &Ctx = CGF.getContext();
5915 // Fill up the arrays with all the captured variables.
5916 MappableExprsHandler::MapValuesArrayTy KernelArgs;
5917 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
5918 MappableExprsHandler::MapValuesArrayTy Pointers;
5919 MappableExprsHandler::MapValuesArrayTy Sizes;
5920 MappableExprsHandler::MapFlagsArrayTy MapTypes;
5922 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
5923 MappableExprsHandler::MapValuesArrayTy CurPointers;
5924 MappableExprsHandler::MapValuesArrayTy CurSizes;
5925 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5927 // Get mappable expression information.
5928 MappableExprsHandler MEHandler(D, CGF);
5930 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5931 auto RI = CS.getCapturedRecordDecl()->field_begin();
5932 auto CV = CapturedVars.begin();
5933 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5934 CE = CS.capture_end();
5935 CI != CE; ++CI, ++RI, ++CV) {
5939 CurBasePointers.clear();
5940 CurPointers.clear();
5942 CurMapTypes.clear();
5944 // VLA sizes are passed to the outlined region by copy and do not have map
5945 // information associated.
5946 if (CI->capturesVariableArrayType()) {
5947 CurBasePointers.push_back(*CV);
5948 CurPointers.push_back(*CV);
5949 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
5950 // Copy to the device as an argument. No need to retrieve it.
5951 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5952 MappableExprsHandler::OMP_MAP_FIRST_REF);
5954 // If we have any information in the map clause, we use it, otherwise we
5955 // just do a default mapping.
5956 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
5957 CurSizes, CurMapTypes);
5958 if (CurBasePointers.empty())
5959 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5960 CurPointers, CurSizes, CurMapTypes);
5962 // We expect to have at least an element of information for this capture.
5963 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5964 assert(CurBasePointers.size() == CurPointers.size() &&
5965 CurBasePointers.size() == CurSizes.size() &&
5966 CurBasePointers.size() == CurMapTypes.size() &&
5967 "Inconsistent map information sizes!");
5969 // The kernel args are always the first elements of the base pointers
5970 // associated with a capture.
5971 KernelArgs.push_back(*CurBasePointers.front());
5972 // We need to append the results of this capture to what we already have.
5973 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5974 Pointers.append(CurPointers.begin(), CurPointers.end());
5975 Sizes.append(CurSizes.begin(), CurSizes.end());
5976 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
5979 // Keep track on whether the host function has to be executed.
5980 auto OffloadErrorQType =
5981 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
5982 auto OffloadError = CGF.MakeAddrLValue(
5983 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5985 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5988 // Fill up the pointer arrays and transfer execution to the device.
5989 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5990 OutlinedFnID, OffloadError, OffloadErrorQType,
5991 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5992 auto &RT = CGF.CGM.getOpenMPRuntime();
5993 // Emit the offloading arrays.
5994 TargetDataInfo Info;
5995 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5996 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5997 Info.PointersArray, Info.SizesArray,
5998 Info.MapTypesArray, Info);
6000 // On top of the arrays that were filled up, the target offloading call
6001 // takes as arguments the device id as well as the host pointer. The host
6002 // pointer is used by the runtime library to identify the current target
6003 // region, so it only has to be unique and not necessarily point to
6004 // anything. It could be the pointer to the outlined function that
6005 // implements the target region, but we aren't using that so that the
6006 // compiler doesn't need to keep that, and could therefore inline the host
6007 // function if proven worthwhile during optimization.
6009 // From this point on, we need to have an ID of the target region defined.
6010 assert(OutlinedFnID && "Invalid outlined function ID!");
6012 // Emit device ID if any.
6013 llvm::Value *DeviceID;
6015 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6016 CGF.Int32Ty, /*isSigned=*/true);
6018 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6020 // Emit the number of elements in the offloading arrays.
6021 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6023 // Return value of the runtime offloading call.
6024 llvm::Value *Return;
6026 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6027 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
6029 // If we have NumTeams defined this means that we have an enclosed teams
6030 // region. Therefore we also expect to have ThreadLimit defined. These two
6031 // values should be defined in the presence of a teams directive, regardless
6032 // of having any clauses associated. If the user is using teams but no
6033 // clauses, these two values will be the default that should be passed to
6034 // the runtime library - a 32-bit integer with the value zero.
6036 assert(ThreadLimit && "Thread limit expression should be available along "
6037 "with number of teams.");
6038 llvm::Value *OffloadingArgs[] = {
6039 DeviceID, OutlinedFnID,
6040 PointerNum, Info.BasePointersArray,
6041 Info.PointersArray, Info.SizesArray,
6042 Info.MapTypesArray, NumTeams,
6044 Return = CGF.EmitRuntimeCall(
6045 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
6047 llvm::Value *OffloadingArgs[] = {
6048 DeviceID, OutlinedFnID,
6049 PointerNum, Info.BasePointersArray,
6050 Info.PointersArray, Info.SizesArray,
6051 Info.MapTypesArray};
6052 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
6056 CGF.EmitStoreOfScalar(Return, OffloadError);
6059 // Notify that the host version must be executed.
6060 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6061 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
6065 // If we have a target function ID it means that we need to support
6066 // offloading, otherwise, just execute on the host. We need to execute on host
6067 // regardless of the conditional in the if clause if, e.g., the user do not
6068 // specify target triples.
6071 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6073 RegionCodeGenTy ThenRCG(ThenGen);
6077 RegionCodeGenTy ElseRCG(ElseGen);
6081 // Check the error code and execute the host version if required.
6082 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6083 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6084 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6085 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6086 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6088 CGF.EmitBlock(OffloadFailedBlock);
6089 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
6090 CGF.EmitBranch(OffloadContBlock);
6092 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
6095 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6096 StringRef ParentName) {
6100 // If we find a OMP target directive, codegen the outline function and
6101 // register the result.
6102 // FIXME: Add other directives with target when they become supported.
6103 bool isTargetDirective = isa<OMPTargetDirective>(S);
6105 if (isTargetDirective) {
6106 auto *E = cast<OMPExecutableDirective>(S);
6110 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
6113 // Is this a target region that should not be emitted as an entry point? If
6114 // so just signal we are done with this target region.
6115 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6120 llvm::Constant *Addr;
6121 std::tie(Fn, Addr) =
6122 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6123 CGM, cast<OMPTargetDirective>(*E), ParentName,
6124 /*isOffloadEntry=*/true);
6125 assert(Fn && Addr && "Target region emission failed.");
6129 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
6130 if (!E->hasAssociatedStmt())
6133 scanForTargetRegionsFunctions(
6134 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6139 // If this is a lambda function, look into its body.
6140 if (auto *L = dyn_cast<LambdaExpr>(S))
6143 // Keep looking for target regions recursively.
6144 for (auto *II : S->children())
6145 scanForTargetRegionsFunctions(II, ParentName);
6148 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6149 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6151 // If emitting code for the host, we do not process FD here. Instead we do
6152 // the normal code generation.
6153 if (!CGM.getLangOpts().OpenMPIsDevice)
6156 // Try to detect target regions in the function.
6157 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6159 // We should not emit any function other that the ones created during the
6160 // scanning. Therefore, we signal that this function is completely dealt
6165 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6166 if (!CGM.getLangOpts().OpenMPIsDevice)
6169 // Check if there are Ctors/Dtors in this declaration and look for target
6170 // regions in it. We use the complete variant to produce the kernel name
6172 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6173 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6174 for (auto *Ctor : RD->ctors()) {
6175 StringRef ParentName =
6176 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6177 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6179 auto *Dtor = RD->getDestructor();
6181 StringRef ParentName =
6182 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6183 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6187 // If we are in target mode we do not emit any global (declare target is not
6188 // implemented yet). Therefore we signal that GD was processed in this case.
6192 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6193 auto *VD = GD.getDecl();
6194 if (isa<FunctionDecl>(VD))
6195 return emitTargetFunctions(GD);
6197 return emitTargetGlobalVariable(GD);
6200 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6201 // If we have offloading in the current module, we need to emit the entries
6202 // now and register the offloading descriptor.
6203 createOffloadEntriesAndInfoMetadata();
6205 // Create and register the offloading binary descriptors. This is the main
6206 // entity that captures all the information about offloading in the current
6207 // compilation unit.
6208 return createOffloadingBinaryDescriptorRegistration();
6211 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6212 const OMPExecutableDirective &D,
6214 llvm::Value *OutlinedFn,
6215 ArrayRef<llvm::Value *> CapturedVars) {
6216 if (!CGF.HaveInsertPoint())
6219 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6220 CodeGenFunction::RunCleanupsScope Scope(CGF);
6222 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6223 llvm::Value *Args[] = {
6225 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6226 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6227 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6228 RealArgs.append(std::begin(Args), std::end(Args));
6229 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6231 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6232 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6235 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
6236 const Expr *NumTeams,
6237 const Expr *ThreadLimit,
6238 SourceLocation Loc) {
6239 if (!CGF.HaveInsertPoint())
6242 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6244 llvm::Value *NumTeamsVal =
6246 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6247 CGF.CGM.Int32Ty, /* isSigned = */ true)
6248 : CGF.Builder.getInt32(0);
6250 llvm::Value *ThreadLimitVal =
6252 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6253 CGF.CGM.Int32Ty, /* isSigned = */ true)
6254 : CGF.Builder.getInt32(0);
6256 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
6257 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6259 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6263 void CGOpenMPRuntime::emitTargetDataCalls(
6264 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6265 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
6266 if (!CGF.HaveInsertPoint())
6269 // Action used to replace the default codegen action and turn privatization
6271 PrePostActionTy NoPrivAction;
6273 // Generate the code for the opening of the data environment. Capture all the
6274 // arguments of the runtime call by reference because they are used in the
6275 // closing of the region.
6276 auto &&BeginThenGen = [&D, &CGF, Device, &Info, &CodeGen, &NoPrivAction](
6277 CodeGenFunction &CGF, PrePostActionTy &) {
6278 // Fill up the arrays with all the mapped variables.
6279 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6280 MappableExprsHandler::MapValuesArrayTy Pointers;
6281 MappableExprsHandler::MapValuesArrayTy Sizes;
6282 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6284 // Get map clause information.
6285 MappableExprsHandler MCHandler(D, CGF);
6286 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6288 // Fill up the arrays and create the arguments.
6289 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6291 llvm::Value *BasePointersArrayArg = nullptr;
6292 llvm::Value *PointersArrayArg = nullptr;
6293 llvm::Value *SizesArrayArg = nullptr;
6294 llvm::Value *MapTypesArrayArg = nullptr;
6295 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6296 SizesArrayArg, MapTypesArrayArg, Info);
6298 // Emit device ID if any.
6299 llvm::Value *DeviceID = nullptr;
6301 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6302 CGF.Int32Ty, /*isSigned=*/true);
6304 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6306 // Emit the number of elements in the offloading arrays.
6307 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6309 llvm::Value *OffloadingArgs[] = {
6310 DeviceID, PointerNum, BasePointersArrayArg,
6311 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6312 auto &RT = CGF.CGM.getOpenMPRuntime();
6313 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6316 // If device pointer privatization is required, emit the body of the region
6317 // here. It will have to be duplicated: with and without privatization.
6318 if (!Info.CaptureDeviceAddrMap.empty())
6322 // Generate code for the closing of the data region.
6323 auto &&EndThenGen = [&CGF, Device, &Info](CodeGenFunction &CGF,
6324 PrePostActionTy &) {
6325 assert(Info.isValid() && "Invalid data environment closing arguments.");
6327 llvm::Value *BasePointersArrayArg = nullptr;
6328 llvm::Value *PointersArrayArg = nullptr;
6329 llvm::Value *SizesArrayArg = nullptr;
6330 llvm::Value *MapTypesArrayArg = nullptr;
6331 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
6332 SizesArrayArg, MapTypesArrayArg, Info);
6334 // Emit device ID if any.
6335 llvm::Value *DeviceID = nullptr;
6337 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6338 CGF.Int32Ty, /*isSigned=*/true);
6340 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6342 // Emit the number of elements in the offloading arrays.
6343 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
6345 llvm::Value *OffloadingArgs[] = {
6346 DeviceID, PointerNum, BasePointersArrayArg,
6347 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6348 auto &RT = CGF.CGM.getOpenMPRuntime();
6349 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6353 // If we need device pointer privatization, we need to emit the body of the
6354 // region with no privatization in the 'else' branch of the conditional.
6355 // Otherwise, we don't have to do anything.
6356 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6357 PrePostActionTy &) {
6358 if (!Info.CaptureDeviceAddrMap.empty()) {
6359 CodeGen.setAction(NoPrivAction);
6364 // We don't have to do anything to close the region if the if clause evaluates
6366 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6369 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
6371 RegionCodeGenTy RCG(BeginThenGen);
6375 // If we don't require privatization of device pointers, we emit the body in
6376 // between the runtime calls. This avoids duplicating the body code.
6377 if (Info.CaptureDeviceAddrMap.empty()) {
6378 CodeGen.setAction(NoPrivAction);
6383 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
6385 RegionCodeGenTy RCG(EndThenGen);
6390 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
6391 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6392 const Expr *Device) {
6393 if (!CGF.HaveInsertPoint())
6396 assert((isa<OMPTargetEnterDataDirective>(D) ||
6397 isa<OMPTargetExitDataDirective>(D) ||
6398 isa<OMPTargetUpdateDirective>(D)) &&
6399 "Expecting either target enter, exit data, or update directives.");
6401 // Generate the code for the opening of the data environment.
6402 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6403 // Fill up the arrays with all the mapped variables.
6404 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6405 MappableExprsHandler::MapValuesArrayTy Pointers;
6406 MappableExprsHandler::MapValuesArrayTy Sizes;
6407 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6409 // Get map clause information.
6410 MappableExprsHandler MEHandler(D, CGF);
6411 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
6413 // Fill up the arrays and create the arguments.
6414 TargetDataInfo Info;
6415 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6416 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6417 Info.PointersArray, Info.SizesArray,
6418 Info.MapTypesArray, Info);
6420 // Emit device ID if any.
6421 llvm::Value *DeviceID = nullptr;
6423 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6424 CGF.Int32Ty, /*isSigned=*/true);
6426 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6428 // Emit the number of elements in the offloading arrays.
6429 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6431 llvm::Value *OffloadingArgs[] = {
6432 DeviceID, PointerNum, Info.BasePointersArray,
6433 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
6435 auto &RT = CGF.CGM.getOpenMPRuntime();
6436 // Select the right runtime function call for each expected standalone
6438 OpenMPRTLFunction RTLFn;
6439 switch (D.getDirectiveKind()) {
6441 llvm_unreachable("Unexpected standalone target data directive.");
6443 case OMPD_target_enter_data:
6444 RTLFn = OMPRTL__tgt_target_data_begin;
6446 case OMPD_target_exit_data:
6447 RTLFn = OMPRTL__tgt_target_data_end;
6449 case OMPD_target_update:
6450 RTLFn = OMPRTL__tgt_target_data_update;
6453 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
6456 // In the event we get an if clause, we don't have to take any action on the
6458 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6461 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6463 RegionCodeGenTy ThenGenRCG(ThenGen);
6469 /// Kind of parameter in a function with 'declare simd' directive.
6470 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6471 /// Attribute set of the parameter.
6472 struct ParamAttrTy {
6473 ParamKindTy Kind = Vector;
6474 llvm::APSInt StrideOrArg;
6475 llvm::APSInt Alignment;
6479 static unsigned evaluateCDTSize(const FunctionDecl *FD,
6480 ArrayRef<ParamAttrTy> ParamAttrs) {
6481 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6482 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6483 // of that clause. The VLEN value must be power of 2.
6484 // In other case the notion of the function`s "characteristic data type" (CDT)
6485 // is used to compute the vector length.
6486 // CDT is defined in the following order:
6487 // a) For non-void function, the CDT is the return type.
6488 // b) If the function has any non-uniform, non-linear parameters, then the
6489 // CDT is the type of the first such parameter.
6490 // c) If the CDT determined by a) or b) above is struct, union, or class
6491 // type which is pass-by-value (except for the type that maps to the
6492 // built-in complex data type), the characteristic data type is int.
6493 // d) If none of the above three cases is applicable, the CDT is int.
6494 // The VLEN is then determined based on the CDT and the size of vector
6495 // register of that ISA for which current vector version is generated. The
6496 // VLEN is computed using the formula below:
6497 // VLEN = sizeof(vector_register) / sizeof(CDT),
6498 // where vector register size specified in section 3.2.1 Registers and the
6499 // Stack Frame of original AMD64 ABI document.
6500 QualType RetType = FD->getReturnType();
6501 if (RetType.isNull())
6503 ASTContext &C = FD->getASTContext();
6505 if (!RetType.isNull() && !RetType->isVoidType())
6508 unsigned Offset = 0;
6509 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6510 if (ParamAttrs[Offset].Kind == Vector)
6511 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6515 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6516 if (ParamAttrs[I + Offset].Kind == Vector) {
6517 CDT = FD->getParamDecl(I)->getType();
6525 CDT = CDT->getCanonicalTypeUnqualified();
6526 if (CDT->isRecordType() || CDT->isUnionType())
6528 return C.getTypeSize(CDT);
6532 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
6533 const llvm::APSInt &VLENVal,
6534 ArrayRef<ParamAttrTy> ParamAttrs,
6535 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6538 unsigned VecRegSize;
6540 ISADataTy ISAData[] = {
6554 llvm::SmallVector<char, 2> Masked;
6556 case OMPDeclareSimdDeclAttr::BS_Undefined:
6557 Masked.push_back('N');
6558 Masked.push_back('M');
6560 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6561 Masked.push_back('N');
6563 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6564 Masked.push_back('M');
6567 for (auto Mask : Masked) {
6568 for (auto &Data : ISAData) {
6569 SmallString<256> Buffer;
6570 llvm::raw_svector_ostream Out(Buffer);
6571 Out << "_ZGV" << Data.ISA << Mask;
6573 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6574 evaluateCDTSize(FD, ParamAttrs));
6577 for (auto &ParamAttr : ParamAttrs) {
6578 switch (ParamAttr.Kind){
6579 case LinearWithVarStride:
6580 Out << 's' << ParamAttr.StrideOrArg;
6584 if (!!ParamAttr.StrideOrArg)
6585 Out << ParamAttr.StrideOrArg;
6594 if (!!ParamAttr.Alignment)
6595 Out << 'a' << ParamAttr.Alignment;
6597 Out << '_' << Fn->getName();
6598 Fn->addFnAttr(Out.str());
6603 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6604 llvm::Function *Fn) {
6605 ASTContext &C = CGM.getContext();
6606 FD = FD->getCanonicalDecl();
6607 // Map params to their positions in function decl.
6608 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6609 if (isa<CXXMethodDecl>(FD))
6610 ParamPositions.insert({FD, 0});
6611 unsigned ParamPos = ParamPositions.size();
6612 for (auto *P : FD->parameters()) {
6613 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6616 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6617 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6618 // Mark uniform parameters.
6619 for (auto *E : Attr->uniforms()) {
6620 E = E->IgnoreParenImpCasts();
6622 if (isa<CXXThisExpr>(E))
6623 Pos = ParamPositions[FD];
6625 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6626 ->getCanonicalDecl();
6627 Pos = ParamPositions[PVD];
6629 ParamAttrs[Pos].Kind = Uniform;
6631 // Get alignment info.
6632 auto NI = Attr->alignments_begin();
6633 for (auto *E : Attr->aligneds()) {
6634 E = E->IgnoreParenImpCasts();
6637 if (isa<CXXThisExpr>(E)) {
6638 Pos = ParamPositions[FD];
6639 ParmTy = E->getType();
6641 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6642 ->getCanonicalDecl();
6643 Pos = ParamPositions[PVD];
6644 ParmTy = PVD->getType();
6646 ParamAttrs[Pos].Alignment =
6647 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6648 : llvm::APSInt::getUnsigned(
6649 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6653 // Mark linear parameters.
6654 auto SI = Attr->steps_begin();
6655 auto MI = Attr->modifiers_begin();
6656 for (auto *E : Attr->linears()) {
6657 E = E->IgnoreParenImpCasts();
6659 if (isa<CXXThisExpr>(E))
6660 Pos = ParamPositions[FD];
6662 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6663 ->getCanonicalDecl();
6664 Pos = ParamPositions[PVD];
6666 auto &ParamAttr = ParamAttrs[Pos];
6667 ParamAttr.Kind = Linear;
6669 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6670 Expr::SE_AllowSideEffects)) {
6671 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6672 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6673 ParamAttr.Kind = LinearWithVarStride;
6674 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6675 ParamPositions[StridePVD->getCanonicalDecl()]);
6683 llvm::APSInt VLENVal;
6684 if (const Expr *VLEN = Attr->getSimdlen())
6685 VLENVal = VLEN->EvaluateKnownConstInt(C);
6686 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6687 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6688 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6689 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6694 /// Cleanup action for doacross support.
6695 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6697 static const int DoacrossFinArgs = 2;
6701 llvm::Value *Args[DoacrossFinArgs];
6704 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6706 assert(CallArgs.size() == DoacrossFinArgs);
6707 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6709 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6710 if (!CGF.HaveInsertPoint())
6712 CGF.EmitRuntimeCall(RTLFn, Args);
6717 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6718 const OMPLoopDirective &D) {
6719 if (!CGF.HaveInsertPoint())
6722 ASTContext &C = CGM.getContext();
6723 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6725 if (KmpDimTy.isNull()) {
6726 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6727 // kmp_int64 lo; // lower
6728 // kmp_int64 up; // upper
6729 // kmp_int64 st; // stride
6731 RD = C.buildImplicitRecord("kmp_dim");
6732 RD->startDefinition();
6733 addFieldToRecordDecl(C, RD, Int64Ty);
6734 addFieldToRecordDecl(C, RD, Int64Ty);
6735 addFieldToRecordDecl(C, RD, Int64Ty);
6736 RD->completeDefinition();
6737 KmpDimTy = C.getRecordType(RD);
6739 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6741 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6742 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6743 enum { LowerFD = 0, UpperFD, StrideFD };
6744 // Fill dims with data.
6745 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6746 // dims.upper = num_iterations;
6748 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6749 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6750 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6751 Int64Ty, D.getNumIterations()->getExprLoc());
6752 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6755 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6756 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6759 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6760 // kmp_int32 num_dims, struct kmp_dim * dims);
6761 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6762 getThreadID(CGF, D.getLocStart()),
6763 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6764 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6765 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6767 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6768 CGF.EmitRuntimeCall(RTLFn, Args);
6769 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6770 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6771 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6772 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6773 llvm::makeArrayRef(FiniArgs));
6776 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6777 const OMPDependClause *C) {
6779 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6780 const Expr *CounterVal = C->getCounterValue();
6782 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6783 CounterVal->getType(), Int64Ty,
6784 CounterVal->getExprLoc());
6785 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6786 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6787 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6788 getThreadID(CGF, C->getLocStart()),
6789 CntAddr.getPointer()};
6791 if (C->getDependencyKind() == OMPC_DEPEND_source)
6792 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6794 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6795 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6797 CGF.EmitRuntimeCall(RTLFn, Args);