clang 17.0.0git
CGOpenMPRuntime.cpp
Go to the documentation of this file.
1//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGOpenMPRuntime.h"
14#include "CGCXXABI.h"
15#include "CGCleanup.h"
16#include "CGRecordLayout.h"
17#include "CodeGenFunction.h"
18#include "TargetInfo.h"
19#include "clang/AST/APValue.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/SetOperations.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/Bitcode/BitcodeReader.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DerivedTypes.h"
37#include "llvm/IR/GlobalValue.h"
38#include "llvm/IR/InstrTypes.h"
39#include "llvm/IR/Value.h"
40#include "llvm/Support/AtomicOrdering.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/raw_ostream.h"
43#include <cassert>
44#include <numeric>
45#include <optional>
46
47using namespace clang;
48using namespace CodeGen;
49using namespace llvm::omp;
50
51namespace {
52/// Base class for handling code generation inside OpenMP regions.
53class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
54public:
55 /// Kinds of OpenMP regions used in codegen.
56 enum CGOpenMPRegionKind {
57 /// Region with outlined function for standalone 'parallel'
58 /// directive.
59 ParallelOutlinedRegion,
60 /// Region with outlined function for standalone 'task' directive.
61 TaskOutlinedRegion,
62 /// Region for constructs that do not require function outlining,
63 /// like 'for', 'sections', 'atomic' etc. directives.
64 InlinedRegion,
65 /// Region with outlined function for standalone 'target' directive.
66 TargetRegion,
67 };
68
69 CGOpenMPRegionInfo(const CapturedStmt &CS,
70 const CGOpenMPRegionKind RegionKind,
71 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
72 bool HasCancel)
73 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
74 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
75
76 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
77 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
78 bool HasCancel)
79 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
80 Kind(Kind), HasCancel(HasCancel) {}
81
82 /// Get a variable or parameter for storing global thread id
83 /// inside OpenMP construct.
84 virtual const VarDecl *getThreadIDVariable() const = 0;
85
86 /// Emit the captured statement body.
87 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
88
89 /// Get an LValue for the current ThreadID variable.
90 /// \return LValue for thread id variable. This LValue always has type int32*.
91 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
92
93 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
94
95 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
96
97 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
98
99 bool hasCancel() const { return HasCancel; }
100
101 static bool classof(const CGCapturedStmtInfo *Info) {
102 return Info->getKind() == CR_OpenMP;
103 }
104
105 ~CGOpenMPRegionInfo() override = default;
106
107protected:
108 CGOpenMPRegionKind RegionKind;
109 RegionCodeGenTy CodeGen;
111 bool HasCancel;
112};
113
114/// API for captured statement code generation in OpenMP constructs.
115class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
116public:
117 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
118 const RegionCodeGenTy &CodeGen,
119 OpenMPDirectiveKind Kind, bool HasCancel,
120 StringRef HelperName)
121 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
122 HasCancel),
123 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
124 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
125 }
126
127 /// Get a variable or parameter for storing global thread id
128 /// inside OpenMP construct.
129 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
130
131 /// Get the name of the capture helper.
132 StringRef getHelperName() const override { return HelperName; }
133
134 static bool classof(const CGCapturedStmtInfo *Info) {
135 return CGOpenMPRegionInfo::classof(Info) &&
136 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
137 ParallelOutlinedRegion;
138 }
139
140private:
141 /// A variable or parameter storing global thread id for OpenMP
142 /// constructs.
143 const VarDecl *ThreadIDVar;
144 StringRef HelperName;
145};
146
147/// API for captured statement code generation in OpenMP constructs.
148class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
149public:
150 class UntiedTaskActionTy final : public PrePostActionTy {
151 bool Untied;
152 const VarDecl *PartIDVar;
153 const RegionCodeGenTy UntiedCodeGen;
154 llvm::SwitchInst *UntiedSwitch = nullptr;
155
156 public:
157 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
158 const RegionCodeGenTy &UntiedCodeGen)
159 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
160 void Enter(CodeGenFunction &CGF) override {
161 if (Untied) {
162 // Emit task switching point.
163 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 llvm::Value *Res =
167 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
168 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
169 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
170 CGF.EmitBlock(DoneBB);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
174 CGF.Builder.GetInsertBlock());
175 emitUntiedSwitch(CGF);
176 }
177 }
178 void emitUntiedSwitch(CodeGenFunction &CGF) const {
179 if (Untied) {
180 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
181 CGF.GetAddrOfLocalVar(PartIDVar),
182 PartIDVar->getType()->castAs<PointerType>());
183 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
184 PartIdLVal);
185 UntiedCodeGen(CGF);
186 CodeGenFunction::JumpDest CurPoint =
187 CGF.getJumpDestInCurrentScope(".untied.next.");
189 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
190 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
191 CGF.Builder.GetInsertBlock());
192 CGF.EmitBranchThroughCleanup(CurPoint);
193 CGF.EmitBlock(CurPoint.getBlock());
194 }
195 }
196 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
197 };
198 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
199 const VarDecl *ThreadIDVar,
200 const RegionCodeGenTy &CodeGen,
201 OpenMPDirectiveKind Kind, bool HasCancel,
202 const UntiedTaskActionTy &Action)
203 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
204 ThreadIDVar(ThreadIDVar), Action(Action) {
205 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
206 }
207
208 /// Get a variable or parameter for storing global thread id
209 /// inside OpenMP construct.
210 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
211
212 /// Get an LValue for the current ThreadID variable.
213 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
214
215 /// Get the name of the capture helper.
216 StringRef getHelperName() const override { return ".omp_outlined."; }
217
218 void emitUntiedSwitch(CodeGenFunction &CGF) override {
219 Action.emitUntiedSwitch(CGF);
220 }
221
222 static bool classof(const CGCapturedStmtInfo *Info) {
223 return CGOpenMPRegionInfo::classof(Info) &&
224 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
225 TaskOutlinedRegion;
226 }
227
228private:
229 /// A variable or parameter storing global thread id for OpenMP
230 /// constructs.
231 const VarDecl *ThreadIDVar;
232 /// Action for emitting code for untied tasks.
233 const UntiedTaskActionTy &Action;
234};
235
236/// API for inlined captured statement code generation in OpenMP
237/// constructs.
238class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
239public:
240 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
241 const RegionCodeGenTy &CodeGen,
242 OpenMPDirectiveKind Kind, bool HasCancel)
243 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
244 OldCSI(OldCSI),
245 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
246
247 // Retrieve the value of the context parameter.
248 llvm::Value *getContextValue() const override {
249 if (OuterRegionInfo)
250 return OuterRegionInfo->getContextValue();
251 llvm_unreachable("No context value for inlined OpenMP region");
252 }
253
254 void setContextValue(llvm::Value *V) override {
255 if (OuterRegionInfo) {
256 OuterRegionInfo->setContextValue(V);
257 return;
258 }
259 llvm_unreachable("No context value for inlined OpenMP region");
260 }
261
262 /// Lookup the captured field decl for a variable.
263 const FieldDecl *lookup(const VarDecl *VD) const override {
264 if (OuterRegionInfo)
265 return OuterRegionInfo->lookup(VD);
266 // If there is no outer outlined region,no need to lookup in a list of
267 // captured variables, we can use the original one.
268 return nullptr;
269 }
270
271 FieldDecl *getThisFieldDecl() const override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThisFieldDecl();
274 return nullptr;
275 }
276
277 /// Get a variable or parameter for storing global thread id
278 /// inside OpenMP construct.
279 const VarDecl *getThreadIDVariable() const override {
280 if (OuterRegionInfo)
281 return OuterRegionInfo->getThreadIDVariable();
282 return nullptr;
283 }
284
285 /// Get an LValue for the current ThreadID variable.
286 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
287 if (OuterRegionInfo)
288 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
289 llvm_unreachable("No LValue for inlined OpenMP construct");
290 }
291
292 /// Get the name of the capture helper.
293 StringRef getHelperName() const override {
294 if (auto *OuterRegionInfo = getOldCSI())
295 return OuterRegionInfo->getHelperName();
296 llvm_unreachable("No helper name for inlined OpenMP construct");
297 }
298
299 void emitUntiedSwitch(CodeGenFunction &CGF) override {
300 if (OuterRegionInfo)
301 OuterRegionInfo->emitUntiedSwitch(CGF);
302 }
303
304 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
305
306 static bool classof(const CGCapturedStmtInfo *Info) {
307 return CGOpenMPRegionInfo::classof(Info) &&
308 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
309 }
310
311 ~CGOpenMPInlinedRegionInfo() override = default;
312
313private:
314 /// CodeGen info about outer OpenMP region.
315 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
316 CGOpenMPRegionInfo *OuterRegionInfo;
317};
318
319/// API for captured statement code generation in OpenMP target
320/// constructs. For this captures, implicit parameters are used instead of the
321/// captured fields. The name of the target region has to be unique in a given
322/// application so it is provided by the client, because only the client has
323/// the information to generate that.
324class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
325public:
326 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
327 const RegionCodeGenTy &CodeGen, StringRef HelperName)
328 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
329 /*HasCancel=*/false),
330 HelperName(HelperName) {}
331
332 /// This is unused for target regions because each starts executing
333 /// with a single thread.
334 const VarDecl *getThreadIDVariable() const override { return nullptr; }
335
336 /// Get the name of the capture helper.
337 StringRef getHelperName() const override { return HelperName; }
338
339 static bool classof(const CGCapturedStmtInfo *Info) {
340 return CGOpenMPRegionInfo::classof(Info) &&
341 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
342 }
343
344private:
345 StringRef HelperName;
346};
347
348static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
349 llvm_unreachable("No codegen for expressions");
350}
351/// API for generation of expressions captured in a innermost OpenMP
352/// region.
353class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
354public:
355 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
356 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
357 OMPD_unknown,
358 /*HasCancel=*/false),
359 PrivScope(CGF) {
360 // Make sure the globals captured in the provided statement are local by
361 // using the privatization logic. We assume the same variable is not
362 // captured more than once.
363 for (const auto &C : CS.captures()) {
364 if (!C.capturesVariable() && !C.capturesVariableByCopy())
365 continue;
366
367 const VarDecl *VD = C.getCapturedVar();
368 if (VD->isLocalVarDeclOrParm())
369 continue;
370
371 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
372 /*RefersToEnclosingVariableOrCapture=*/false,
374 C.getLocation());
375 PrivScope.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF));
376 }
377 (void)PrivScope.Privatize();
378 }
379
380 /// Lookup the captured field decl for a variable.
381 const FieldDecl *lookup(const VarDecl *VD) const override {
382 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
383 return FD;
384 return nullptr;
385 }
386
387 /// Emit the captured statement body.
388 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
389 llvm_unreachable("No body for expressions");
390 }
391
392 /// Get a variable or parameter for storing global thread id
393 /// inside OpenMP construct.
394 const VarDecl *getThreadIDVariable() const override {
395 llvm_unreachable("No thread id for expressions");
396 }
397
398 /// Get the name of the capture helper.
399 StringRef getHelperName() const override {
400 llvm_unreachable("No helper name for expressions");
401 }
402
403 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
404
405private:
406 /// Private scope to capture global variables.
407 CodeGenFunction::OMPPrivateScope PrivScope;
408};
409
410/// RAII for emitting code of OpenMP constructs.
411class InlinedOpenMPRegionRAII {
412 CodeGenFunction &CGF;
413 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
414 FieldDecl *LambdaThisCaptureField = nullptr;
415 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
416 bool NoInheritance = false;
417
418public:
419 /// Constructs region for combined constructs.
420 /// \param CodeGen Code generation sequence for combined directives. Includes
421 /// a list of functions used for code generation of implicitly inlined
422 /// regions.
423 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
424 OpenMPDirectiveKind Kind, bool HasCancel,
425 bool NoInheritance = true)
426 : CGF(CGF), NoInheritance(NoInheritance) {
427 // Start emission for the construct.
428 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
429 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
430 if (NoInheritance) {
431 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
432 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
433 CGF.LambdaThisCaptureField = nullptr;
434 BlockInfo = CGF.BlockInfo;
435 CGF.BlockInfo = nullptr;
436 }
437 }
438
439 ~InlinedOpenMPRegionRAII() {
440 // Restore original CapturedStmtInfo only if we're done with code emission.
441 auto *OldCSI =
442 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
443 delete CGF.CapturedStmtInfo;
444 CGF.CapturedStmtInfo = OldCSI;
445 if (NoInheritance) {
446 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
447 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
448 CGF.BlockInfo = BlockInfo;
449 }
450 }
451};
452
453/// Values for bit flags used in the ident_t to describe the fields.
454/// All enumeric elements are named and described in accordance with the code
455/// from https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h
456enum OpenMPLocationFlags : unsigned {
457 /// Use trampoline for internal microtask.
458 OMP_IDENT_IMD = 0x01,
459 /// Use c-style ident structure.
460 OMP_IDENT_KMPC = 0x02,
461 /// Atomic reduction option for kmpc_reduce.
462 OMP_ATOMIC_REDUCE = 0x10,
463 /// Explicit 'barrier' directive.
464 OMP_IDENT_BARRIER_EXPL = 0x20,
465 /// Implicit barrier in code.
466 OMP_IDENT_BARRIER_IMPL = 0x40,
467 /// Implicit barrier in 'for' directive.
468 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
469 /// Implicit barrier in 'sections' directive.
470 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
471 /// Implicit barrier in 'single' directive.
472 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
473 /// Call of __kmp_for_static_init for static loop.
474 OMP_IDENT_WORK_LOOP = 0x200,
475 /// Call of __kmp_for_static_init for sections.
476 OMP_IDENT_WORK_SECTIONS = 0x400,
477 /// Call of __kmp_for_static_init for distribute.
478 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
479 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
480};
481
482namespace {
484/// Values for bit flags for marking which requires clauses have been used.
485enum OpenMPOffloadingRequiresDirFlags : int64_t {
486 /// flag undefined.
487 OMP_REQ_UNDEFINED = 0x000,
488 /// no requires clause present.
489 OMP_REQ_NONE = 0x001,
490 /// reverse_offload clause.
491 OMP_REQ_REVERSE_OFFLOAD = 0x002,
492 /// unified_address clause.
493 OMP_REQ_UNIFIED_ADDRESS = 0x004,
494 /// unified_shared_memory clause.
495 OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
496 /// dynamic_allocators clause.
497 OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
498 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
499};
500
501} // anonymous namespace
502
503/// Describes ident structure that describes a source location.
504/// All descriptions are taken from
505/// https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h
506/// Original structure:
507/// typedef struct ident {
508/// kmp_int32 reserved_1; /**< might be used in Fortran;
509/// see above */
510/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
511/// KMP_IDENT_KMPC identifies this union
512/// member */
513/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
514/// see above */
515///#if USE_ITT_BUILD
516/// /* but currently used for storing
517/// region-specific ITT */
518/// /* contextual information. */
519///#endif /* USE_ITT_BUILD */
520/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
521/// C++ */
522/// char const *psource; /**< String describing the source location.
523/// The string is composed of semi-colon separated
524// fields which describe the source file,
525/// the function and a pair of line numbers that
526/// delimit the construct.
527/// */
528/// } ident_t;
529enum IdentFieldIndex {
530 /// might be used in Fortran
531 IdentField_Reserved_1,
532 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
533 IdentField_Flags,
534 /// Not really used in Fortran any more
535 IdentField_Reserved_2,
536 /// Source[4] in Fortran, do not use for C++
537 IdentField_Reserved_3,
538 /// String describing the source location. The string is composed of
539 /// semi-colon separated fields which describe the source file, the function
540 /// and a pair of line numbers that delimit the construct.
541 IdentField_PSource
542};
543
544/// Schedule types for 'omp for' loops (these enumerators are taken from
545/// the enum sched_type in kmp.h).
546enum OpenMPSchedType {
547 /// Lower bound for default (unordered) versions.
548 OMP_sch_lower = 32,
549 OMP_sch_static_chunked = 33,
550 OMP_sch_static = 34,
551 OMP_sch_dynamic_chunked = 35,
552 OMP_sch_guided_chunked = 36,
553 OMP_sch_runtime = 37,
554 OMP_sch_auto = 38,
555 /// static with chunk adjustment (e.g., simd)
556 OMP_sch_static_balanced_chunked = 45,
557 /// Lower bound for 'ordered' versions.
558 OMP_ord_lower = 64,
559 OMP_ord_static_chunked = 65,
560 OMP_ord_static = 66,
561 OMP_ord_dynamic_chunked = 67,
562 OMP_ord_guided_chunked = 68,
563 OMP_ord_runtime = 69,
564 OMP_ord_auto = 70,
565 OMP_sch_default = OMP_sch_static,
566 /// dist_schedule types
567 OMP_dist_sch_static_chunked = 91,
568 OMP_dist_sch_static = 92,
569 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
570 /// Set if the monotonic schedule modifier was present.
571 OMP_sch_modifier_monotonic = (1 << 29),
572 /// Set if the nonmonotonic schedule modifier was present.
573 OMP_sch_modifier_nonmonotonic = (1 << 30),
574};
575
576/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
577/// region.
578class CleanupTy final : public EHScopeStack::Cleanup {
579 PrePostActionTy *Action;
580
581public:
582 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
583 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
584 if (!CGF.HaveInsertPoint())
585 return;
586 Action->Exit(CGF);
587 }
588};
589
590} // anonymous namespace
591
594 if (PrePostAction) {
595 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
596 Callback(CodeGen, CGF, *PrePostAction);
597 } else {
598 PrePostActionTy Action;
599 Callback(CodeGen, CGF, Action);
600 }
601}
602
603/// Check if the combiner is a call to UDR combiner and if it is so return the
604/// UDR decl used for reduction.
605static const OMPDeclareReductionDecl *
606getReductionInit(const Expr *ReductionOp) {
607 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
608 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
609 if (const auto *DRE =
610 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
611 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
612 return DRD;
613 return nullptr;
614}
615
617 const OMPDeclareReductionDecl *DRD,
618 const Expr *InitOp,
619 Address Private, Address Original,
620 QualType Ty) {
621 if (DRD->getInitializer()) {
622 std::pair<llvm::Function *, llvm::Function *> Reduction =
624 const auto *CE = cast<CallExpr>(InitOp);
625 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
626 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
627 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
628 const auto *LHSDRE =
629 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
630 const auto *RHSDRE =
631 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
632 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
633 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), Private);
634 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), Original);
635 (void)PrivateScope.Privatize();
636 RValue Func = RValue::get(Reduction.second);
637 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
638 CGF.EmitIgnoredExpr(InitOp);
639 } else {
640 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
641 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
642 auto *GV = new llvm::GlobalVariable(
643 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
644 llvm::GlobalValue::PrivateLinkage, Init, Name);
645 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
646 RValue InitRVal;
647 switch (CGF.getEvaluationKind(Ty)) {
648 case TEK_Scalar:
649 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
650 break;
651 case TEK_Complex:
652 InitRVal =
654 break;
655 case TEK_Aggregate: {
656 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_LValue);
657 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, LV);
658 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
659 /*IsInitializer=*/false);
660 return;
661 }
662 }
663 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_PRValue);
664 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
665 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
666 /*IsInitializer=*/false);
667 }
668}
669
670/// Emit initialization of arrays of complex types.
671/// \param DestAddr Address of the array.
672/// \param Type Type of array.
673/// \param Init Initial expression of array.
674/// \param SrcAddr Address of the original array.
676 QualType Type, bool EmitDeclareReductionInit,
677 const Expr *Init,
678 const OMPDeclareReductionDecl *DRD,
679 Address SrcAddr = Address::invalid()) {
680 // Perform element-by-element initialization.
681 QualType ElementTy;
682
683 // Drill down to the base element type on both arrays.
684 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
685 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
686 if (DRD)
687 SrcAddr =
688 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
689
690 llvm::Value *SrcBegin = nullptr;
691 if (DRD)
692 SrcBegin = SrcAddr.getPointer();
693 llvm::Value *DestBegin = DestAddr.getPointer();
694 // Cast from pointer to array type to pointer to single element.
695 llvm::Value *DestEnd =
696 CGF.Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements);
697 // The basic structure here is a while-do loop.
698 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
699 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
700 llvm::Value *IsEmpty =
701 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
702 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
703
704 // Enter the loop body, making that address the current address.
705 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
706 CGF.EmitBlock(BodyBB);
707
708 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
709
710 llvm::PHINode *SrcElementPHI = nullptr;
711 Address SrcElementCurrent = Address::invalid();
712 if (DRD) {
713 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
714 "omp.arraycpy.srcElementPast");
715 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
716 SrcElementCurrent =
717 Address(SrcElementPHI, SrcAddr.getElementType(),
718 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
719 }
720 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
721 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
722 DestElementPHI->addIncoming(DestBegin, EntryBB);
723 Address DestElementCurrent =
724 Address(DestElementPHI, DestAddr.getElementType(),
725 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
726
727 // Emit copy.
728 {
729 CodeGenFunction::RunCleanupsScope InitScope(CGF);
730 if (EmitDeclareReductionInit) {
731 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
732 SrcElementCurrent, ElementTy);
733 } else
734 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
735 /*IsInitializer=*/false);
736 }
737
738 if (DRD) {
739 // Shift the address forward by one element.
740 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
741 SrcAddr.getElementType(), SrcElementPHI, /*Idx0=*/1,
742 "omp.arraycpy.dest.element");
743 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
744 }
745
746 // Shift the address forward by one element.
747 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
748 DestAddr.getElementType(), DestElementPHI, /*Idx0=*/1,
749 "omp.arraycpy.dest.element");
750 // Check whether we've reached the end.
751 llvm::Value *Done =
752 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
753 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
754 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
755
756 // Done.
757 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
758}
759
760LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
761 return CGF.EmitOMPSharedLValue(E);
762}
763
764LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
765 const Expr *E) {
766 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
767 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
768 return LValue();
769}
770
771void ReductionCodeGen::emitAggregateInitialization(
772 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr,
773 const OMPDeclareReductionDecl *DRD) {
774 // Emit VarDecl with copy init for arrays.
775 // Get the address of the original variable captured in current
776 // captured region.
777 const auto *PrivateVD =
778 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
779 bool EmitDeclareReductionInit =
780 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
781 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
782 EmitDeclareReductionInit,
783 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
784 : PrivateVD->getInit(),
785 DRD, SharedAddr);
786}
787
790 ArrayRef<const Expr *> Privates,
791 ArrayRef<const Expr *> ReductionOps) {
792 ClausesData.reserve(Shareds.size());
793 SharedAddresses.reserve(Shareds.size());
794 Sizes.reserve(Shareds.size());
795 BaseDecls.reserve(Shareds.size());
796 const auto *IOrig = Origs.begin();
797 const auto *IPriv = Privates.begin();
798 const auto *IRed = ReductionOps.begin();
799 for (const Expr *Ref : Shareds) {
800 ClausesData.emplace_back(Ref, *IOrig, *IPriv, *IRed);
801 std::advance(IOrig, 1);
802 std::advance(IPriv, 1);
803 std::advance(IRed, 1);
804 }
805}
806
808 assert(SharedAddresses.size() == N && OrigAddresses.size() == N &&
809 "Number of generated lvalues must be exactly N.");
810 LValue First = emitSharedLValue(CGF, ClausesData[N].Shared);
811 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Shared);
812 SharedAddresses.emplace_back(First, Second);
813 if (ClausesData[N].Shared == ClausesData[N].Ref) {
814 OrigAddresses.emplace_back(First, Second);
815 } else {
816 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
817 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
818 OrigAddresses.emplace_back(First, Second);
819 }
820}
821
823 QualType PrivateType = getPrivateType(N);
824 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
825 if (!PrivateType->isVariablyModifiedType()) {
826 Sizes.emplace_back(
827 CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()),
828 nullptr);
829 return;
830 }
831 llvm::Value *Size;
832 llvm::Value *SizeInChars;
833 auto *ElemType = OrigAddresses[N].first.getAddress(CGF).getElementType();
834 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
835 if (AsArraySection) {
836 Size = CGF.Builder.CreatePtrDiff(ElemType,
837 OrigAddresses[N].second.getPointer(CGF),
838 OrigAddresses[N].first.getPointer(CGF));
839 Size = CGF.Builder.CreateNUWAdd(
840 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
841 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
842 } else {
843 SizeInChars =
844 CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType());
845 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
846 }
847 Sizes.emplace_back(SizeInChars, Size);
849 CGF,
850 cast<OpaqueValueExpr>(
851 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
852 RValue::get(Size));
853 CGF.EmitVariablyModifiedType(PrivateType);
854}
855
857 llvm::Value *Size) {
858 QualType PrivateType = getPrivateType(N);
859 if (!PrivateType->isVariablyModifiedType()) {
860 assert(!Size && !Sizes[N].second &&
861 "Size should be nullptr for non-variably modified reduction "
862 "items.");
863 return;
864 }
866 CGF,
867 cast<OpaqueValueExpr>(
868 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
869 RValue::get(Size));
870 CGF.EmitVariablyModifiedType(PrivateType);
871}
872
874 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, Address SharedAddr,
875 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
876 assert(SharedAddresses.size() > N && "No variable was generated");
877 const auto *PrivateVD =
878 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
879 const OMPDeclareReductionDecl *DRD =
880 getReductionInit(ClausesData[N].ReductionOp);
881 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
882 if (DRD && DRD->getInitializer())
883 (void)DefaultInit(CGF);
884 emitAggregateInitialization(CGF, N, PrivateAddr, SharedAddr, DRD);
885 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
886 (void)DefaultInit(CGF);
887 QualType SharedType = SharedAddresses[N].first.getType();
888 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
889 PrivateAddr, SharedAddr, SharedType);
890 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
891 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
892 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
893 PrivateVD->getType().getQualifiers(),
894 /*IsInitializer=*/false);
895 }
896}
897
899 QualType PrivateType = getPrivateType(N);
900 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
901 return DTorKind != QualType::DK_none;
902}
903
905 Address PrivateAddr) {
906 QualType PrivateType = getPrivateType(N);
907 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
908 if (needCleanups(N)) {
909 PrivateAddr = CGF.Builder.CreateElementBitCast(
910 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
911 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
912 }
913}
914
916 LValue BaseLV) {
917 BaseTy = BaseTy.getNonReferenceType();
918 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
919 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
920 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
921 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(CGF), PtrTy);
922 } else {
923 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(CGF), BaseTy);
924 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
925 }
926 BaseTy = BaseTy->getPointeeType();
927 }
928 return CGF.MakeAddrLValue(
930 CGF.ConvertTypeForMem(ElTy)),
931 BaseLV.getType(), BaseLV.getBaseInfo(),
932 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
933}
934
936 Address OriginalBaseAddress, llvm::Value *Addr) {
938 Address TopTmp = Address::invalid();
939 Address MostTopTmp = Address::invalid();
940 BaseTy = BaseTy.getNonReferenceType();
941 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
942 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
943 Tmp = CGF.CreateMemTemp(BaseTy);
944 if (TopTmp.isValid())
945 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
946 else
947 MostTopTmp = Tmp;
948 TopTmp = Tmp;
949 BaseTy = BaseTy->getPointeeType();
950 }
951
952 if (Tmp.isValid()) {
954 Addr, Tmp.getElementType());
955 CGF.Builder.CreateStore(Addr, Tmp);
956 return MostTopTmp;
957 }
958
960 Addr, OriginalBaseAddress.getType());
961 return OriginalBaseAddress.withPointer(Addr, NotKnownNonNull);
962}
963
964static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
965 const VarDecl *OrigVD = nullptr;
966 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
967 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
968 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
969 Base = TempOASE->getBase()->IgnoreParenImpCasts();
970 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
971 Base = TempASE->getBase()->IgnoreParenImpCasts();
972 DE = cast<DeclRefExpr>(Base);
973 OrigVD = cast<VarDecl>(DE->getDecl());
974 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
975 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
976 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
977 Base = TempASE->getBase()->IgnoreParenImpCasts();
978 DE = cast<DeclRefExpr>(Base);
979 OrigVD = cast<VarDecl>(DE->getDecl());
980 }
981 return OrigVD;
982}
983
985 Address PrivateAddr) {
986 const DeclRefExpr *DE;
987 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
988 BaseDecls.emplace_back(OrigVD);
989 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
990 LValue BaseLValue =
991 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
992 OriginalBaseLValue);
993 Address SharedAddr = SharedAddresses[N].first.getAddress(CGF);
994 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
995 SharedAddr.getElementType(), BaseLValue.getPointer(CGF),
996 SharedAddr.getPointer());
997 llvm::Value *PrivatePointer =
999 PrivateAddr.getPointer(), SharedAddr.getType());
1000 llvm::Value *Ptr = CGF.Builder.CreateGEP(
1001 SharedAddr.getElementType(), PrivatePointer, Adjustment);
1002 return castToBase(CGF, OrigVD->getType(),
1003 SharedAddresses[N].first.getType(),
1004 OriginalBaseLValue.getAddress(CGF), Ptr);
1005 }
1006 BaseDecls.emplace_back(
1007 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1008 return PrivateAddr;
1009}
1010
1012 const OMPDeclareReductionDecl *DRD =
1013 getReductionInit(ClausesData[N].ReductionOp);
1014 return DRD && DRD->getInitializer();
1015}
1016
1017LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1018 return CGF.EmitLoadOfPointerLValue(
1019 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1020 getThreadIDVariable()->getType()->castAs<PointerType>());
1021}
1022
1023void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) {
1024 if (!CGF.HaveInsertPoint())
1025 return;
1026 // 1.2.2 OpenMP Language Terminology
1027 // Structured block - An executable statement with a single entry at the
1028 // top and a single exit at the bottom.
1029 // The point of exit cannot be a branch out of the structured block.
1030 // longjmp() and throw() must not violate the entry/exit criteria.
1031 CGF.EHStack.pushTerminate();
1032 if (S)
1034 CodeGen(CGF);
1035 CGF.EHStack.popTerminate();
1036}
1037
1038LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1039 CodeGenFunction &CGF) {
1040 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1041 getThreadIDVariable()->getType(),
1043}
1044
1046 QualType FieldTy) {
1047 auto *Field = FieldDecl::Create(
1048 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1049 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1050 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1051 Field->setAccess(AS_public);
1052 DC->addDecl(Field);
1053 return Field;
1054}
1055
1057 : CGM(CGM), OMPBuilder(CGM.getModule()) {
1058 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1059 llvm::OpenMPIRBuilderConfig Config(CGM.getLangOpts().OpenMPIsDevice, false,
1061 CGM.getLangOpts().OpenMPOffloadMandatory);
1062 // Initialize Types used in OpenMPIRBuilder from OMPKinds.def
1063 OMPBuilder.initialize();
1064 OMPBuilder.setConfig(Config);
1066}
1067
1069 InternalVars.clear();
1070 // Clean non-target variable declarations possibly used only in debug info.
1071 for (const auto &Data : EmittedNonTargetVariables) {
1072 if (!Data.getValue().pointsToAliveValue())
1073 continue;
1074 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1075 if (!GV)
1076 continue;
1077 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1078 continue;
1079 GV->eraseFromParent();
1080 }
1081}
1082
1084 return OMPBuilder.createPlatformSpecificName(Parts);
1085}
1086
1087static llvm::Function *
1089 const Expr *CombinerInitializer, const VarDecl *In,
1090 const VarDecl *Out, bool IsCombiner) {
1091 // void .omp_combiner.(Ty *in, Ty *out);
1092 ASTContext &C = CGM.getContext();
1093 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1094 FunctionArgList Args;
1095 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1096 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1097 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1098 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1099 Args.push_back(&OmpOutParm);
1100 Args.push_back(&OmpInParm);
1101 const CGFunctionInfo &FnInfo =
1102 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1103 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1104 std::string Name = CGM.getOpenMPRuntime().getName(
1105 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1106 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1107 Name, &CGM.getModule());
1108 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1109 if (CGM.getLangOpts().Optimize) {
1110 Fn->removeFnAttr(llvm::Attribute::NoInline);
1111 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1112 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1113 }
1114 CodeGenFunction CGF(CGM);
1115 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1116 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1117 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1118 Out->getLocation());
1119 CodeGenFunction::OMPPrivateScope Scope(CGF);
1120 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1121 Scope.addPrivate(
1122 In, CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1123 .getAddress(CGF));
1124 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1125 Scope.addPrivate(
1126 Out, CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1127 .getAddress(CGF));
1128 (void)Scope.Privatize();
1129 if (!IsCombiner && Out->hasInit() &&
1130 !CGF.isTrivialInitializer(Out->getInit())) {
1131 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1132 Out->getType().getQualifiers(),
1133 /*IsInitializer=*/true);
1134 }
1135 if (CombinerInitializer)
1136 CGF.EmitIgnoredExpr(CombinerInitializer);
1137 Scope.ForceCleanup();
1138 CGF.FinishFunction();
1139 return Fn;
1140}
1141
1144 if (UDRMap.count(D) > 0)
1145 return;
1146 llvm::Function *Combiner = emitCombinerOrInitializer(
1147 CGM, D->getType(), D->getCombiner(),
1148 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1149 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
1150 /*IsCombiner=*/true);
1151 llvm::Function *Initializer = nullptr;
1152 if (const Expr *Init = D->getInitializer()) {
1154 CGM, D->getType(),
1156 : nullptr,
1157 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1158 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
1159 /*IsCombiner=*/false);
1160 }
1161 UDRMap.try_emplace(D, Combiner, Initializer);
1162 if (CGF) {
1163 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1164 Decls.second.push_back(D);
1165 }
1166}
1167
1168std::pair<llvm::Function *, llvm::Function *>
1170 auto I = UDRMap.find(D);
1171 if (I != UDRMap.end())
1172 return I->second;
1173 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1174 return UDRMap.lookup(D);
1175}
1176
1177namespace {
1178// Temporary RAII solution to perform a push/pop stack event on the OpenMP IR
1179// Builder if one is present.
1180struct PushAndPopStackRAII {
1181 PushAndPopStackRAII(llvm::OpenMPIRBuilder *OMPBuilder, CodeGenFunction &CGF,
1182 bool HasCancel, llvm::omp::Directive Kind)
1183 : OMPBuilder(OMPBuilder) {
1184 if (!OMPBuilder)
1185 return;
1186
1187 // The following callback is the crucial part of clangs cleanup process.
1188 //
1189 // NOTE:
1190 // Once the OpenMPIRBuilder is used to create parallel regions (and
1191 // similar), the cancellation destination (Dest below) is determined via
1192 // IP. That means if we have variables to finalize we split the block at IP,
1193 // use the new block (=BB) as destination to build a JumpDest (via
1194 // getJumpDestInCurrentScope(BB)) which then is fed to
1195 // EmitBranchThroughCleanup. Furthermore, there will not be the need
1196 // to push & pop an FinalizationInfo object.
1197 // The FiniCB will still be needed but at the point where the
1198 // OpenMPIRBuilder is asked to construct a parallel (or similar) construct.
1199 auto FiniCB = [&CGF](llvm::OpenMPIRBuilder::InsertPointTy IP) {
1200 assert(IP.getBlock()->end() == IP.getPoint() &&
1201 "Clang CG should cause non-terminated block!");
1202 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1203 CGF.Builder.restoreIP(IP);
1205 CGF.getOMPCancelDestination(OMPD_parallel);
1206 CGF.EmitBranchThroughCleanup(Dest);
1207 };
1208
1209 // TODO: Remove this once we emit parallel regions through the
1210 // OpenMPIRBuilder as it can do this setup internally.
1211 llvm::OpenMPIRBuilder::FinalizationInfo FI({FiniCB, Kind, HasCancel});
1212 OMPBuilder->pushFinalizationCB(std::move(FI));
1213 }
1214 ~PushAndPopStackRAII() {
1215 if (OMPBuilder)
1216 OMPBuilder->popFinalizationCB();
1217 }
1218 llvm::OpenMPIRBuilder *OMPBuilder;
1219};
1220} // namespace
1221
1223 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1224 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1225 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1226 assert(ThreadIDVar->getType()->isPointerType() &&
1227 "thread id variable must be of type kmp_int32 *");
1228 CodeGenFunction CGF(CGM, true);
1229 bool HasCancel = false;
1230 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1231 HasCancel = OPD->hasCancel();
1232 else if (const auto *OPD = dyn_cast<OMPTargetParallelDirective>(&D))
1233 HasCancel = OPD->hasCancel();
1234 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1235 HasCancel = OPSD->hasCancel();
1236 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1237 HasCancel = OPFD->hasCancel();
1238 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1239 HasCancel = OPFD->hasCancel();
1240 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1241 HasCancel = OPFD->hasCancel();
1242 else if (const auto *OPFD =
1243 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1244 HasCancel = OPFD->hasCancel();
1245 else if (const auto *OPFD =
1246 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1247 HasCancel = OPFD->hasCancel();
1248
1249 // TODO: Temporarily inform the OpenMPIRBuilder, if any, about the new
1250 // parallel region to make cancellation barriers work properly.
1251 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1252 PushAndPopStackRAII PSR(&OMPBuilder, CGF, HasCancel, InnermostKind);
1253 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1254 HasCancel, OutlinedHelperName);
1255 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1257}
1258
1260 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1261 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1262 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1264 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1265}
1266
1268 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1269 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1270 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1272 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1273}
1274
1276 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1277 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1278 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1279 bool Tied, unsigned &NumberOfParts) {
1280 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1281 PrePostActionTy &) {
1282 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1283 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
1284 llvm::Value *TaskArgs[] = {
1285 UpLoc, ThreadID,
1286 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1287 TaskTVar->getType()->castAs<PointerType>())
1288 .getPointer(CGF)};
1289 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1290 CGM.getModule(), OMPRTL___kmpc_omp_task),
1291 TaskArgs);
1292 };
1293 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1294 UntiedCodeGen);
1295 CodeGen.setAction(Action);
1296 assert(!ThreadIDVar->getType()->isPointerType() &&
1297 "thread id variable must be of type kmp_int32 for tasks");
1298 const OpenMPDirectiveKind Region =
1299 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1300 : OMPD_task;
1301 const CapturedStmt *CS = D.getCapturedStmt(Region);
1302 bool HasCancel = false;
1303 if (const auto *TD = dyn_cast<OMPTaskDirective>(&D))
1304 HasCancel = TD->hasCancel();
1305 else if (const auto *TD = dyn_cast<OMPTaskLoopDirective>(&D))
1306 HasCancel = TD->hasCancel();
1307 else if (const auto *TD = dyn_cast<OMPMasterTaskLoopDirective>(&D))
1308 HasCancel = TD->hasCancel();
1309 else if (const auto *TD = dyn_cast<OMPParallelMasterTaskLoopDirective>(&D))
1310 HasCancel = TD->hasCancel();
1311
1312 CodeGenFunction CGF(CGM, true);
1313 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1314 InnermostKind, HasCancel, Action);
1315 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1316 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
1317 if (!Tied)
1318 NumberOfParts = Action.getNumberOfParts();
1319 return Res;
1320}
1321
1323 bool AtCurrentPoint) {
1324 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1325 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1326
1327 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1328 if (AtCurrentPoint) {
1329 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1330 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1331 } else {
1332 Elem.second.ServiceInsertPt =
1333 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1334 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1335 }
1336}
1337
1339 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1340 if (Elem.second.ServiceInsertPt) {
1341 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1342 Elem.second.ServiceInsertPt = nullptr;
1343 Ptr->eraseFromParent();
1344 }
1345}
1346
1348 SourceLocation Loc,
1349 SmallString<128> &Buffer) {
1350 llvm::raw_svector_ostream OS(Buffer);
1351 // Build debug location
1353 OS << ";" << PLoc.getFilename() << ";";
1354 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1355 OS << FD->getQualifiedNameAsString();
1356 OS << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1357 return OS.str();
1358}
1359
1361 SourceLocation Loc,
1362 unsigned Flags, bool EmitLoc) {
1363 uint32_t SrcLocStrSize;
1364 llvm::Constant *SrcLocStr;
1365 if ((!EmitLoc && CGM.getCodeGenOpts().getDebugInfo() ==
1366 llvm::codegenoptions::NoDebugInfo) ||
1367 Loc.isInvalid()) {
1368 SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
1369 } else {
1370 std::string FunctionName;
1371 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1372 FunctionName = FD->getQualifiedNameAsString();
1374 const char *FileName = PLoc.getFilename();
1375 unsigned Line = PLoc.getLine();
1376 unsigned Column = PLoc.getColumn();
1377 SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(FunctionName, FileName, Line,
1378 Column, SrcLocStrSize);
1379 }
1380 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1381 return OMPBuilder.getOrCreateIdent(
1382 SrcLocStr, SrcLocStrSize, llvm::omp::IdentFlag(Flags), Reserved2Flags);
1383}
1384
1386 SourceLocation Loc) {
1387 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1388 // If the OpenMPIRBuilder is used we need to use it for all thread id calls as
1389 // the clang invariants used below might be broken.
1390 if (CGM.getLangOpts().OpenMPIRBuilder) {
1391 SmallString<128> Buffer;
1392 OMPBuilder.updateToLocation(CGF.Builder.saveIP());
1393 uint32_t SrcLocStrSize;
1394 auto *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(
1395 getIdentStringFromSourceLocation(CGF, Loc, Buffer), SrcLocStrSize);
1396 return OMPBuilder.getOrCreateThreadID(
1397 OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize));
1398 }
1399
1400 llvm::Value *ThreadID = nullptr;
1401 // Check whether we've already cached a load of the thread id in this
1402 // function.
1403 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1404 if (I != OpenMPLocThreadIDMap.end()) {
1405 ThreadID = I->second.ThreadID;
1406 if (ThreadID != nullptr)
1407 return ThreadID;
1408 }
1409 // If exceptions are enabled, do not use parameter to avoid possible crash.
1410 if (auto *OMPRegionInfo =
1411 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1412 if (OMPRegionInfo->getThreadIDVariable()) {
1413 // Check if this an outlined function with thread id passed as argument.
1414 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1415 llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent();
1416 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1417 !CGF.getLangOpts().CXXExceptions ||
1418 CGF.Builder.GetInsertBlock() == TopBlock ||
1419 !isa<llvm::Instruction>(LVal.getPointer(CGF)) ||
1420 cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1421 TopBlock ||
1422 cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1423 CGF.Builder.GetInsertBlock()) {
1424 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1425 // If value loaded in entry block, cache it and use it everywhere in
1426 // function.
1427 if (CGF.Builder.GetInsertBlock() == TopBlock) {
1428 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1429 Elem.second.ThreadID = ThreadID;
1430 }
1431 return ThreadID;
1432 }
1433 }
1434 }
1435
1436 // This is not an outlined function region - need to call __kmpc_int32
1437 // kmpc_global_thread_num(ident_t *loc).
1438 // Generate thread id value and cache this value for use across the
1439 // function.
1440 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1441 if (!Elem.second.ServiceInsertPt)
1443 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1444 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
1445 llvm::CallInst *Call = CGF.Builder.CreateCall(
1446 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
1447 OMPRTL___kmpc_global_thread_num),
1448 emitUpdateLocation(CGF, Loc));
1449 Call->setCallingConv(CGF.getRuntimeCC());
1450 Elem.second.ThreadID = Call;
1451 return Call;
1452}
1453
1455 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1456 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1458 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1459 }
1460 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1461 for(const auto *D : FunctionUDRMap[CGF.CurFn])
1462 UDRMap.erase(D);
1463 FunctionUDRMap.erase(CGF.CurFn);
1464 }
1465 auto I = FunctionUDMMap.find(CGF.CurFn);
1466 if (I != FunctionUDMMap.end()) {
1467 for(const auto *D : I->second)
1468 UDMMap.erase(D);
1469 FunctionUDMMap.erase(I);
1470 }
1473}
1474
1476 return OMPBuilder.IdentPtr;
1477}
1478
1480 if (!Kmpc_MicroTy) {
1481 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1482 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1483 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1484 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1485 }
1486 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1487}
1488
1489llvm::FunctionCallee
1491 bool IsGPUDistribute) {
1492 assert((IVSize == 32 || IVSize == 64) &&
1493 "IV size is not compatible with the omp runtime");
1494 StringRef Name;
1495 if (IsGPUDistribute)
1496 Name = IVSize == 32 ? (IVSigned ? "__kmpc_distribute_static_init_4"
1497 : "__kmpc_distribute_static_init_4u")
1498 : (IVSigned ? "__kmpc_distribute_static_init_8"
1499 : "__kmpc_distribute_static_init_8u");
1500 else
1501 Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1502 : "__kmpc_for_static_init_4u")
1503 : (IVSigned ? "__kmpc_for_static_init_8"
1504 : "__kmpc_for_static_init_8u");
1505
1506 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1507 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
1508 llvm::Type *TypeParams[] = {
1509 getIdentTyPointerTy(), // loc
1510 CGM.Int32Ty, // tid
1511 CGM.Int32Ty, // schedtype
1512 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1513 PtrTy, // p_lower
1514 PtrTy, // p_upper
1515 PtrTy, // p_stride
1516 ITy, // incr
1517 ITy // chunk
1518 };
1519 auto *FnTy =
1520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1521 return CGM.CreateRuntimeFunction(FnTy, Name);
1522}
1523
1524llvm::FunctionCallee
1525CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
1526 assert((IVSize == 32 || IVSize == 64) &&
1527 "IV size is not compatible with the omp runtime");
1528 StringRef Name =
1529 IVSize == 32
1530 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1531 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1532 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1533 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1534 CGM.Int32Ty, // tid
1535 CGM.Int32Ty, // schedtype
1536 ITy, // lower
1537 ITy, // upper
1538 ITy, // stride
1539 ITy // chunk
1540 };
1541 auto *FnTy =
1542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543 return CGM.CreateRuntimeFunction(FnTy, Name);
1544}
1545
1546llvm::FunctionCallee
1547CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
1548 assert((IVSize == 32 || IVSize == 64) &&
1549 "IV size is not compatible with the omp runtime");
1550 StringRef Name =
1551 IVSize == 32
1552 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1553 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1554 llvm::Type *TypeParams[] = {
1555 getIdentTyPointerTy(), // loc
1556 CGM.Int32Ty, // tid
1557 };
1558 auto *FnTy =
1559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1560 return CGM.CreateRuntimeFunction(FnTy, Name);
1561}
1562
1563llvm::FunctionCallee
1564CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
1565 assert((IVSize == 32 || IVSize == 64) &&
1566 "IV size is not compatible with the omp runtime");
1567 StringRef Name =
1568 IVSize == 32
1569 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1570 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1571 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1572 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
1573 llvm::Type *TypeParams[] = {
1574 getIdentTyPointerTy(), // loc
1575 CGM.Int32Ty, // tid
1576 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1577 PtrTy, // p_lower
1578 PtrTy, // p_upper
1579 PtrTy // p_stride
1580 };
1581 auto *FnTy =
1582 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1583 return CGM.CreateRuntimeFunction(FnTy, Name);
1584}
1585
1586/// Obtain information that uniquely identifies a target entry. This
1587/// consists of the file and device IDs as well as line number associated with
1588/// the relevant entry source location.
1589static llvm::TargetRegionEntryInfo
1591 StringRef ParentName = "") {
1592 SourceManager &SM = C.getSourceManager();
1593
1594 // The loc should be always valid and have a file ID (the user cannot use
1595 // #pragma directives in macros)
1596
1597 assert(Loc.isValid() && "Source location is expected to be always valid.");
1598
1599 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1600 assert(PLoc.isValid() && "Source location is expected to be always valid.");
1601
1602 llvm::sys::fs::UniqueID ID;
1603 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
1604 PLoc = SM.getPresumedLoc(Loc, /*UseLineDirectives=*/false);
1605 assert(PLoc.isValid() && "Source location is expected to be always valid.");
1606 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
1607 SM.getDiagnostics().Report(diag::err_cannot_open_file)
1608 << PLoc.getFilename() << EC.message();
1609 }
1610
1611 return llvm::TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(),
1612 PLoc.getLine());
1613}
1614
1616 if (CGM.getLangOpts().OpenMPSimd)
1617 return Address::invalid();
1618 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1619 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
1620 if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link ||
1621 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
1622 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
1624 SmallString<64> PtrName;
1625 {
1626 llvm::raw_svector_ostream OS(PtrName);
1628 if (!VD->isExternallyVisible()) {
1629 auto EntryInfo = getTargetEntryUniqueInfo(
1631 OS << llvm::format("_%x", EntryInfo.FileID);
1632 }
1633 OS << "_decl_tgt_ref_ptr";
1634 }
1635 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
1636 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
1637 llvm::Type *LlvmPtrTy = CGM.getTypes().ConvertTypeForMem(PtrTy);
1638 if (!Ptr) {
1639 Ptr = OMPBuilder.getOrCreateInternalVariable(LlvmPtrTy, PtrName);
1640
1641 auto *GV = cast<llvm::GlobalVariable>(Ptr);
1642 GV->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
1643
1644 if (!CGM.getLangOpts().OpenMPIsDevice)
1645 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
1646 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
1647 }
1648 return Address(Ptr, LlvmPtrTy, CGM.getContext().getDeclAlign(VD));
1649 }
1650 return Address::invalid();
1651}
1652
1653llvm::Constant *
1655 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1657 // Lookup the entry, lazily creating it if necessary.
1658 std::string Suffix = getName({"cache", ""});
1659 return OMPBuilder.getOrCreateInternalVariable(
1660 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix).str());
1661}
1662
1664 const VarDecl *VD,
1665 Address VDAddr,
1666 SourceLocation Loc) {
1667 if (CGM.getLangOpts().OpenMPUseTLS &&
1669 return VDAddr;
1670
1671 llvm::Type *VarTy = VDAddr.getElementType();
1672 llvm::Value *Args[] = {
1673 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1674 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy),
1677 return Address(
1678 CGF.EmitRuntimeCall(
1679 OMPBuilder.getOrCreateRuntimeFunction(
1680 CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
1681 Args),
1682 CGF.Int8Ty, VDAddr.getAlignment());
1683}
1684
1686 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1687 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1688 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1689 // library.
1690 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
1691 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1692 CGM.getModule(), OMPRTL___kmpc_global_thread_num),
1693 OMPLoc);
1694 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1695 // to register constructor/destructor for variable.
1696 llvm::Value *Args[] = {
1697 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
1698 Ctor, CopyCtor, Dtor};
1699 CGF.EmitRuntimeCall(
1700 OMPBuilder.getOrCreateRuntimeFunction(
1701 CGM.getModule(), OMPRTL___kmpc_threadprivate_register),
1702 Args);
1703}
1704
1706 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1707 bool PerformInit, CodeGenFunction *CGF) {
1708 if (CGM.getLangOpts().OpenMPUseTLS &&
1710 return nullptr;
1711
1712 VD = VD->getDefinition(CGM.getContext());
1713 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
1714 QualType ASTTy = VD->getType();
1715
1716 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1717 const Expr *Init = VD->getAnyInitializer();
1718 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1719 // Generate function that re-emits the declaration's initializer into the
1720 // threadprivate copy of the variable VD
1721 CodeGenFunction CtorCGF(CGM);
1722 FunctionArgList Args;
1723 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1724 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1726 Args.push_back(&Dst);
1727
1729 CGM.getContext().VoidPtrTy, Args);
1730 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1731 std::string Name = getName({"__kmpc_global_ctor_", ""});
1732 llvm::Function *Fn =
1733 CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1734 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1735 Args, Loc, Loc);
1736 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
1737 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1739 Address Arg(ArgVal, CtorCGF.Int8Ty, VDAddr.getAlignment());
1740 Arg = CtorCGF.Builder.CreateElementBitCast(
1741 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
1742 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1743 /*IsInitializer=*/true);
1744 ArgVal = CtorCGF.EmitLoadOfScalar(
1745 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1747 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1748 CtorCGF.FinishFunction();
1749 Ctor = Fn;
1750 }
1752 // Generate function that emits destructor call for the threadprivate copy
1753 // of the variable VD
1754 CodeGenFunction DtorCGF(CGM);
1755 FunctionArgList Args;
1756 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1757 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1759 Args.push_back(&Dst);
1760
1762 CGM.getContext().VoidTy, Args);
1763 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1764 std::string Name = getName({"__kmpc_global_dtor_", ""});
1765 llvm::Function *Fn =
1766 CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1767 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1768 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1769 Loc, Loc);
1770 // Create a scope with an artificial location for the body of this function.
1771 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1772 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
1773 DtorCGF.GetAddrOfLocalVar(&Dst),
1774 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1775 DtorCGF.emitDestroy(
1776 Address(ArgVal, DtorCGF.Int8Ty, VDAddr.getAlignment()), ASTTy,
1777 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1778 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1779 DtorCGF.FinishFunction();
1780 Dtor = Fn;
1781 }
1782 // Do not emit init function if it is not required.
1783 if (!Ctor && !Dtor)
1784 return nullptr;
1785
1786 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1787 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1788 /*isVarArg=*/false)
1789 ->getPointerTo();
1790 // Copying constructor for the threadprivate variable.
1791 // Must be NULL - reserved by runtime, but currently it requires that this
1792 // parameter is always NULL. Otherwise it fires assertion.
1793 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1794 if (Ctor == nullptr) {
1795 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1796 /*isVarArg=*/false)
1797 ->getPointerTo();
1798 Ctor = llvm::Constant::getNullValue(CtorTy);
1799 }
1800 if (Dtor == nullptr) {
1801 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1802 /*isVarArg=*/false)
1803 ->getPointerTo();
1804 Dtor = llvm::Constant::getNullValue(DtorTy);
1805 }
1806 if (!CGF) {
1807 auto *InitFunctionTy =
1808 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1809 std::string Name = getName({"__omp_threadprivate_init_", ""});
1810 llvm::Function *InitFunction = CGM.CreateGlobalInitOrCleanUpFunction(
1811 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
1812 CodeGenFunction InitCGF(CGM);
1813 FunctionArgList ArgList;
1814 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1815 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1816 Loc, Loc);
1817 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1818 InitCGF.FinishFunction();
1819 return InitFunction;
1820 }
1821 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1822 }
1823 return nullptr;
1824}
1825
1827 llvm::GlobalVariable *Addr,
1828 bool PerformInit) {
1829 if (CGM.getLangOpts().OMPTargetTriples.empty() &&
1830 !CGM.getLangOpts().OpenMPIsDevice)
1831 return false;
1832 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1833 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
1834 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
1835 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
1836 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
1838 return CGM.getLangOpts().OpenMPIsDevice;
1839 VD = VD->getDefinition(CGM.getContext());
1840 assert(VD && "Unknown VarDecl");
1841
1842 if (!DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
1843 return CGM.getLangOpts().OpenMPIsDevice;
1844
1845 QualType ASTTy = VD->getType();
1847
1848 // Produce the unique prefix to identify the new target regions. We use
1849 // the source location of the variable declaration which we know to not
1850 // conflict with any target region.
1851 auto EntryInfo =
1853 SmallString<128> Buffer, Out;
1854 OMPBuilder.OffloadInfoManager.getTargetRegionEntryFnName(Buffer, EntryInfo);
1855
1856 const Expr *Init = VD->getAnyInitializer();
1857 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1858 llvm::Constant *Ctor;
1859 llvm::Constant *ID;
1860 if (CGM.getLangOpts().OpenMPIsDevice) {
1861 // Generate function that re-emits the declaration's initializer into
1862 // the threadprivate copy of the variable VD
1863 CodeGenFunction CtorCGF(CGM);
1864
1866 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1867 llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
1868 FTy, Twine(Buffer, "_ctor"), FI, Loc, false,
1869 llvm::GlobalValue::WeakODRLinkage);
1870 Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1871 if (CGM.getTriple().isAMDGCN())
1872 Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
1873 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
1874 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
1875 FunctionArgList(), Loc, Loc);
1876 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
1877 llvm::Constant *AddrInAS0 = Addr;
1878 if (Addr->getAddressSpace() != 0)
1879 AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast(
1880 Addr, llvm::PointerType::getWithSamePointeeType(
1881 cast<llvm::PointerType>(Addr->getType()), 0));
1882 CtorCGF.EmitAnyExprToMem(Init,
1883 Address(AddrInAS0, Addr->getValueType(),
1885 Init->getType().getQualifiers(),
1886 /*IsInitializer=*/true);
1887 CtorCGF.FinishFunction();
1888 Ctor = Fn;
1889 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
1890 } else {
1891 Ctor = new llvm::GlobalVariable(
1892 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1893 llvm::GlobalValue::PrivateLinkage,
1894 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
1895 ID = Ctor;
1896 }
1897
1898 // Register the information for the entry associated with the constructor.
1899 Out.clear();
1900 auto CtorEntryInfo = EntryInfo;
1901 CtorEntryInfo.ParentName = Twine(Buffer, "_ctor").toStringRef(Out);
1902 OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo(
1903 CtorEntryInfo, Ctor, ID,
1904 llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryCtor);
1905 }
1907 llvm::Constant *Dtor;
1908 llvm::Constant *ID;
1909 if (CGM.getLangOpts().OpenMPIsDevice) {
1910 // Generate function that emits destructor call for the threadprivate
1911 // copy of the variable VD
1912 CodeGenFunction DtorCGF(CGM);
1913
1915 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1916 llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
1917 FTy, Twine(Buffer, "_dtor"), FI, Loc, false,
1918 llvm::GlobalValue::WeakODRLinkage);
1919 Fn->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1920 if (CGM.getTriple().isAMDGCN())
1921 Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
1922 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1923 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
1924 FunctionArgList(), Loc, Loc);
1925 // Create a scope with an artificial location for the body of this
1926 // function.
1927 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1928 llvm::Constant *AddrInAS0 = Addr;
1929 if (Addr->getAddressSpace() != 0)
1930 AddrInAS0 = llvm::ConstantExpr::getAddrSpaceCast(
1931 Addr, llvm::PointerType::getWithSamePointeeType(
1932 cast<llvm::PointerType>(Addr->getType()), 0));
1933 DtorCGF.emitDestroy(Address(AddrInAS0, Addr->getValueType(),
1935 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1936 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1937 DtorCGF.FinishFunction();
1938 Dtor = Fn;
1939 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
1940 } else {
1941 Dtor = new llvm::GlobalVariable(
1942 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1943 llvm::GlobalValue::PrivateLinkage,
1944 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
1945 ID = Dtor;
1946 }
1947 // Register the information for the entry associated with the destructor.
1948 Out.clear();
1949 auto DtorEntryInfo = EntryInfo;
1950 DtorEntryInfo.ParentName = Twine(Buffer, "_dtor").toStringRef(Out);
1951 OMPBuilder.OffloadInfoManager.registerTargetRegionEntryInfo(
1952 DtorEntryInfo, Dtor, ID,
1953 llvm::OffloadEntriesInfoManager::OMPTargetRegionEntryDtor);
1954 }
1955 return CGM.getLangOpts().OpenMPIsDevice;
1956}
1957
1959 QualType VarType,
1960 StringRef Name) {
1961 std::string Suffix = getName({"artificial", ""});
1962 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
1963 llvm::GlobalVariable *GAddr = OMPBuilder.getOrCreateInternalVariable(
1964 VarLVType, Twine(Name).concat(Suffix).str());
1965 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS &&
1967 GAddr->setThreadLocal(/*Val=*/true);
1968 return Address(GAddr, GAddr->getValueType(),
1970 }
1971 std::string CacheSuffix = getName({"cache", ""});
1972 llvm::Value *Args[] = {
1976 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
1977 /*isSigned=*/false),
1978 OMPBuilder.getOrCreateInternalVariable(
1980 Twine(Name).concat(Suffix).concat(CacheSuffix).str())};
1981 return Address(
1983 CGF.EmitRuntimeCall(
1984 OMPBuilder.getOrCreateRuntimeFunction(
1985 CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
1986 Args),
1987 VarLVType->getPointerTo(/*AddrSpace=*/0)),
1988 VarLVType, CGM.getContext().getTypeAlignInChars(VarType));
1989}
1990
1992 const RegionCodeGenTy &ThenGen,
1993 const RegionCodeGenTy &ElseGen) {
1994 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1995
1996 // If the condition constant folds and can be elided, try to avoid emitting
1997 // the condition and the dead arm of the if/else.
1998 bool CondConstant;
1999 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2000 if (CondConstant)
2001 ThenGen(CGF);
2002 else
2003 ElseGen(CGF);
2004 return;
2005 }
2006
2007 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2008 // emit the conditional branch.
2009 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2010 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2011 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
2012 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2013
2014 // Emit the 'then' code.
2015 CGF.EmitBlock(ThenBlock);
2016 ThenGen(CGF);
2017 CGF.EmitBranch(ContBlock);
2018 // Emit the 'else' code if present.
2019 // There is no need to emit line number for unconditional branch.
2021 CGF.EmitBlock(ElseBlock);
2022 ElseGen(CGF);
2023 // There is no need to emit line number for unconditional branch.
2025 CGF.EmitBranch(ContBlock);
2026 // Emit the continuation block for code after the if.
2027 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2028}
2029
2031 llvm::Function *OutlinedFn,
2032 ArrayRef<llvm::Value *> CapturedVars,
2033 const Expr *IfCond,
2034 llvm::Value *NumThreads) {
2035 if (!CGF.HaveInsertPoint())
2036 return;
2037 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2038 auto &M = CGM.getModule();
2039 auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc,
2040 this](CodeGenFunction &CGF, PrePostActionTy &) {
2041 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2043 llvm::Value *Args[] = {
2044 RTLoc,
2045 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2046 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2048 RealArgs.append(std::begin(Args), std::end(Args));
2049 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2050
2051 llvm::FunctionCallee RTLFn =
2052 OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_fork_call);
2053 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2054 };
2055 auto &&ElseGen = [&M, OutlinedFn, CapturedVars, RTLoc, Loc,
2056 this](CodeGenFunction &CGF, PrePostActionTy &) {
2058 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
2059 // Build calls:
2060 // __kmpc_serialized_parallel(&Loc, GTid);
2061 llvm::Value *Args[] = {RTLoc, ThreadID};
2062 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2063 M, OMPRTL___kmpc_serialized_parallel),
2064 Args);
2065
2066 // OutlinedFn(&GTid, &zero_bound, CapturedStruct);
2067 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2068 Address ZeroAddrBound =
2070 /*Name=*/".bound.zero.addr");
2071 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddrBound);
2073 // ThreadId for serialized parallels is 0.
2074 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2075 OutlinedFnArgs.push_back(ZeroAddrBound.getPointer());
2076 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2077
2078 // Ensure we do not inline the function. This is trivially true for the ones
2079 // passed to __kmpc_fork_call but the ones called in serialized regions
2080 // could be inlined. This is not a perfect but it is closer to the invariant
2081 // we want, namely, every data environment starts with a new function.
2082 // TODO: We should pass the if condition to the runtime function and do the
2083 // handling there. Much cleaner code.
2084 OutlinedFn->removeFnAttr(llvm::Attribute::AlwaysInline);
2085 OutlinedFn->addFnAttr(llvm::Attribute::NoInline);
2086 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2087
2088 // __kmpc_end_serialized_parallel(&Loc, GTid);
2089 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2090 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2091 M, OMPRTL___kmpc_end_serialized_parallel),
2092 EndArgs);
2093 };
2094 if (IfCond) {
2095 emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2096 } else {
2097 RegionCodeGenTy ThenRCG(ThenGen);
2098 ThenRCG(CGF);
2099 }
2100}
2101
2102// If we're inside an (outlined) parallel region, use the region info's
2103// thread-ID variable (it is passed in a first argument of the outlined function
2104// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2105// regular serial code region, get thread ID by calling kmp_int32
2106// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2107// return the address of that temp.
2109 SourceLocation Loc) {
2110 if (auto *OMPRegionInfo =
2111 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2112 if (OMPRegionInfo->getThreadIDVariable())
2113 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(CGF);
2114
2115 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2116 QualType Int32Ty =
2117 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2118 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2119 CGF.EmitStoreOfScalar(ThreadID,
2120 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2121
2122 return ThreadIDTemp;
2123}
2124
2125llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2126 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2127 std::string Name = getName({Prefix, "var"});
2128 return OMPBuilder.getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2129}
2130
2131namespace {
2132/// Common pre(post)-action for different OpenMP constructs.
2133class CommonActionTy final : public PrePostActionTy {
2134 llvm::FunctionCallee EnterCallee;
2135 ArrayRef<llvm::Value *> EnterArgs;
2136 llvm::FunctionCallee ExitCallee;
2137 ArrayRef<llvm::Value *> ExitArgs;
2138 bool Conditional;
2139 llvm::BasicBlock *ContBlock = nullptr;
2140
2141public:
2142 CommonActionTy(llvm::FunctionCallee EnterCallee,
2143 ArrayRef<llvm::Value *> EnterArgs,
2144 llvm::FunctionCallee ExitCallee,
2145 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
2146 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2147 ExitArgs(ExitArgs), Conditional(Conditional) {}
2148 void Enter(CodeGenFunction &CGF) override {
2149 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2150 if (Conditional) {
2151 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2152 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2153 ContBlock = CGF.createBasicBlock("omp_if.end");
2154 // Generate the branch (If-stmt)
2155 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2156 CGF.EmitBlock(ThenBlock);
2157 }
2158 }
2159 void Done(CodeGenFunction &CGF) {
2160 // Emit the rest of blocks/branches
2161 CGF.EmitBranch(ContBlock);
2162 CGF.EmitBlock(ContBlock, true);
2163 }
2164 void Exit(CodeGenFunction &CGF) override {
2165 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2166 }
2167};
2168} // anonymous namespace
2169
2171 StringRef CriticalName,
2172 const RegionCodeGenTy &CriticalOpGen,
2173 SourceLocation Loc, const Expr *Hint) {
2174 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2175 // CriticalOpGen();
2176 // __kmpc_end_critical(ident_t *, gtid, Lock);
2177 // Prepare arguments and build a call to __kmpc_critical
2178 if (!CGF.HaveInsertPoint())
2179 return;
2180 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2181 getCriticalRegionLock(CriticalName)};
2182 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2183 std::end(Args));
2184 if (Hint) {
2185 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2186 CGF.EmitScalarExpr(Hint), CGM.Int32Ty, /*isSigned=*/false));
2187 }
2188 CommonActionTy Action(
2189 OMPBuilder.getOrCreateRuntimeFunction(
2190 CGM.getModule(),
2191 Hint ? OMPRTL___kmpc_critical_with_hint : OMPRTL___kmpc_critical),
2192 EnterArgs,
2193 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2194 OMPRTL___kmpc_end_critical),
2195 Args);
2196 CriticalOpGen.setAction(Action);
2197 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2198}
2199
2201 const RegionCodeGenTy &MasterOpGen,
2202 SourceLocation Loc) {
2203 if (!CGF.HaveInsertPoint())
2204 return;
2205 // if(__kmpc_master(ident_t *, gtid)) {
2206 // MasterOpGen();
2207 // __kmpc_end_master(ident_t *, gtid);
2208 // }
2209 // Prepare arguments and build a call to __kmpc_master
2210 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2211 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2212 CGM.getModule(), OMPRTL___kmpc_master),
2213 Args,
2214 OMPBuilder.getOrCreateRuntimeFunction(
2215 CGM.getModule(), OMPRTL___kmpc_end_master),
2216 Args,
2217 /*Conditional=*/true);
2218 MasterOpGen.setAction(Action);
2219 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2220 Action.Done(CGF);
2221}
2222
2224 const RegionCodeGenTy &MaskedOpGen,
2225 SourceLocation Loc, const Expr *Filter) {
2226 if (!CGF.HaveInsertPoint())
2227 return;
2228 // if(__kmpc_masked(ident_t *, gtid, filter)) {
2229 // MaskedOpGen();
2230 // __kmpc_end_masked(iden_t *, gtid);
2231 // }
2232 // Prepare arguments and build a call to __kmpc_masked
2233 llvm::Value *FilterVal = Filter
2234 ? CGF.EmitScalarExpr(Filter, CGF.Int32Ty)
2235 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
2236 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2237 FilterVal};
2238 llvm::Value *ArgsEnd[] = {emitUpdateLocation(CGF, Loc),
2239 getThreadID(CGF, Loc)};
2240 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2241 CGM.getModule(), OMPRTL___kmpc_masked),
2242 Args,
2243 OMPBuilder.getOrCreateRuntimeFunction(
2244 CGM.getModule(), OMPRTL___kmpc_end_masked),
2245 ArgsEnd,
2246 /*Conditional=*/true);
2247 MaskedOpGen.setAction(Action);
2248 emitInlinedDirective(CGF, OMPD_masked, MaskedOpGen);
2249 Action.Done(CGF);
2250}
2251
2253 SourceLocation Loc) {
2254 if (!CGF.HaveInsertPoint())
2255 return;
2256 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2257 OMPBuilder.createTaskyield(CGF.Builder);
2258 } else {
2259 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2260 llvm::Value *Args[] = {
2261 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2262 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2263 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2264 CGM.getModule(), OMPRTL___kmpc_omp_taskyield),
2265 Args);
2266 }
2267
2268 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2269 Region->emitUntiedSwitch(CGF);
2270}
2271
2273 const RegionCodeGenTy &TaskgroupOpGen,
2274 SourceLocation Loc) {
2275 if (!CGF.HaveInsertPoint())
2276 return;
2277 // __kmpc_taskgroup(ident_t *, gtid);
2278 // TaskgroupOpGen();
2279 // __kmpc_end_taskgroup(ident_t *, gtid);
2280 // Prepare arguments and build a call to __kmpc_taskgroup
2281 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2282 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2283 CGM.getModule(), OMPRTL___kmpc_taskgroup),
2284 Args,
2285 OMPBuilder.getOrCreateRuntimeFunction(
2286 CGM.getModule(), OMPRTL___kmpc_end_taskgroup),
2287 Args);
2288 TaskgroupOpGen.setAction(Action);
2289 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2290}
2291
2292/// Given an array of pointers to variables, project the address of a
2293/// given variable.
2295 unsigned Index, const VarDecl *Var) {
2296 // Pull out the pointer to the variable.
2297 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
2298 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2299
2300 llvm::Type *ElemTy = CGF.ConvertTypeForMem(Var->getType());
2301 return Address(
2302 CGF.Builder.CreateBitCast(
2303 Ptr, ElemTy->getPointerTo(Ptr->getType()->getPointerAddressSpace())),
2304 ElemTy, CGF.getContext().getDeclAlign(Var));
2305}
2306
2308 CodeGenModule &CGM, llvm::Type *ArgsElemType,
2309 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2310 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2311 SourceLocation Loc) {
2312 ASTContext &C = CGM.getContext();
2313 // void copy_func(void *LHSArg, void *RHSArg);
2314 FunctionArgList Args;
2315 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2317 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2319 Args.push_back(&LHSArg);
2320 Args.push_back(&RHSArg);
2321 const auto &CGFI =
2322 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2323 std::string Name =
2324 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
2325 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2326 llvm::GlobalValue::InternalLinkage, Name,
2327 &CGM.getModule());
2329 Fn->setDoesNotRecurse();
2330 CodeGenFunction CGF(CGM);
2331 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2332 // Dest = (void*[n])(LHSArg);
2333 // Src = (void*[n])(RHSArg);
2335 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2336 ArgsElemType->getPointerTo()),
2337 ArgsElemType, CGF.getPointerAlign());
2339 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2340 ArgsElemType->getPointerTo()),
2341 ArgsElemType, CGF.getPointerAlign());
2342 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2343 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2344 // ...
2345 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2346 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2347 const auto *DestVar =
2348 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2349 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2350
2351 const auto *SrcVar =
2352 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2353 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2354
2355 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2356 QualType Type = VD->getType();
2357 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2358 }
2359 CGF.FinishFunction();
2360 return Fn;
2361}
2362
2364 const RegionCodeGenTy &SingleOpGen,
2365 SourceLocation Loc,
2366 ArrayRef<const Expr *> CopyprivateVars,
2367 ArrayRef<const Expr *> SrcExprs,
2368 ArrayRef<const Expr *> DstExprs,
2369 ArrayRef<const Expr *> AssignmentOps) {
2370 if (!CGF.HaveInsertPoint())
2371 return;
2372 assert(CopyprivateVars.size() == SrcExprs.size() &&
2373 CopyprivateVars.size() == DstExprs.size() &&
2374 CopyprivateVars.size() == AssignmentOps.size());
2376 // int32 did_it = 0;
2377 // if(__kmpc_single(ident_t *, gtid)) {
2378 // SingleOpGen();
2379 // __kmpc_end_single(ident_t *, gtid);
2380 // did_it = 1;
2381 // }
2382 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2383 // <copy_func>, did_it);
2384
2385 Address DidIt = Address::invalid();
2386 if (!CopyprivateVars.empty()) {
2387 // int32 did_it = 0;
2388 QualType KmpInt32Ty =
2389 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2390 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2391 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2392 }
2393 // Prepare arguments and build a call to __kmpc_single
2394 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2395 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2396 CGM.getModule(), OMPRTL___kmpc_single),
2397 Args,
2398 OMPBuilder.getOrCreateRuntimeFunction(
2399 CGM.getModule(), OMPRTL___kmpc_end_single),
2400 Args,
2401 /*Conditional=*/true);
2402 SingleOpGen.setAction(Action);
2403 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2404 if (DidIt.isValid()) {
2405 // did_it = 1;
2406 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2407 }
2408 Action.Done(CGF);
2409 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2410 // <copy_func>, did_it);
2411 if (DidIt.isValid()) {
2412 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2413 QualType CopyprivateArrayTy = C.getConstantArrayType(
2414 C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
2415 /*IndexTypeQuals=*/0);
2416 // Create a list of all private variables for copyprivate.
2417 Address CopyprivateList =
2418 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2419 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2420 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
2421 CGF.Builder.CreateStore(
2423 CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF),
2424 CGF.VoidPtrTy),
2425 Elem);
2426 }
2427 // Build function that copies private values from single region to all other
2428 // threads in the corresponding parallel region.
2429 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
2430 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), CopyprivateVars,
2431 SrcExprs, DstExprs, AssignmentOps, Loc);
2432 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2434 CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty);
2435 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
2436 llvm::Value *Args[] = {
2437 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2438 getThreadID(CGF, Loc), // i32 <gtid>
2439 BufSize, // size_t <buf_size>
2440 CL.getPointer(), // void *<copyprivate list>
2441 CpyFn, // void (*) (void *, void *) <copy_func>
2442 DidItVal // i32 did_it
2443 };
2444 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2445 CGM.getModule(), OMPRTL___kmpc_copyprivate),
2446 Args);
2447 }
2448}
2449
2451 const RegionCodeGenTy &OrderedOpGen,
2452 SourceLocation Loc, bool IsThreads) {
2453 if (!CGF.HaveInsertPoint())
2454 return;
2455 // __kmpc_ordered(ident_t *, gtid);
2456 // OrderedOpGen();
2457 // __kmpc_end_ordered(ident_t *, gtid);
2458 // Prepare arguments and build a call to __kmpc_ordered
2459 if (IsThreads) {
2460 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2461 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2462 CGM.getModule(), OMPRTL___kmpc_ordered),
2463 Args,
2464 OMPBuilder.getOrCreateRuntimeFunction(
2465 CGM.getModule(), OMPRTL___kmpc_end_ordered),
2466 Args);
2467 OrderedOpGen.setAction(Action);
2468 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2469 return;
2470 }
2471 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2472}
2473
2475 unsigned Flags;
2476 if (Kind == OMPD_for)
2477 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2478 else if (Kind == OMPD_sections)
2479 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2480 else if (Kind == OMPD_single)
2481 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2482 else if (Kind == OMPD_barrier)
2483 Flags = OMP_IDENT_BARRIER_EXPL;
2484 else
2485 Flags = OMP_IDENT_BARRIER_IMPL;
2486 return Flags;
2487}
2488
2490 CodeGenFunction &CGF, const OMPLoopDirective &S,
2491 OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
2492 // Check if the loop directive is actually a doacross loop directive. In this
2493 // case choose static, 1 schedule.
2494 if (llvm::any_of(
2495 S.getClausesOfKind<OMPOrderedClause>(),
2496 [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
2497 ScheduleKind = OMPC_SCHEDULE_static;
2498 // Chunk size is 1 in this case.
2499 llvm::APInt ChunkSize(32, 1);
2500 ChunkExpr = IntegerLiteral::Create(
2501 CGF.getContext(), ChunkSize,
2502 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2503 SourceLocation());
2504 }
2505}
2506
2508 OpenMPDirectiveKind Kind, bool EmitChecks,
2509 bool ForceSimpleCall) {
2510 // Check if we should use the OMPBuilder
2511 auto *OMPRegionInfo =
2512 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo);
2513 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2514 CGF.Builder.restoreIP(OMPBuilder.createBarrier(
2515 CGF.Builder, Kind, ForceSimpleCall, EmitChecks));
2516 return;
2517 }
2518
2519 if (!CGF.HaveInsertPoint())
2520 return;
2521 // Build call __kmpc_cancel_barrier(loc, thread_id);
2522 // Build call __kmpc_barrier(loc, thread_id);
2523 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2524 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2525 // thread_id);
2526 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2527 getThreadID(CGF, Loc)};
2528 if (OMPRegionInfo) {
2529 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2530 llvm::Value *Result = CGF.EmitRuntimeCall(
2531 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2532 OMPRTL___kmpc_cancel_barrier),
2533 Args);
2534 if (EmitChecks) {
2535 // if (__kmpc_cancel_barrier()) {
2536 // exit from construct;
2537 // }
2538 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
2539 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
2540 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
2541 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2542 CGF.EmitBlock(ExitBB);
2543 // exit from construct;
2544 CodeGenFunction::JumpDest CancelDestination =
2545 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2546 CGF.EmitBranchThroughCleanup(CancelDestination);
2547 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2548 }
2549 return;
2550 }
2551 }
2552 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2553 CGM.getModule(), OMPRTL___kmpc_barrier),
2554 Args);
2555}
2556
2558 Expr *ME, bool IsFatal) {
2559 llvm::Value *MVL =
2560 ME ? CGF.EmitStringLiteralLValue(cast<StringLiteral>(ME)).getPointer(CGF)
2561 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2562 // Build call void __kmpc_error(ident_t *loc, int severity, const char
2563 // *message)
2564 llvm::Value *Args[] = {
2565 emitUpdateLocation(CGF, Loc, /*Flags=*/0, /*GenLoc=*/true),
2566 llvm::ConstantInt::get(CGM.Int32Ty, IsFatal ? 2 : 1),
2567 CGF.Builder.CreatePointerCast(MVL, CGM.Int8PtrTy)};
2568 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2569 CGM.getModule(), OMPRTL___kmpc_error),
2570 Args);
2571}
2572
2573/// Map the OpenMP loop schedule to the runtime enumeration.
2574static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2575 bool Chunked, bool Ordered) {
2576 switch (ScheduleKind) {
2577 case OMPC_SCHEDULE_static:
2578 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2579 : (Ordered ? OMP_ord_static : OMP_sch_static);
2580 case OMPC_SCHEDULE_dynamic:
2581 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2582 case OMPC_SCHEDULE_guided:
2583 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2584 case OMPC_SCHEDULE_runtime:
2585 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2586 case OMPC_SCHEDULE_auto:
2587 return Ordered ? OMP_ord_auto : OMP_sch_auto;
2589 assert(!Chunked && "chunk was specified but schedule kind not known");
2590 return Ordered ? OMP_ord_static : OMP_sch_static;
2591 }
2592 llvm_unreachable("Unexpected runtime schedule");
2593}
2594
2595/// Map the OpenMP distribute schedule to the runtime enumeration.
2596static OpenMPSchedType
2598 // only static is allowed for dist_schedule
2599 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2600}
2601
2603 bool Chunked) const {
2604 OpenMPSchedType Schedule =
2605 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2606 return Schedule == OMP_sch_static;
2607}
2608
2610 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2611 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2612 return Schedule == OMP_dist_sch_static;
2613}
2614
2616 bool Chunked) const {
2617 OpenMPSchedType Schedule =
2618 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2619 return Schedule == OMP_sch_static_chunked;
2620}
2621
2623 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2624 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2625 return Schedule == OMP_dist_sch_static_chunked;
2626}
2627
2629 OpenMPSchedType Schedule =
2630 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2631 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2632 return Schedule != OMP_sch_static;
2633}
2634
2635static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule,
2638 int Modifier = 0;
2639 switch (M1) {
2640 case OMPC_SCHEDULE_MODIFIER_monotonic:
2641 Modifier = OMP_sch_modifier_monotonic;
2642 break;
2643 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2644 Modifier = OMP_sch_modifier_nonmonotonic;
2645 break;
2646 case OMPC_SCHEDULE_MODIFIER_simd:
2647 if (Schedule == OMP_sch_static_chunked)
2648 Schedule = OMP_sch_static_balanced_chunked;
2649 break;
2652 break;
2653 }
2654 switch (M2) {
2655 case OMPC_SCHEDULE_MODIFIER_monotonic:
2656 Modifier = OMP_sch_modifier_monotonic;
2657 break;
2658 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2659 Modifier = OMP_sch_modifier_nonmonotonic;
2660 break;
2661 case OMPC_SCHEDULE_MODIFIER_simd:
2662 if (Schedule == OMP_sch_static_chunked)
2663 Schedule = OMP_sch_static_balanced_chunked;
2664 break;
2667 break;
2668 }
2669 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription.
2670 // If the static schedule kind is specified or if the ordered clause is
2671 // specified, and if the nonmonotonic modifier is not specified, the effect is
2672 // as if the monotonic modifier is specified. Otherwise, unless the monotonic
2673 // modifier is specified, the effect is as if the nonmonotonic modifier is
2674 // specified.
2675 if (CGM.getLangOpts().OpenMP >= 50 && Modifier == 0) {
2676 if (!(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static ||
2677 Schedule == OMP_sch_static_balanced_chunked ||
2678 Schedule == OMP_ord_static_chunked || Schedule == OMP_ord_static ||
2679 Schedule == OMP_dist_sch_static_chunked ||
2680 Schedule == OMP_dist_sch_static))
2681 Modifier = OMP_sch_modifier_nonmonotonic;
2682 }
2683 return Schedule | Modifier;
2684}
2685
2688 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2689 bool Ordered, const DispatchRTInput &DispatchValues) {
2690 if (!CGF.HaveInsertPoint())
2691 return;
2692 OpenMPSchedType Schedule = getRuntimeSchedule(
2693 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
2694 assert(Ordered ||
2695 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2696 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2697 Schedule != OMP_sch_static_balanced_chunked));
2698 // Call __kmpc_dispatch_init(
2699 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2700 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2701 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
2702
2703 // If the Chunk was not specified in the clause - use default value 1.
2704 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2705 : CGF.Builder.getIntN(IVSize, 1);
2706 llvm::Value *Args[] = {
2707 emitUpdateLocation(CGF, Loc),
2708 getThreadID(CGF, Loc),
2709 CGF.Builder.getInt32(addMonoNonMonoModifier(
2710 CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2711 DispatchValues.LB, // Lower
2712 DispatchValues.UB, // Upper
2713 CGF.Builder.getIntN(IVSize, 1), // Stride
2714 Chunk // Chunk
2715 };
2716 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2717}
2718
2720 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2721 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
2723 const CGOpenMPRuntime::StaticRTInput &Values) {
2724 if (!CGF.HaveInsertPoint())
2725 return;
2726
2727 assert(!Values.Ordered);
2728 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2729 Schedule == OMP_sch_static_balanced_chunked ||
2730 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2731 Schedule == OMP_dist_sch_static ||
2732 Schedule == OMP_dist_sch_static_chunked);
2733
2734 // Call __kmpc_for_static_init(
2735 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2736 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2737 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2738 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2739 llvm::Value *Chunk = Values.Chunk;
2740 if (Chunk == nullptr) {
2741 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2742 Schedule == OMP_dist_sch_static) &&
2743 "expected static non-chunked schedule");
2744 // If the Chunk was not specified in the clause - use default value 1.
2745 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2746 } else {
2747 assert((Schedule == OMP_sch_static_chunked ||
2748 Schedule == OMP_sch_static_balanced_chunked ||
2749 Schedule == OMP_ord_static_chunked ||
2750 Schedule == OMP_dist_sch_static_chunked) &&
2751 "expected static chunked schedule");
2752 }
2753 llvm::Value *Args[] = {
2754 UpdateLocation,
2755 ThreadId,
2756 CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1,
2757 M2)), // Schedule type
2758 Values.IL.getPointer(), // &isLastIter
2759 Values.LB.getPointer(), // &LB
2760 Values.UB.getPointer(), // &UB
2761 Values.ST.getPointer(), // &Stride
2762 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
2763 Chunk // Chunk
2764 };
2765 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2766}
2767
2769 SourceLocation Loc,
2770 OpenMPDirectiveKind DKind,
2771 const OpenMPScheduleTy &ScheduleKind,
2772 const StaticRTInput &Values) {
2773 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
2774 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
2775 assert(isOpenMPWorksharingDirective(DKind) &&
2776 "Expected loop-based or sections-based directive.");
2777 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
2779 ? OMP_IDENT_WORK_LOOP
2780 : OMP_IDENT_WORK_SECTIONS);
2781 llvm::Value *ThreadId = getThreadID(CGF, Loc);
2782 llvm::FunctionCallee StaticInitFunction =
2783 createForStaticInitFunction(Values.IVSize, Values.IVSigned, false);
2785 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2786 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
2787}
2788
2792 const CGOpenMPRuntime::StaticRTInput &Values) {
2793 OpenMPSchedType ScheduleNum =
2794 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
2795 llvm::Value *UpdatedLocation =
2796 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
2797 llvm::Value *ThreadId = getThreadID(CGF, Loc);
2798 llvm::FunctionCallee StaticInitFunction;
2799 bool isGPUDistribute =
2800 CGM.getLangOpts().OpenMPIsDevice &&
2801 (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX());
2802 StaticInitFunction = createForStaticInitFunction(
2803 Values.IVSize, Values.IVSigned, isGPUDistribute);
2804
2805 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2806 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2808}
2809
2811 SourceLocation Loc,
2812 OpenMPDirectiveKind DKind) {
2813 if (!CGF.HaveInsertPoint())
2814 return;
2815 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2816 llvm::Value *Args[] = {
2817 emitUpdateLocation(CGF, Loc,
2819 ? OMP_IDENT_WORK_DISTRIBUTE
2820 : isOpenMPLoopDirective(DKind)
2821 ? OMP_IDENT_WORK_LOOP
2822 : OMP_IDENT_WORK_SECTIONS),
2823 getThreadID(CGF, Loc)};
2825 if (isOpenMPDistributeDirective(DKind) && CGM.getLangOpts().OpenMPIsDevice &&
2826 (CGM.getTriple().isAMDGCN() || CGM.getTriple().isNVPTX()))
2827 CGF.EmitRuntimeCall(
2828 OMPBuilder.getOrCreateRuntimeFunction(
2829 CGM.getModule(), OMPRTL___kmpc_distribute_static_fini),
2830 Args);
2831 else
2832 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2833 CGM.getModule(), OMPRTL___kmpc_for_static_fini),
2834 Args);
2835}
2836
2838 SourceLocation Loc,
2839 unsigned IVSize,
2840 bool IVSigned) {
2841 if (!CGF.HaveInsertPoint())
2842 return;
2843 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2844 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2845 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2846}
2847
2849 SourceLocation Loc, unsigned IVSize,
2850 bool IVSigned, Address IL,
2851 Address LB, Address UB,
2852 Address ST) {
2853 // Call __kmpc_dispatch_next(
2854 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2855 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2856 // kmp_int[32|64] *p_stride);
2857 llvm::Value *Args[] = {
2858 emitUpdateLocation(CGF, Loc),
2859 getThreadID(CGF, Loc),
2860 IL.getPointer(), // &isLastIter
2861 LB.getPointer(), // &Lower
2862 UB.getPointer(), // &Upper
2863 ST.getPointer() // &Stride
2864 };
2865 llvm::Value *Call =
2866 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2867 return CGF.EmitScalarConversion(
2868 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
2869 CGF.getContext().BoolTy, Loc);
2870}
2871
2873 llvm::Value *NumThreads,
2874 SourceLocation Loc) {
2875 if (!CGF.HaveInsertPoint())
2876 return;
2877 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2878 llvm::Value *Args[] = {
2879 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2880 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2881 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2882 CGM.getModule(), OMPRTL___kmpc_push_num_threads),
2883 Args);
2884}
2885
2887 ProcBindKind ProcBind,
2888 SourceLocation Loc) {
2889 if (!CGF.HaveInsertPoint())
2890 return;
2891 assert(ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.");
2892 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2893 llvm::Value *Args[] = {
2894 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2895 llvm::ConstantInt::get(CGM.IntTy, unsigned(ProcBind), /*isSigned=*/true)};
2896 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2897 CGM.getModule(), OMPRTL___kmpc_push_proc_bind),
2898 Args);
2899}
2900
2902 SourceLocation Loc, llvm::AtomicOrdering AO) {
2903 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2904 OMPBuilder.createFlush(CGF.Builder);
2905 } else {
2906 if (!CGF.HaveInsertPoint())
2907 return;
2908 // Build call void __kmpc_flush(ident_t *loc)
2909 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2910 CGM.getModule(), OMPRTL___kmpc_flush),
2911 emitUpdateLocation(CGF, Loc));
2912 }
2913}
2914
2915namespace {
2916/// Indexes of fields for type kmp_task_t.
2917enum KmpTaskTFields {
2918 /// List of shared variables.
2919 KmpTaskTShareds,
2920 /// Task routine.
2921 KmpTaskTRoutine,
2922 /// Partition id for the untied tasks.
2923 KmpTaskTPartId,
2924 /// Function with call of destructors for private variables.
2925 Data1,
2926 /// Task priority.
2927 Data2,
2928 /// (Taskloops only) Lower bound.
2929 KmpTaskTLowerBound,
2930 /// (Taskloops only) Upper bound.
2931 KmpTaskTUpperBound,
2932 /// (Taskloops only) Stride.
2933 KmpTaskTStride,
2934 /// (Taskloops only) Is last iteration flag.
2935 KmpTaskTLastIter,
2936 /// (Taskloops only) Reduction data.
2937 KmpTaskTReductions,
2938};
2939} // anonymous namespace
2940
2942 // If we are in simd mode or there are no entries, we don't need to do
2943 // anything.
2944 if (CGM.getLangOpts().OpenMPSimd || OMPBuilder.OffloadInfoManager.empty())
2945 return;
2946
2947 llvm::OpenMPIRBuilder::EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
2948 [this](llvm::OpenMPIRBuilder::EmitMetadataErrorKind Kind,
2949 const llvm::TargetRegionEntryInfo &EntryInfo) -> void {
2950 SourceLocation Loc;
2951 if (Kind != llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR) {
2952 for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(),
2954 I != E; ++I) {
2955 if (I->getFirst()->getUniqueID().getDevice() == EntryInfo.DeviceID &&
2956 I->getFirst()->getUniqueID().getFile() == EntryInfo.FileID) {
2958 I->getFirst(), EntryInfo.Line, 1);
2959 break;
2960 }
2961 }
2962 }
2963 switch (Kind) {
2964 case llvm::OpenMPIRBuilder::EMIT_MD_TARGET_REGION_ERROR: {
2965 unsigned DiagID = CGM.getDiags().getCustomDiagID(
2966 DiagnosticsEngine::Error, "Offloading entry for target region in "
2967 "%0 is incorrect: either the "
2968 "address or the ID is invalid.");
2969 CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName;
2970 } break;
2971 case llvm::OpenMPIRBuilder::EMIT_MD_DECLARE_TARGET_ERROR: {
2972 unsigned DiagID = CGM.getDiags().getCustomDiagID(
2973 DiagnosticsEngine::Error, "Offloading entry for declare target "
2974 "variable %0 is incorrect: the "
2975 "address is invalid.");
2976 CGM.getDiags().Report(Loc, DiagID) << EntryInfo.ParentName;
2977 } break;
2978 case llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR: {
2979 unsigned DiagID = CGM.getDiags().getCustomDiagID(
2981 "Offloading entry for declare target variable is incorrect: the "
2982 "address is invalid.");
2983 CGM.getDiags().Report(DiagID);
2984 } break;
2985 }
2986 };
2987
2988 OMPBuilder.createOffloadEntriesAndInfoMetadata(ErrorReportFn);
2989}
2990
2991/// Loads all the offload entries information from the host IR
2992/// metadata.
2994 // If we are in target mode, load the metadata from the host IR. This code has
2995 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2996
2997 if (!CGM.getLangOpts().OpenMPIsDevice)
2998 return;
2999
3000 if (CGM.getLangOpts().OMPHostIRFile.empty())
3001 return;
3002
3003 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3004 if (auto EC = Buf.getError()) {
3005 CGM.getDiags().Report(diag::err_cannot_open_file)
3006 << CGM.getLangOpts().OMPHostIRFile << EC.message();
3007 return;
3008 }
3009
3010 llvm::LLVMContext C;
3011 auto ME = expectedToErrorOrAndEmitErrors(
3012 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3013
3014 if (auto EC = ME.getError()) {
3015 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3016 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
3017 CGM.getDiags().Report(DiagID)
3018 << CGM.getLangOpts().OMPHostIRFile << EC.message();
3019 return;
3020 }
3021
3022 OMPBuilder.loadOffloadInfoMetadata(*ME.get());
3023}
3024
3026 if (!KmpRoutineEntryPtrTy) {
3027 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3029 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3031 KmpRoutineEntryPtrQTy = C.getPointerType(
3032 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3034 }
3035}
3036
3037namespace {
3038struct PrivateHelpersTy {
3039 PrivateHelpersTy(const Expr *OriginalRef, const VarDecl *Original,
3040 const VarDecl *PrivateCopy, const VarDecl *PrivateElemInit)
3041 : OriginalRef(OriginalRef), Original(Original), PrivateCopy(PrivateCopy),
3042 PrivateElemInit(PrivateElemInit) {}
3043 PrivateHelpersTy(const VarDecl *Original) : Original(Original) {}
3044 const Expr *OriginalRef = nullptr;
3045 const VarDecl *Original = nullptr;
3046 const VarDecl *PrivateCopy = nullptr;
3047 const VarDecl *PrivateElemInit = nullptr;
3048 bool isLocalPrivate() const {
3049 return !OriginalRef && !PrivateCopy && !PrivateElemInit;
3050 }
3051};
3052typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3053} // anonymous namespace
3054
3055static bool isAllocatableDecl(const VarDecl *VD) {
3056 const VarDecl *CVD = VD->getCanonicalDecl();
3057 if (!CVD->hasAttr<OMPAllocateDeclAttr>())
3058 return false;
3059 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
3060 // Use the default allocation.
3061 return !(AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc &&
3062 !AA->getAllocator());
3063}
3064
3065static RecordDecl *
3067 if (!Privates.empty()) {
3068 ASTContext &C = CGM.getContext();
3069 // Build struct .kmp_privates_t. {
3070 // /* private vars */
3071 // };
3072 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
3073 RD->startDefinition();
3074 for (const auto &Pair : Privates) {
3075 const VarDecl *VD = Pair.second.Original;
3077 // If the private variable is a local variable with lvalue ref type,
3078 // allocate the pointer instead of the pointee type.
3079 if (Pair.second.isLocalPrivate()) {
3080 if (VD->getType()->isLValueReferenceType())
3081 Type = C.getPointerType(Type);
3082 if (isAllocatableDecl(VD))
3083 Type = C.getPointerType(Type);
3084 }
3086 if (VD->hasAttrs()) {
3087 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3088 E(VD->getAttrs().end());
3089 I != E; ++I)
3090 FD->addAttr(*I);
3091 }
3092 }
3093 RD->completeDefinition();
3094 return RD;
3095 }
3096 return nullptr;
3097}
3098
3099static RecordDecl *
3101 QualType KmpInt32Ty,
3102 QualType KmpRoutineEntryPointerQTy) {
3103 ASTContext &C = CGM.getContext();
3104 // Build struct kmp_task_t {
3105 // void * shareds;
3106 // kmp_routine_entry_t routine;
3107 // kmp_int32 part_id;
3108 // kmp_cmplrdata_t data1;
3109 // kmp_cmplrdata_t data2;
3110 // For taskloops additional fields:
3111 // kmp_uint64 lb;
3112 // kmp_uint64 ub;
3113 // kmp_int64 st;
3114 // kmp_int32 liter;
3115 // void * reductions;
3116 // };
3117 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3118 UD->startDefinition();
3119 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3120 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3121 UD->completeDefinition();
3122 QualType KmpCmplrdataTy = C.getRecordType(UD);
3123 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
3124 RD->startDefinition();
3125 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3126 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3127 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3128 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3129 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3130 if (isOpenMPTaskLoopDirective(Kind)) {
3131 QualType KmpUInt64Ty =
3132 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3133 QualType KmpInt64Ty =
3134 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3135 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3136 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3137 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3138 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3139 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3140 }
3141 RD->completeDefinition();
3142 return RD;
3143}
3144
3145static RecordDecl *
3147 ArrayRef<PrivateDataTy> Privates) {
3148 ASTContext &C = CGM.getContext();
3149 // Build struct kmp_task_t_with_privates {
3150 // kmp_task_t task_data;
3151 // .kmp_privates_t. privates;
3152 // };
3153 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3154 RD->startDefinition();
3155 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3156 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
3157 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3158 RD->completeDefinition();
3159 return RD;
3160}
3161
3162/// Emit a proxy function which accepts kmp_task_t as the second
3163/// argument.
3164/// \code
3165/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3166/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3167/// For taskloops:
3168/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3169/// tt->reductions, tt->shareds);
3170/// return 0;
3171/// }
3172/// \endcode
3173static llvm::Function *
3175 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3176 QualType KmpTaskTWithPrivatesPtrQTy,
3177 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3178 QualType SharedsPtrTy, llvm::Function *TaskFunction,
3179 llvm::Value *TaskPrivatesMap) {
3180 ASTContext &C = CGM.getContext();
3181 FunctionArgList Args;
3182 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3184 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3185 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3187 Args.push_back(&GtidArg);
3188 Args.push_back(&TaskTypeArg);
3189 const auto &TaskEntryFnInfo =
3190 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3191 llvm::FunctionType *TaskEntryTy =
3192 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3193 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
3194 auto *TaskEntry = llvm::Function::Create(
3195 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
3196 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
3197 TaskEntry->setDoesNotRecurse();
3198 CodeGenFunction CGF(CGM);
3199 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
3200 Loc, Loc);
3201
3202 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3203 // tt,
3204 // For taskloops:
3205 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3206 // tt->task_data.shareds);
3207 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
3208 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3209 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3210 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3211 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3212 const auto *KmpTaskTWithPrivatesQTyRD =
3213 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3214 LValue Base =
3215 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3216 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3217 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3218 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3219 llvm::Value *PartidParam = PartIdLVal.getPointer(CGF);
3220
3221 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3222 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3223 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3224 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
3225 CGF.ConvertTypeForMem(SharedsPtrTy));
3226
3227 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3228 llvm::Value *PrivatesParam;
3229 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3230 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3231 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3232 PrivatesLVal.getPointer(CGF), CGF.VoidPtrTy);
3233 } else {
3234 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3235 }
3236
3237 llvm::Value *CommonArgs[] = {
3238 GtidParam, PartidParam, PrivatesParam, TaskPrivatesMap,
3239 CGF.Builder
3241 CGF.VoidPtrTy, CGF.Int8Ty)
3242 .getPointer()};
3243 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3244 std::end(CommonArgs));
3245 if (isOpenMPTaskLoopDirective(Kind)) {
3246 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3247 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3248 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
3249 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3250 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3251 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
3252 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3253 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
3254 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
3255 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3256 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3257 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
3258 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3259 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
3260 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
3261 CallArgs.push_back(LBParam);
3262 CallArgs.push_back(UBParam);
3263 CallArgs.push_back(StParam);
3264 CallArgs.push_back(LIParam);
3265 CallArgs.push_back(RParam);
3266 }
3267 CallArgs.push_back(SharedsParam);
3268
3269 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3270 CallArgs);
3271 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3272 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3273 CGF.FinishFunction();
3274 return TaskEntry;
3275}
3276
3278 SourceLocation Loc,
3279 QualType KmpInt32Ty,
3280 QualType KmpTaskTWithPrivatesPtrQTy,
3281 QualType KmpTaskTWithPrivatesQTy) {
3282 ASTContext &C = CGM.getContext();
3283 FunctionArgList Args;
3284 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3286 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3287 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3289 Args.push_back(&GtidArg);
3290 Args.push_back(&TaskTypeArg);
3291 const auto &DestructorFnInfo =
3292 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3293 llvm::FunctionType *DestructorFnTy =
3294 CGM.getTypes().GetFunctionType(DestructorFnInfo);
3295 std::string Name =
3296 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
3297 auto *DestructorFn =
3298 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3299 Name, &CGM.getModule());
3300 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
3301 DestructorFnInfo);
3302 DestructorFn->setDoesNotRecurse();
3303 CodeGenFunction CGF(CGM);
3304 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3305 Args, Loc, Loc);
3306
3308 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3309 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3310 const auto *KmpTaskTWithPrivatesQTyRD =
3311 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3312 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3313 Base = CGF.EmitLValueForField(Base, *FI);
3314 for (const auto *Field :
3315 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3316 if (QualType::DestructionKind DtorKind =
3317 Field->getType().isDestructedType()) {
3318 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
3319 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(CGF), Field->getType());
3320 }
3321 }
3322 CGF.FinishFunction();
3323 return DestructorFn;
3324}
3325
3326/// Emit a privates mapping function for correct handling of private and
3327/// firstprivate variables.
3328/// \code
3329/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3330/// **noalias priv1,..., <tyn> **noalias privn) {
3331/// *priv1 = &.privates.priv1;
3332/// ...;
3333/// *privn = &.privates.privn;
3334/// }
3335/// \endcode
3336static llvm::Value *
3338 const OMPTaskDataTy &Data, QualType PrivatesQTy,
3339 ArrayRef<PrivateDataTy> Privates) {
3340 ASTContext &C = CGM.getContext();
3341 FunctionArgList Args;
3342 ImplicitParamDecl TaskPrivatesArg(
3343 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3344 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3346 Args.push_back(&TaskPrivatesArg);
3347 llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, unsigned> PrivateVarsPos;
3348 unsigned Counter = 1;
3349 for (const Expr *E : Data.PrivateVars) {
3350 Args.push_back(ImplicitParamDecl::Create(
3351 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3352 C.getPointerType(C.getPointerType(E->getType()))
3353 .withConst()
3354 .withRestrict(),
3356 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3357 PrivateVarsPos[VD] = Counter;
3358 ++Counter;
3359 }
3360 for (const Expr *E : Data.FirstprivateVars) {
3361 Args.push_back(ImplicitParamDecl::Create(
3362 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3363 C.getPointerType(C.getPointerType(E->getType()))
3364 .withConst()
3365 .withRestrict(),
3367 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3368 PrivateVarsPos[VD] = Counter;
3369 ++Counter;
3370 }
3371 for (const Expr *E : Data.LastprivateVars) {
3372 Args.push_back(ImplicitParamDecl::Create(
3373 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3374 C.getPointerType(C.getPointerType(E->getType()))
3375 .withConst()
3376 .withRestrict(),
3378 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3379 PrivateVarsPos[VD] = Counter;
3380 ++Counter;
3381 }
3382 for (const VarDecl *VD : Data.PrivateLocals) {
3384 if (VD->getType()->isLValueReferenceType())
3385 Ty = C.getPointerType(Ty);
3386 if (isAllocatableDecl(VD))
3387 Ty = C.getPointerType(Ty);
3388 Args.push_back(ImplicitParamDecl::Create(
3389 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3390 C.getPointerType(C.getPointerType(Ty)).withConst().withRestrict(),
3392 PrivateVarsPos[VD] = Counter;
3393 ++Counter;
3394 }
3395 const auto &TaskPrivatesMapFnInfo =
3396 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3397 llvm::FunctionType *TaskPrivatesMapTy =
3398 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3399 std::string Name =
3400 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
3401 auto *TaskPrivatesMap = llvm::Function::Create(
3402 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
3403 &CGM.getModule());
3404 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
3405 TaskPrivatesMapFnInfo);
3406 if (CGM.getLangOpts().Optimize) {
3407 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3408 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
3409 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3410 }
3411 CodeGenFunction CGF(CGM);
3412 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3413 TaskPrivatesMapFnInfo, Args, Loc, Loc);
3414
3415 // *privi = &.privates.privi;
3417 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3418 TaskPrivatesArg.getType()->castAs<PointerType>());
3419 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3420 Counter = 0;
3421 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
3422 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
3423 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3424 LValue RefLVal =
3425 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3426 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3427 RefLVal.getAddress(CGF), RefLVal.getType()->castAs<PointerType>());
3428 CGF.EmitStoreOfScalar(FieldLVal.getPointer(CGF), RefLoadLVal);
3429 ++Counter;
3430 }
3431 CGF.FinishFunction();
3432 return TaskPrivatesMap;
3433}
3434
3435/// Emit initialization for private variables in task-based directives.
3437 const OMPExecutableDirective &D,
3438 Address KmpTaskSharedsPtr, LValue TDBase,
3439 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3440 QualType SharedsTy, QualType SharedsPtrTy,
3441 const OMPTaskDataTy &Data,
3442 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3443 ASTContext &C = CGF.getContext();
3444 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3445 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3447 ? OMPD_taskloop
3448 : OMPD_task;
3449 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
3450 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
3451 LValue SrcBase;
3452 bool IsTargetTask =
3455 // For target-based directives skip 4 firstprivate arrays BasePointersArray,
3456 // PointersArray, SizesArray, and MappersArray. The original variables for
3457 // these arrays are not captured and we get their addresses explicitly.
3458 if ((!IsTargetTask && !Data.FirstprivateVars.empty() && ForDup) ||
3459 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
3460 SrcBase = CGF.MakeAddrLValue(
3462 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy),
3463 CGF.ConvertTypeForMem(SharedsTy)),
3464 SharedsTy);
3465 }
3466 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3467 for (const PrivateDataTy &Pair : Privates) {
3468 // Do not initialize private locals.
3469 if (Pair.second.isLocalPrivate()) {
3470 ++FI;
3471 continue;
3472 }
3473 const VarDecl *VD = Pair.second.PrivateCopy;
3474 const Expr *Init = VD->getAnyInitializer();
3475 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3476 !CGF.isTrivialInitializer(Init)))) {
3477 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3478 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
3479 const VarDecl *OriginalVD = Pair.second.Original;
3480 // Check if the variable is the target-based BasePointersArray,
3481 // PointersArray, SizesArray, or MappersArray.
3482 LValue SharedRefLValue;
3483 QualType Type = PrivateLValue.getType();
3484 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
3485 if (IsTargetTask && !SharedField) {
3486 assert(isa<ImplicitParamDecl>(OriginalVD) &&
3487 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
3488 cast<CapturedDecl>(OriginalVD->getDeclContext())
3489 ->getNumParams() == 0 &&
3490 isa<TranslationUnitDecl>(
3491 cast<CapturedDecl>(OriginalVD->getDeclContext())
3492 ->getDeclContext()) &&
3493 "Expected artificial target data variable.");
3494 SharedRefLValue =
3495 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
3496 } else if (ForDup) {
3497 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3498 SharedRefLValue = CGF.MakeAddrLValue(
3499 SharedRefLValue.getAddress(CGF).withAlignment(
3500 C.getDeclAlign(OriginalVD)),
3501 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
3502 SharedRefLValue.getTBAAInfo());
3503 } else if (CGF.LambdaCaptureFields.count(
3504 Pair.second.Original->getCanonicalDecl()) > 0 ||
3505 isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl)) {
3506 SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3507 } else {
3508 // Processing for implicitly captured variables.
3509 InlinedOpenMPRegionRAII Region(
3510 CGF, [](CodeGenFunction &, PrePostActionTy &) {}, OMPD_unknown,
3511 /*HasCancel=*/false, /*NoInheritance=*/true);
3512 SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3513 }
3514 if (Type->isArrayType()) {
3515 // Initialize firstprivate array.
3516 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3517 // Perform simple memcpy.
3518 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
3519 } else {
3520 // Initialize firstprivate array using element-by-element
3521 // initialization.
3523 PrivateLValue.getAddress(CGF), SharedRefLValue.getAddress(CGF),
3524 Type,
3525 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3526 Address SrcElement) {
3527 // Clean up any temporaries needed by the initialization.
3528 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3529 InitScope.addPrivate(Elem, SrcElement);
3530 (void)InitScope.Privatize();
3531 // Emit initialization for single element.
3532 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3533 CGF, &CapturesInfo);
3534 CGF.EmitAnyExprToMem(Init, DestElement,
3535 Init->getType().getQualifiers(),
3536 /*IsInitializer=*/false);
3537 });
3538 }
3539 } else {
3540 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3541 InitScope.addPrivate(Elem, SharedRefLValue.getAddress(CGF));
3542 (void)InitScope.Privatize();
3543 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3544 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3545 /*capturedByInit=*/false);
3546 }
3547 } else {
3548 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3549 }
3550 }
3551 ++FI;
3552 }
3553}
3554
3555/// Check if duplication function is required for taskloops.
3557 ArrayRef<PrivateDataTy> Privates) {
3558 bool InitRequired = false;
3559 for (const PrivateDataTy &Pair : Privates) {
3560 if (Pair.second.isLocalPrivate())
3561 continue;
3562 const VarDecl *VD = Pair.second.PrivateCopy;
3563 const Expr *Init = VD->getAnyInitializer();
3564 InitRequired = InitRequired || (isa_and_nonnull<CXXConstructExpr>(Init) &&
3565 !CGF.isTrivialInitializer(Init));
3566 if (InitRequired)
3567 break;
3568 }
3569 return InitRequired;
3570}
3571
3572
3573/// Emit task_dup function (for initialization of
3574/// private/firstprivate/lastprivate vars and last_iter flag)
3575/// \code
3576/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3577/// lastpriv) {
3578/// // setup lastprivate flag
3579/// task_dst->last = lastpriv;
3580/// // could be constructor calls here...
3581/// }
3582/// \endcode
3583static llvm::Value *
3585 const OMPExecutableDirective &D,
3586 QualType KmpTaskTWithPrivatesPtrQTy,
3587 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3588 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3589 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3590 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3591 ASTContext &C = CGM.getContext();
3592 FunctionArgList Args;
3593 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3594 KmpTaskTWithPrivatesPtrQTy,
3596 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3597 KmpTaskTWithPrivatesPtrQTy,
3599 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3601 Args.push_back(&DstArg);
3602 Args.push_back(&SrcArg);
3603 Args.push_back(&LastprivArg);
3604 const auto &TaskDupFnInfo =
3605 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3606 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3607 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
3608 auto *TaskDup = llvm::Function::Create(
3609 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
3610 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
3611 TaskDup->setDoesNotRecurse();
3612 CodeGenFunction CGF(CGM);
3613 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
3614 Loc);
3615
3616 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3617 CGF.GetAddrOfLocalVar(&DstArg),
3618 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3619 // task_dst->liter = lastpriv;
3620 if (WithLastIter) {
3621 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3623 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3624 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3625 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3626 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3627 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3628 }
3629
3630 // Emit initial values for private copies (if any).
3631 assert(!Privates.empty());
3632 Address KmpTaskSharedsPtr = Address::invalid();
3633 if (!Data.FirstprivateVars.empty()) {
3634 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3635 CGF.GetAddrOfLocalVar(&SrcArg),
3636 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3638 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3639 KmpTaskSharedsPtr = Address(
3641 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3642 KmpTaskTShareds)),
3643 Loc),
3644 CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy));
3645 }
3646 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3647 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
3648 CGF.FinishFunction();
3649 return TaskDup;
3650}
3651
3652/// Checks if destructor function is required to be generated.
3653/// \return true if cleanups are required, false otherwise.
3654static bool
3655checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3656 ArrayRef<PrivateDataTy> Privates) {
3657 for (const PrivateDataTy &P : Privates) {
3658 if (P.second.isLocalPrivate())
3659 continue;
3660 QualType Ty = P.second.Original->getType().getNonReferenceType();
3661 if (Ty.isDestructedType())
3662 return true;
3663 }
3664 return false;
3665}
3666
3667namespace {
3668/// Loop generator for OpenMP iterator expression.
3669class OMPIteratorGeneratorScope final
3670 : public CodeGenFunction::OMPPrivateScope {
3671 CodeGenFunction &CGF;
3672 const OMPIteratorExpr *E = nullptr;
3675 OMPIteratorGeneratorScope() = delete;
3676 OMPIteratorGeneratorScope(OMPIteratorGeneratorScope &) = delete;
3677
3678public:
3679 OMPIteratorGeneratorScope(CodeGenFunction &CGF, const OMPIteratorExpr *E)
3680 : CodeGenFunction::OMPPrivateScope(CGF), CGF(CGF), E(E) {
3681 if (!E)
3682 return;
3684 for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) {
3685 Uppers.push_back(CGF.EmitScalarExpr(E->getHelper(I).Upper));
3686 const auto *VD = cast<VarDecl>(E->getIteratorDecl(I));
3687 addPrivate(VD, CGF.CreateMemTemp(VD->getType(), VD->getName()));
3688 const OMPIteratorHelperData &HelperData = E->getHelper(I);
3689 addPrivate(
3690 HelperData.CounterVD,
3691 CGF.CreateMemTemp(HelperData.CounterVD->getType(), "counter.addr"));
3692 }
3693 Privatize();
3694
3695 for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) {
3696 const OMPIteratorHelperData &HelperData = E->getHelper(I);
3697 LValue CLVal =
3698 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(HelperData.CounterVD),
3699 HelperData.CounterVD->getType());
3700 // Counter = 0;
3702 llvm::ConstantInt::get(CLVal.getAddress(CGF).getElementType(), 0),
3703 CLVal);
3704 CodeGenFunction::JumpDest &ContDest =
3705 ContDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.cont"));
3706 CodeGenFunction::JumpDest &ExitDest =
3707 ExitDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.exit"));
3708 // N = <number-of_iterations>;
3709 llvm::Value *N = Uppers[I];
3710 // cont:
3711 // if (Counter < N) goto body; else goto exit;
3712 CGF.EmitBlock(ContDest.getBlock());
3713 auto *CVal =
3714 CGF.EmitLoadOfScalar(CLVal, HelperData.CounterVD->getLocation());
3715 llvm::Value *Cmp =
3717 ? CGF.Builder.CreateICmpSLT(CVal, N)
3718 : CGF.Builder.CreateICmpULT(CVal, N);
3719 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("iter.body");
3720 CGF.Builder.CreateCondBr(Cmp, BodyBB, ExitDest.getBlock());
3721 // body:
3722 CGF.EmitBlock(BodyBB);
3723 // Iteri = Begini + Counter * Stepi;
3724 CGF.EmitIgnoredExpr(HelperData.Update);
3725 }
3726 }
3727 ~OMPIteratorGeneratorScope() {
3728 if (!E)
3729 return;
3730 for (unsigned I = E->numOfIterators(); I > 0; --I) {
3731 // Counter = Counter + 1;
3732 const OMPIteratorHelperData &HelperData = E->getHelper(I - 1);
3733 CGF.EmitIgnoredExpr(HelperData.CounterUpdate);
3734 // goto cont;
3735 CGF.EmitBranchThroughCleanup(ContDests[I - 1]);
3736 // exit:
3737 CGF.EmitBlock(ExitDests[I - 1].getBlock(), /*IsFinished=*/I == 1);
3738 }
3739 }
3740};
3741} // namespace
3742
3743static std::pair<llvm::Value *, llvm::Value *>
3745 const auto *OASE = dyn_cast<OMPArrayShapingExpr>(E);
3746 llvm::Value *Addr;
3747 if (OASE) {
3748 const Expr *Base = OASE->getBase();
3749 Addr = CGF.EmitScalarExpr(Base);
3750 } else {
3751 Addr = CGF.EmitLValue(E).getPointer(CGF);
3752 }
3753 llvm::Value *SizeVal;
3754 QualType Ty = E->getType();
3755 if (OASE) {
3756 SizeVal = CGF.getTypeSize(OASE->getBase()->getType()->getPointeeType());
3757 for (const Expr *SE : OASE->getDimensions()) {
3758 llvm::Value *Sz = CGF.EmitScalarExpr(SE);
3759 Sz = CGF.EmitScalarConversion(
3760 Sz, SE->getType(), CGF.getContext().getSizeType(), SE->getExprLoc());
3761 SizeVal = CGF.Builder.CreateNUWMul(SizeVal, Sz);
3762 }
3763 } else if (const auto *ASE =
3764 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3765 LValue UpAddrLVal =
3766 CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false);
3767 Address UpAddrAddress = UpAddrLVal.getAddress(CGF);
3768 llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32(
3769 UpAddrAddress.getElementType(), UpAddrAddress.getPointer(), /*Idx0=*/1);
3770 llvm::Value *LowIntPtr = CGF.Builder.CreatePtrToInt(Addr, CGF.SizeTy);
3771 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGF.SizeTy);
3772 SizeVal = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3773 } else {
3774 SizeVal = CGF.getTypeSize(Ty);
3775 }
3776 return std::make_pair(Addr, SizeVal);
3777}
3778
3779/// Builds kmp_depend_info, if it is not built yet, and builds flags type.
3780static void getKmpAffinityType(ASTContext &C, QualType &KmpTaskAffinityInfoTy) {
3781 QualType FlagsTy = C.getIntTypeForBitwidth(32, /*Signed=*/false);
3782 if (KmpTaskAffinityInfoTy.isNull()) {
3783 RecordDecl *KmpAffinityInfoRD =
3784 C.buildImplicitRecord("kmp_task_affinity_info_t");
3785 KmpAffinityInfoRD->startDefinition();
3786 addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getIntPtrType());
3787 addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getSizeType());
3788 addFieldToRecordDecl(C, KmpAffinityInfoRD, FlagsTy);
3789 KmpAffinityInfoRD->completeDefinition();
3790 KmpTaskAffinityInfoTy = C.getRecordType(KmpAffinityInfoRD);
3791 }
3792}
3793
3796 const OMPExecutableDirective &D,
3797 llvm::Function *TaskFunction, QualType SharedsTy,
3798 Address Shareds, const OMPTaskDataTy &Data) {
3801 // Aggregate privates and sort them by the alignment.
3802 const auto *I = Data.PrivateCopies.begin();
3803 for (const Expr *E : Data.PrivateVars) {
3804 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3805 Privates.emplace_back(
3806 C.getDeclAlign(VD),
3807 PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3808 /*PrivateElemInit=*/nullptr));
3809 ++I;
3810 }
3811 I = Data.FirstprivateCopies.begin();
3812 const auto *IElemInitRef = Data.FirstprivateInits.begin();
3813 for (const Expr *E : Data.FirstprivateVars) {
3814 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3815 Privates.emplace_back(
3816 C.getDeclAlign(VD),
3817 PrivateHelpersTy(
3818 E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3819 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
3820 ++I;
3821 ++IElemInitRef;
3822 }
3823 I = Data.LastprivateCopies.begin();
3824 for (const Expr *E : Data.LastprivateVars) {
3825 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3826 Privates.emplace_back(
3827 C.getDeclAlign(VD),
3828 PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3829 /*PrivateElemInit=*/nullptr));
3830 ++I;
3831 }
3832 for (const VarDecl *VD : Data.PrivateLocals) {
3833 if (isAllocatableDecl(VD))
3834 Privates.emplace_back(CGM.getPointerAlign(), PrivateHelpersTy(VD));
3835 else
3836 Privates.emplace_back(C.getDeclAlign(VD), PrivateHelpersTy(VD));
3837 }
3838 llvm::stable_sort(Privates,
3839 [](const PrivateDataTy &L, const PrivateDataTy &R) {
3840 return L.first > R.first;
3841 });
3842 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3843 // Build type kmp_routine_entry_t (if not built yet).
3844 emitKmpRoutineEntryT(KmpInt32Ty);
3845 // Build type kmp_task_t (if not built yet).
3849 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3850 }
3852 } else {
3853 assert((D.getDirectiveKind() == OMPD_task ||
3856 "Expected taskloop, task or target directive");
3857 if (SavedKmpTaskTQTy.isNull()) {
3859 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3860 }
3862 }
3863 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3864 // Build particular struct kmp_task_t for the given task.
3865 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
3867 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3868 QualType KmpTaskTWithPrivatesPtrQTy =
3869 C.getPointerType(KmpTaskTWithPrivatesQTy);
3870 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3871 llvm::Type *KmpTaskTWithPrivatesPtrTy =
3872 KmpTaskTWithPrivatesTy->getPointerTo();
3873 llvm::Value *KmpTaskTWithPrivatesTySize =
3874 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3875 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3876
3877 // Emit initial values for private copies (if any).
3878 llvm::Value *TaskPrivatesMap = nullptr;
3879 llvm::Type *TaskPrivatesMapTy =
3880 std::next(TaskFunction->arg_begin(), 3)->getType();
3881 if (!Privates.empty()) {
3882 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3883 TaskPrivatesMap =
3884 emitTaskPrivateMappingFunction(CGM, Loc, Data, FI->getType(), Privates);
3885 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3886 TaskPrivatesMap, TaskPrivatesMapTy);
3887 } else {
3888 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3889 cast<llvm::PointerType>(TaskPrivatesMapTy));
3890 }
3891 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3892 // kmp_task_t *tt);
3893 llvm::Function *TaskEntry = emitProxyTaskFunction(
3894 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3895 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3896 TaskPrivatesMap);
3897
3898 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3899 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3900 // kmp_routine_entry_t *task_entry);
3901 // Task flags. Format is taken from
3902 // https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h,
3903 // description of kmp_tasking_flags struct.
3904 enum {
3905 TiedFlag = 0x1,
3906 FinalFlag = 0x2,
3907 DestructorsFlag = 0x8,
3908 PriorityFlag = 0x20,
3909 DetachableFlag = 0x40,
3910 };
3911 unsigned Flags = Data.Tied ? TiedFlag : 0;
3912 bool NeedsCleanup = false;
3913 if (!Privates.empty()) {
3914 NeedsCleanup =
3915 checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD, Privates);
3916 if (NeedsCleanup)
3917 Flags = Flags | DestructorsFlag;
3918 }
3919 if (Data.Priority.getInt())
3920 Flags = Flags | PriorityFlag;
3922 Flags = Flags | DetachableFlag;
3923 llvm::Value *TaskFlags =
3924 Data.Final.getPointer()
3925 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
3926 CGF.Builder.getInt32(FinalFlag),
3927 CGF.Builder.getInt32(/*C=*/0))
3928 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
3929 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3930 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3932 getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize,
3934 TaskEntry, KmpRoutineEntryPtrTy)};
3935 llvm::Value *NewTask;
3937 // Check if we have any device clause associated with the directive.
3938 const Expr *Device = nullptr;
3939 if (auto *C = D.getSingleClause<OMPDeviceClause>())
3940 Device = C->getDevice();
3941 // Emit device ID if any otherwise use default value.
3942 llvm::Value *DeviceID;
3943 if (Device)
3944 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
3945 CGF.Int64Ty, /*isSigned=*/true);
3946 else
3947 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
3948 AllocArgs.push_back(DeviceID);
3949 NewTask = CGF.EmitRuntimeCall(
3950 OMPBuilder.getOrCreateRuntimeFunction(
3951 CGM.getModule(), OMPRTL___kmpc_omp_target_task_alloc),
3952 AllocArgs);
3953 } else {
3954 NewTask =
3955 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
3956 CGM.getModule(), OMPRTL___kmpc_omp_task_alloc),
3957 AllocArgs);
3958 }
3959 // Emit detach clause initialization.
3960 // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid,
3961 // task_descriptor);
3962 if (const auto *DC = D.getSingleClause<OMPDetachClause>()) {
3963 const Expr *Evt = DC->getEventHandler()->IgnoreParenImpCasts();
3964 LValue EvtLVal = CGF.EmitLValue(Evt);
3965
3966 // Build kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref,
3967 // int gtid, kmp_task_t *task);
3968 llvm::Value *Loc = emitUpdateLocation(CGF, DC->getBeginLoc());
3969 llvm::Value *Tid = getThreadID(CGF, DC->getBeginLoc());
3970 Tid = CGF.Builder.CreateIntCast(Tid, CGF.IntTy, /*isSigned=*/false);
3971 llvm::Value *EvtVal = CGF.EmitRuntimeCall(
3972 OMPBuilder.getOrCreateRuntimeFunction(
3973 CGM.getModule(), OMPRTL___kmpc_task_allow_completion_event),
3974 {Loc, Tid, NewTask});
3975 EvtVal = CGF.EmitScalarConversion(EvtVal, C.VoidPtrTy, Evt->getType(),
3976 Evt->getExprLoc());
3977 CGF.EmitStoreOfScalar(EvtVal, EvtLVal);
3978 }
3979 // Process affinity clauses.
3981 // Process list of affinity data.
3983 Address AffinitiesArray = Address::invalid();
3984 // Calculate number of elements to form the array of affinity data.
3985 llvm::Value *NumOfElements = nullptr;
3986 unsigned NumAffinities = 0;
3987 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
3988 if (const Expr *Modifier = C->getModifier()) {
3989 const auto *IE = cast<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts());
3990 for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) {
3991 llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
3992 Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false);
3993 NumOfElements =
3994 NumOfElements ? CGF.Builder.CreateNUWMul(NumOfElements, Sz) : Sz;
3995 }
3996 } else {
3997 NumAffinities += C->varlist_size();
3998 }
3999 }
4001 // Fields ids in kmp_task_affinity_info record.
4002 enum RTLAffinityInfoFieldsTy { BaseAddr, Len, Flags };
4003
4004 QualType KmpTaskAffinityInfoArrayTy;
4005 if (NumOfElements) {
4006 NumOfElements = CGF.Builder.CreateNUWAdd(
4007 llvm::ConstantInt::get(CGF.SizeTy, NumAffinities), NumOfElements);
4008 auto *OVE = new (C) OpaqueValueExpr(
4009 Loc,
4010 C.getIntTypeForBitwidth(C.getTypeSize(C.getSizeType()), /*Signed=*/0),
4011 VK_PRValue);
4012 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
4013 RValue::get(NumOfElements));
4014 KmpTaskAffinityInfoArrayTy =
4015 C.getVariableArrayType(KmpTaskAffinityInfoTy, OVE, ArrayType::Normal,
4016 /*IndexTypeQuals=*/0, SourceRange(Loc, Loc));
4017 // Properly emit variable-sized array.
4018 auto *PD = ImplicitParamDecl::Create(C, KmpTaskAffinityInfoArrayTy,
4020 CGF.EmitVarDecl(*PD);
4021 AffinitiesArray = CGF.GetAddrOfLocalVar(PD);
4022 NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
4023 /*isSigned=*/false);
4024 } else {
4025 KmpTaskAffinityInfoArrayTy = C.getConstantArrayType(
4027 llvm::APInt(C.getTypeSize(C.getSizeType()), NumAffinities), nullptr,
4028 ArrayType::Normal, /*IndexTypeQuals=*/0);
4029 AffinitiesArray =
4030 CGF.CreateMemTemp(KmpTaskAffinityInfoArrayTy, ".affs.arr.addr");
4031 AffinitiesArray = CGF.Builder.CreateConstArrayGEP(AffinitiesArray, 0);
4032 NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumAffinities,
4033 /*isSigned=*/false);
4034 }
4035
4036 const auto *KmpAffinityInfoRD = KmpTaskAffinityInfoTy->getAsRecordDecl();
4037 // Fill array by elements without iterators.
4038 unsigned Pos = 0;
4039 bool HasIterator = false;
4040 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4041 if (C->getModifier()) {
4042 HasIterator = true;
4043 continue;
4044 }
4045 for (const Expr *E : C->varlists()) {
4046 llvm::Value *Addr;
4047 llvm::Value *Size;
4048 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4049 LValue Base =
4050 CGF.MakeAddrLValue(CGF.Builder.CreateConstGEP(AffinitiesArray, Pos),
4052 // affs[i].base_addr = &<Affinities[i].second>;
4053 LValue BaseAddrLVal = CGF.EmitLValueForField(
4054 Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4055 CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4056 BaseAddrLVal);
4057 // affs[i].len = sizeof(<Affinities[i].second>);
4058 LValue LenLVal = CGF.EmitLValueForField(
4059 Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4060 CGF.EmitStoreOfScalar(Size, LenLVal);
4061 ++Pos;
4062 }
4063 }
4064 LValue PosLVal;
4065 if (HasIterator) {
4066 PosLVal = CGF.MakeAddrLValue(
4067 CGF.CreateMemTemp(C.getSizeType(), "affs.counter.addr"),
4068 C.getSizeType());
4069 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4070 }
4071 // Process elements with iterators.
4072 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4073 const Expr *Modifier = C->getModifier();
4074 if (!Modifier)
4075 continue;
4076 OMPIteratorGeneratorScope IteratorScope(
4077 CGF, cast_or_null<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts()));
4078 for (const Expr *E : C->varlists()) {
4079 llvm::Value *Addr;
4080 llvm::Value *Size;
4081 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4082 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4084 CGF.Builder.CreateGEP(AffinitiesArray, Idx), KmpTaskAffinityInfoTy);
4085 // affs[i].base_addr = &<Affinities[i].second>;
4086 LValue BaseAddrLVal = CGF.EmitLValueForField(
4087 Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4088 CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4089 BaseAddrLVal);
4090 // affs[i].len = sizeof(<Affinities[i].second>);
4091 LValue LenLVal = CGF.EmitLValueForField(
4092 Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4093 CGF.EmitStoreOfScalar(Size, LenLVal);
4094 Idx = CGF.Builder.CreateNUWAdd(
4095 Idx, llvm::ConstantInt::get(Idx->getType(), 1));
4096 CGF.EmitStoreOfScalar(Idx, PosLVal);
4097 }
4098 }
4099 // Call to kmp_int32 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref,
4100 // kmp_int32 gtid, kmp_task_t *new_task, kmp_int32
4101 // naffins, kmp_task_affinity_info_t *affin_list);
4102 llvm::Value *LocRef = emitUpdateLocation(CGF, Loc);
4103 llvm::Value *GTid = getThreadID(CGF, Loc);
4104 llvm::Value *AffinListPtr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4105 AffinitiesArray.getPointer(), CGM.VoidPtrTy);
4106 // FIXME: Emit the function and ignore its result for now unless the
4107 // runtime function is properly implemented.
4108 (void)CGF.EmitRuntimeCall(
4109 OMPBuilder.getOrCreateRuntimeFunction(
4110 CGM.getModule(), OMPRTL___kmpc_omp_reg_task_with_affinity),
4111 {LocRef, GTid, NewTask, NumOfElements, AffinListPtr});
4112 }
4113 llvm::Value *NewTaskNewTaskTTy =
4115 NewTask, KmpTaskTWithPrivatesPtrTy);
4116 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4117 KmpTaskTWithPrivatesQTy);
4118 LValue TDBase =
4119 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4120 // Fill the data in the resulting kmp_task_t record.
4121 // Copy shareds if there are any.
4122 Address KmpTaskSharedsPtr = Address::invalid();
4123 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
4124 KmpTaskSharedsPtr = Address(
4125 CGF.EmitLoadOfScalar(
4127 TDBase,
4128 *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
4129 Loc),
4130 CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy));
4131 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4132 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4133 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
4134 }
4135 // Emit initial values for private copies (if any).
4137 if (!Privates.empty()) {
4138 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4139 SharedsTy, SharedsPtrTy, Data, Privates,
4140 /*ForDup=*/false);
4142 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4143 Result.TaskDupFn = emitTaskDupFunction(
4144 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4145 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4146 /*WithLastIter=*/!Data.LastprivateVars.empty());
4147 }
4148 }
4149 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4150 enum { Priority = 0, Destructors = 1 };
4151 // Provide pointer to function with destructors for privates.
4152 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4153 const RecordDecl *KmpCmplrdataUD =
4154 (*FI)->getType()->getAsUnionType()->getDecl();
4155 if (NeedsCleanup) {
4156 llvm::Value *DestructorFn = emitDestructorsFunction(
4157 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4158 KmpTaskTWithPrivatesQTy);
4159 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4160 LValue DestructorsLV = CGF.EmitLValueForField(
4161 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4163 DestructorFn, KmpRoutineEntryPtrTy),
4164 DestructorsLV);
4165 }
4166 // Set priority.
4167 if (Data.Priority.getInt()) {
4168 LValue Data2LV = CGF.EmitLValueForField(
4169 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4170 LValue PriorityLV = CGF.EmitLValueForField(
4171 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4172 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4173 }
4174 Result.NewTask = NewTask;
4175 Result.TaskEntry = TaskEntry;
4176 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4177 Result.TDBase = TDBase;
4178 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4179 return Result;
4180}
4181
4182/// Translates internal dependency kind into the runtime kind.
4184 RTLDependenceKindTy DepKind;
4185 switch (K) {
4186 case OMPC_DEPEND_in:
4187 DepKind = RTLDependenceKindTy::DepIn;
4188 break;
4189 // Out and InOut dependencies must use the same code.
4190 case OMPC_DEPEND_out:
4191 case OMPC_DEPEND_inout:
4192 DepKind = RTLDependenceKindTy::DepInOut;
4193 break;
4194 case OMPC_DEPEND_mutexinoutset:
4195 DepKind = RTLDependenceKindTy::DepMutexInOutSet;
4196 break;
4197 case OMPC_DEPEND_inoutset:
4198 DepKind = RTLDependenceKindTy::DepInOutSet;
4199 break;
4200 case OMPC_DEPEND_outallmemory:
4201 DepKind = RTLDependenceKindTy::DepOmpAllMem;
4202 break;
4203 case OMPC_DEPEND_source:
4204 case OMPC_DEPEND_sink:
4205 case OMPC_DEPEND_depobj:
4206 case OMPC_DEPEND_inoutallmemory:
4208 llvm_unreachable("Unknown task dependence type");
4209 }
4210 return DepKind;
4211}
4212
4213/// Builds kmp_depend_info, if it is not built yet, and builds flags type.
4214static void getDependTypes(ASTContext &C, QualType &KmpDependInfoTy,
4215 QualType &FlagsTy) {
4216 FlagsTy = C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4217 if (KmpDependInfoTy.isNull()) {
4218 RecordDecl *KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4219 KmpDependInfoRD->startDefinition();
4220 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4221 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4222 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4223 KmpDependInfoRD->completeDefinition();
4224 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
4225 }
4226}
4227
4228std::pair<llvm::Value *, LValue>
4230 SourceLocation Loc) {
4232 QualType FlagsTy;
4233 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4234 RecordDecl *KmpDependInfoRD =
4235 cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4236 QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4239 DepobjLVal.getAddress(CGF),
4240 CGF.ConvertTypeForMem(KmpDependInfoPtrTy)),
4241 KmpDependInfoPtrTy->castAs<PointerType>());
4242 Address DepObjAddr = CGF.Builder.CreateGEP(
4243 Base.getAddress(CGF),
4244 llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4245 LValue NumDepsBase = CGF.MakeAddrLValue(
4246 DepObjAddr, KmpDependInfoTy, Base.getBaseInfo(), Base.getTBAAInfo());
4247 // NumDeps = deps[i].base_addr;
4248 LValue BaseAddrLVal = CGF.EmitLValueForField(
4249 NumDepsBase,
4250 *std::next(KmpDependInfoRD->field_begin(),
4251 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr)));
4252 llvm::Value *NumDeps = CGF.EmitLoadOfScalar(BaseAddrLVal, Loc);
4253 return std::make_pair(NumDeps, Base);
4254}
4255
4256static void emitDependData(CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4257 llvm::PointerUnion<unsigned *, LValue *> Pos,
4259 Address DependenciesArray) {
4260 CodeGenModule &CGM = CGF.CGM;
4261 ASTContext &C = CGM.getContext();
4262 QualType FlagsTy;
4263 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4264 RecordDecl *KmpDependInfoRD =
4265 cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4266 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4267
4268 OMPIteratorGeneratorScope IteratorScope(
4269 CGF, cast_or_null<OMPIteratorExpr>(
4270 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4271 : nullptr));
4272 for (const Expr *E : Data.DepExprs) {
4273 llvm::Value *Addr;
4274 llvm::Value *Size;
4275
4276 // The expression will be a nullptr in the 'omp_all_memory' case.
4277 if (E) {
4278 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4279 Addr = CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy);
4280 } else {
4281 Addr = llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4282 Size = llvm::ConstantInt::get(CGF.SizeTy, 0);
4283 }
4284 LValue Base;
4285 if (unsigned *P = Pos.dyn_cast<unsigned *>()) {
4286 Base = CGF.MakeAddrLValue(
4287 CGF.Builder.CreateConstGEP(DependenciesArray, *P), KmpDependInfoTy);
4288 } else {
4289 assert(E && "Expected a non-null expression");
4290 LValue &PosLVal = *Pos.get<LValue *>();
4291 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4292 Base = CGF.MakeAddrLValue(
4293 CGF.Builder.CreateGEP(DependenciesArray, Idx), KmpDependInfoTy);
4294 }
4295 // deps[i].base_addr = &<Dependencies[i].second>;
4296 LValue BaseAddrLVal = CGF.EmitLValueForField(
4297 Base,
4298 *std::next(KmpDependInfoRD->field_begin(),
4299 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr)));
4300 CGF.EmitStoreOfScalar(Addr, BaseAddrLVal);
4301 // deps[i].len = sizeof(<Dependencies[i].second>);
4302 LValue LenLVal = CGF.EmitLValueForField(
4303 Base, *std::next(KmpDependInfoRD->field_begin(),
4304 static_cast<unsigned int>(RTLDependInfoFields::Len)));
4305 CGF.EmitStoreOfScalar(Size, LenLVal);
4306 // deps[i].flags = <Dependencies[i].first>;
4307 RTLDependenceKindTy DepKind = translateDependencyKind(Data.DepKind);
4308 LValue FlagsLVal = CGF.EmitLValueForField(
4309 Base,
4310 *std::next(KmpDependInfoRD->field_begin(),
4311 static_cast<unsigned int>(RTLDependInfoFields::Flags)));
4313 llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)),
4314 FlagsLVal);
4315 if (unsigned *P = Pos.dyn_cast<unsigned *>()) {
4316 ++(*P);
4317 } else {
4318 LValue &PosLVal = *Pos.get<LValue *>();
4319 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4320 Idx = CGF.Builder.CreateNUWAdd(Idx,
4321 llvm::ConstantInt::get(Idx->getType(), 1));
4322 CGF.EmitStoreOfScalar(Idx, PosLVal);
4323 }
4324 }
4325}
4326
4328 CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4330 assert(Data.DepKind == OMPC_DEPEND_depobj &&
4331 "Expected depobj dependency kind.");
4333 SmallVector<LValue, 4> SizeLVals;
4334 ASTContext &C = CGF.getContext();
4335 {
4336 OMPIteratorGeneratorScope IteratorScope(
4337 CGF, cast_or_null<OMPIteratorExpr>(
4338 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4339 : nullptr));
4340 for (const Expr *E : Data.DepExprs) {
4341 llvm::Value *NumDeps;
4342 LValue Base;
4343 LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4344 std::tie(NumDeps, Base) =
4345 getDepobjElements(CGF, DepobjLVal, E->getExprLoc());
4346 LValue NumLVal = CGF.MakeAddrLValue(
4347 CGF.CreateMemTemp(C.getUIntPtrType(), "depobj.size.addr"),
4348 C.getUIntPtrType());
4349 CGF.Builder.CreateStore(llvm::ConstantInt::get(CGF.IntPtrTy, 0),
4350 NumLVal.getAddress(CGF));
4351 llvm::Value *PrevVal = CGF.EmitLoadOfScalar(NumLVal, E->getExprLoc());
4352 llvm::Value *Add = CGF.Builder.CreateNUWAdd(PrevVal, NumDeps);
4353 CGF.EmitStoreOfScalar(Add, NumLVal);
4354 SizeLVals.push_back(NumLVal);
4355 }
4356 }
4357 for (unsigned I = 0, E = SizeLVals.size(); I < E; ++I) {
4358 llvm::Value *Size =
4359 CGF.EmitLoadOfScalar(SizeLVals[I], Data.DepExprs[I]->getExprLoc());
4360 Sizes.push_back(Size);
4361 }
4362 return Sizes;
4363}
4364
4366 QualType &KmpDependInfoTy,
4367 LValue PosLVal,
4369 Address DependenciesArray) {
4370 assert(Data.DepKind == OMPC_DEPEND_depobj &&
4371 "Expected depobj dependency kind.");
4372 llvm::Value *ElSize = CGF.getTypeSize(KmpDependInfoTy);
4373 {
4374 OMPIteratorGeneratorScope IteratorScope(
4375 CGF, cast_or_null<OMPIteratorExpr>(
4376 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4377 : nullptr));
4378 for (unsigned I = 0, End = Data.DepExprs.size(); I < End; ++I) {
4379 const Expr *E = Data.DepExprs[I];
4380 llvm::Value *NumDeps;
4381 LValue Base;
4382 LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4383 std::tie(NumDeps, Base) =
4384 getDepobjElements(CGF, DepobjLVal, E->getExprLoc());
4385
4386 // memcopy dependency data.
4387 llvm::Value *Size = CGF.Builder.CreateNUWMul(
4388 ElSize,
4389 CGF.Builder.CreateIntCast(NumDeps, CGF.SizeTy, /*isSigned=*/false));
4390 llvm::Value *Pos = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4391 Address DepAddr = CGF.Builder.CreateGEP(DependenciesArray, Pos);
4392 CGF.Builder.CreateMemCpy(DepAddr, Base.getAddress(CGF), Size);
4393
4394 // Increase pos.
4395 // pos += size;
4396 llvm::Value *Add = CGF.Builder.CreateNUWAdd(Pos, NumDeps);
4397 CGF.EmitStoreOfScalar(Add, PosLVal);
4398 }
4399 }
4400}
4401
4402std::pair<llvm::Value *, Address> CGOpenMPRuntime::emitDependClause(
4404 SourceLocation Loc) {
4405 if (llvm::all_of(Dependencies, [](const OMPTaskDataTy::DependData &D) {
4406 return D.DepExprs.empty();
4407 }))
4408 return std::make_pair(nullptr, Address::invalid());
4409 // Process list of dependencies.
4411 Address DependenciesArray = Address::invalid();
4412 llvm::Value *NumOfElements = nullptr;
4413 unsigned NumDependencies = std::accumulate(
4414 Dependencies.begin(), Dependencies.end(), 0,
4415 [](unsigned V, const OMPTaskDataTy::DependData &D) {
4416 return D.DepKind == OMPC_DEPEND_depobj
4417 ? V
4418 : (V + (D.IteratorExpr ? 0 : D.DepExprs.size()));
4419 });
4420 QualType FlagsTy;
4421 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4422 bool HasDepobjDeps = false;
4423 bool HasRegularWithIterators = false;
4424 llvm::Value *NumOfDepobjElements = llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4425 llvm::Value *NumOfRegularWithIterators =
4426 llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4427 // Calculate number of depobj dependencies and regular deps with the
4428 // iterators.
4429 for (const OMPTaskDataTy::DependData &D : Dependencies) {
4430 if (D.DepKind == OMPC_DEPEND_depobj) {
4433 for (llvm::Value *Size : Sizes) {
4434 NumOfDepobjElements =
4435 CGF.Builder.CreateNUWAdd(NumOfDepobjElements, Size);
4436 }
4437 HasDepobjDeps = true;
4438 continue;
4439 }
4440 // Include number of iterations, if any.
4441
4442 if (const auto *IE = cast_or_null<OMPIteratorExpr>(D.IteratorExpr)) {
4443 for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) {
4444 llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4445 Sz = CGF.Builder.CreateIntCast(Sz, CGF.IntPtrTy, /*isSigned=*/false);
4446 llvm::Value *NumClauseDeps = CGF.Builder.CreateNUWMul(
4447 Sz, llvm::ConstantInt::get(CGF.IntPtrTy, D.DepExprs.size()));
4448 NumOfRegularWithIterators =
4449 CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumClauseDeps);
4450 }
4451 HasRegularWithIterators = true;
4452 continue;
4453 }
4454 }
4455
4456 QualType KmpDependInfoArrayTy;
4457 if (HasDepobjDeps || HasRegularWithIterators) {
4458 NumOfElements = llvm::ConstantInt::get(CGM.IntPtrTy, NumDependencies,
4459 /*isSigned=*/false);
4460 if (HasDepobjDeps) {
4461 NumOfElements =
4462 CGF.Builder.CreateNUWAdd(NumOfDepobjElements, NumOfElements);
4463 }
4464 if (HasRegularWithIterators) {
4465 NumOfElements =
4466 CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumOfElements);
4467 }
4468 auto *OVE = new (C) OpaqueValueExpr(
4469 Loc, C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0),
4470 VK_PRValue);
4471 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
4472 RValue::get(NumOfElements));
4473 KmpDependInfoArrayTy =
4474 C.getVariableArrayType(KmpDependInfoTy, OVE, ArrayType::Normal,
4475 /*IndexTypeQuals=*/0, SourceRange(Loc, Loc));
4476 // CGF.EmitVariablyModifiedType(KmpDependInfoArrayTy);
4477 // Properly emit variable-sized array.
4478 auto *PD = ImplicitParamDecl::Create(C, KmpDependInfoArrayTy,
4480 CGF.EmitVarDecl(*PD);
4481 DependenciesArray = CGF.GetAddrOfLocalVar(PD);
4482 NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
4483 /*isSigned=*/false);
4484 } else {
4485 KmpDependInfoArrayTy = C.getConstantArrayType(
4486 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), nullptr,
4487 ArrayType::Normal, /*IndexTypeQuals=*/0);
4488 DependenciesArray =
4489 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4490 DependenciesArray = CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0);
4491 NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumDependencies,
4492 /*isSigned=*/false);
4493 }
4494 unsigned Pos = 0;
4495 for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) {
4496 if (Dependencies[I].DepKind == OMPC_DEPEND_depobj ||
4497 Dependencies[I].IteratorExpr)
4498 continue;
4499 emitDependData(CGF, KmpDependInfoTy, &Pos, Dependencies[I],
4500 DependenciesArray);
4501 }
4502 // Copy regular dependencies with iterators.
4503 LValue PosLVal = CGF.MakeAddrLValue(
4504 CGF.CreateMemTemp(C.getSizeType(), "dep.counter.addr"), C.getSizeType());
4505 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4506 for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) {
4507 if (Dependencies[I].DepKind == OMPC_DEPEND_depobj ||
4508 !Dependencies[I].IteratorExpr)
4509 continue;
4510 emitDependData(CGF, KmpDependInfoTy, &PosLVal, Dependencies[I],
4511 DependenciesArray);
4512 }
4513 // Copy final depobj arrays without iterators.
4514 if (HasDepobjDeps) {
4515 for (unsigned I = 0, End = Dependencies.size(); I < End; ++I) {
4516 if (Dependencies[I].DepKind != OMPC_DEPEND_depobj)
4517 continue;
4518 emitDepobjElements(CGF, KmpDependInfoTy, PosLVal, Dependencies[I],
4519 DependenciesArray);
4520 }
4521 }
4522 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4523 DependenciesArray, CGF.VoidPtrTy, CGF.Int8Ty);
4524 return std::make_pair(NumOfElements, DependenciesArray);
4525}
4526