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