Debian Codegraph @

clang/lib/CodeGen/CGOpenMPRuntime.cpp

raw
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 "ABIInfoImpl.h"
15 #include "CGCXXABI.h"
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "TargetInfo.h"
21 #include "clang/AST/APValue.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/OpenMPClause.h"
25 #include "clang/AST/StmtOpenMP.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/DiagnosticFrontend.h"
28 #include "clang/Basic/OpenMPKinds.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/CodeGen/ConstantInitBuilder.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Bitcode/BitcodeReader.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Support/AtomicOrdering.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <cstdint>
45 #include <numeric>
46 #include <optional>
47
48 using namespace clang;
49 using namespace CodeGen;
50 using namespace llvm::omp;
51
52 namespace {
53 /// Base class for handling code generation inside OpenMP regions.
54 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
55 public:
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
108 protected:
109 CGOpenMPRegionKind RegionKind;
110 RegionCodeGenTy CodeGen;
111 OpenMPDirectiveKind Kind;
112 bool HasCancel;
113 };
114
115 /// API for captured statement code generation in OpenMP constructs.
116 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
117 public:
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
141 private:
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.
149 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
150 public:
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);
172 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
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.");
189 CGF.EmitBranch(CGF.ReturnBlock.getBlock());
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
229 private:
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.
239 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
240 public:
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
314 private:
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.
325 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
326 public:
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
345 private:
346 StringRef HelperName;
347 };
348
349 static 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.
354 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
355 public:
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,
374 VD->getType().getNonReferenceType(), VK_LValue,
375 C.getLocation());
376 PrivScope.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress());
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
406 private:
407 /// Private scope to capture global variables.
408 CodeGenFunction::OMPPrivateScope PrivScope;
409 };
410
411 /// RAII for emitting code of OpenMP constructs.
412 class 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
419 public:
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
457 enum 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;
509 enum 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).
526 enum 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.
558 class CleanupTy final : public EHScopeStack::Cleanup {
559 PrePostActionTy *Action;
560
561 public:
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
572 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
573 CodeGenFunction::RunCleanupsScope Scope(CGF);
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.
585 static const OMPDeclareReductionDecl *
586 getReductionInit(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
596 static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
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 =
603 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
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.MakeNaturalAlignRawAddrLValue(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 =
633 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
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.
655 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
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.emitRawPointer(CGF);
672 llvm::Value *DestBegin = DestAddr.emitRawPointer(CGF);
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
739 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
740 return CGF.EmitOMPSharedLValue(E);
741 }
742
743 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
744 const Expr *E) {
745 if (const auto *OASE = dyn_cast<ArraySectionExpr>(E))
746 return CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false);
747 return LValue();
748 }
749
750 void 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
767 ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
768 ArrayRef<const Expr *> Origs,
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
786 void ReductionCodeGen::emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N) {
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
801 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
802 QualType PrivateType = getPrivateType(N);
803 bool AsArraySection = isa<ArraySectionExpr>(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().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);
827 CodeGenFunction::OpaqueValueMapping OpaqueMap(
828 CGF,
829 cast<OpaqueValueExpr>(
830 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
831 RValue::get(Size));
832 CGF.EmitVariablyModifiedType(PrivateType);
833 }
834
835 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
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 }
844 CodeGenFunction::OpaqueValueMapping OpaqueMap(
845 CGF,
846 cast<OpaqueValueExpr>(
847 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
848 RValue::get(Size));
849 CGF.EmitVariablyModifiedType(PrivateType);
850 }
851
852 void ReductionCodeGen::emitInitialization(
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
877 bool ReductionCodeGen::needCleanups(unsigned N) {
878 QualType PrivateType = getPrivateType(N);
879 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
880 return DTorKind != QualType::DK_none;
881 }
882
883 void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
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
894 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
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(), PtrTy);
901 } else {
902 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
903 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
904 }
905 BaseTy = BaseTy->getPointeeType();
906 }
907 return CGF.MakeAddrLValue(
908 BaseLV.getAddress().withElementType(CGF.ConvertTypeForMem(ElTy)),
909 BaseLV.getType(), BaseLV.getBaseInfo(),
910 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
911 }
912
913 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
914 Address OriginalBaseAddress, llvm::Value *Addr) {
915 RawAddress Tmp = RawAddress::invalid();
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()) {
931 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
932 Addr, Tmp.getElementType());
933 CGF.Builder.CreateStore(Addr, Tmp);
934 return MostTopTmp;
935 }
936
937 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
938 Addr, OriginalBaseAddress.getType());
939 return OriginalBaseAddress.withPointer(Addr, NotKnownNonNull);
940 }
941
942 static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
943 const VarDecl *OrigVD = nullptr;
944 if (const auto *OASE = dyn_cast<ArraySectionExpr>(Ref)) {
945 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
946 while (const auto *TempOASE = dyn_cast<ArraySectionExpr>(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
962 Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
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();
972 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
973 SharedAddr.getElementType(), BaseLValue.getPointer(CGF),
974 SharedAddr.emitRawPointer(CGF));
975 llvm::Value *PrivatePointer =
976 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
977 PrivateAddr.emitRawPointer(CGF), 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(), Ptr);
983 }
984 BaseDecls.emplace_back(
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
986 return PrivateAddr;
987 }
988
989 bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
990 const OMPDeclareReductionDecl *DRD =
991 getReductionInit(ClausesData[N].ReductionOp);
992 return DRD && DRD->getInitializer();
993 }
994
995 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
996 return CGF.EmitLoadOfPointerLValue(
997 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
998 getThreadIDVariable()->getType()->castAs<PointerType>());
999 }
1000
1001 void 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)
1011 CGF.incrementProfileCounter(S);
1012 CodeGen(CGF);
1013 CGF.EHStack.popTerminate();
1014 }
1015
1016 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1017 CodeGenFunction &CGF) {
1018 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1019 getThreadIDVariable()->getType(),
1020 AlignmentSource::Decl);
1021 }
1022
1023 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
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
1034 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
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 Config.setDefaultTargetAS(
1043 CGM.getContext().getTargetInfo().getTargetAddressSpace(LangAS::Default));
1044 Config.setRuntimeCC(CGM.getRuntimeCC());
1045
1046 OMPBuilder.setConfig(Config);
1047 OMPBuilder.initialize();
1048 OMPBuilder.loadOffloadInfoMetadata(*CGM.getFileSystem(),
1049 CGM.getLangOpts().OpenMPIsTargetDevice
1050 ? CGM.getLangOpts().OMPHostIRFile
1051 : StringRef{});
1052
1053 // The user forces the compiler to behave as if omp requires
1054 // unified_shared_memory was given.
1055 if (CGM.getLangOpts().OpenMPForceUSM) {
1056 HasRequiresUnifiedSharedMemory = true;
1057 OMPBuilder.Config.setHasRequiresUnifiedSharedMemory(true);
1058 }
1059 }
1060
1061 void CGOpenMPRuntime::clear() {
1062 InternalVars.clear();
1063 // Clean non-target variable declarations possibly used only in debug info.
1064 for (const auto &Data : EmittedNonTargetVariables) {
1065 if (!Data.getValue().pointsToAliveValue())
1066 continue;
1067 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1068 if (!GV)
1069 continue;
1070 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1071 continue;
1072 GV->eraseFromParent();
1073 }
1074 }
1075
1076 std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1077 return OMPBuilder.createPlatformSpecificName(Parts);
1078 }
1079
1080 static llvm::Function *
1081 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1082 const Expr *CombinerInitializer, const VarDecl *In,
1083 const VarDecl *Out, bool IsCombiner) {
1084 // void .omp_combiner.(Ty *in, Ty *out);
1085 ASTContext &C = CGM.getContext();
1086 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1087 FunctionArgList Args;
1088 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1089 /*Id=*/nullptr, PtrTy, ImplicitParamKind::Other);
1090 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1091 /*Id=*/nullptr, PtrTy, ImplicitParamKind::Other);
1092 Args.push_back(&OmpOutParm);
1093 Args.push_back(&OmpInParm);
1094 const CGFunctionInfo &FnInfo =
1095 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1096 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1097 std::string Name = CGM.getOpenMPRuntime().getName(
1098 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1099 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1100 Name, &CGM.getModule());
1101 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1102 if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
1103 Fn->removeFnAttr(llvm::Attribute::NoInline);
1104 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1105 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1106 }
1107 CodeGenFunction CGF(CGM);
1108 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1109 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1110 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1111 Out->getLocation());
1112 CodeGenFunction::OMPPrivateScope Scope(CGF);
1113 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1114 Scope.addPrivate(
1115 In, CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1116 .getAddress());
1117 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1118 Scope.addPrivate(
1119 Out, CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1120 .getAddress());
1121 (void)Scope.Privatize();
1122 if (!IsCombiner && Out->hasInit() &&
1123 !CGF.isTrivialInitializer(Out->getInit())) {
1124 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1125 Out->getType().getQualifiers(),
1126 /*IsInitializer=*/true);
1127 }
1128 if (CombinerInitializer)
1129 CGF.EmitIgnoredExpr(CombinerInitializer);
1130 Scope.ForceCleanup();
1131 CGF.FinishFunction();
1132 return Fn;
1133 }
1134
1135 void CGOpenMPRuntime::emitUserDefinedReduction(
1136 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1137 if (UDRMap.count(D) > 0)
1138 return;
1139 llvm::Function *Combiner = emitCombinerOrInitializer(
1140 CGM, D->getType(), D->getCombiner(),
1141 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1142 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
1143 /*IsCombiner=*/true);
1144 llvm::Function *Initializer = nullptr;
1145 if (const Expr *Init = D->getInitializer()) {
1146 Initializer = emitCombinerOrInitializer(
1147 CGM, D->getType(),
1148 D->getInitializerKind() == OMPDeclareReductionInitKind::Call ? Init
1149 : nullptr,
1150 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1151 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
1152 /*IsCombiner=*/false);
1153 }
1154 UDRMap.try_emplace(D, Combiner, Initializer);
1155 if (CGF)
1156 FunctionUDRMap[CGF->CurFn].push_back(D);
1157 }
1158
1159 std::pair<llvm::Function *, llvm::Function *>
1160 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1161 auto I = UDRMap.find(D);
1162 if (I != UDRMap.end())
1163 return I->second;
1164 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1165 return UDRMap.lookup(D);
1166 }
1167
1168 namespace {
1169 // Temporary RAII solution to perform a push/pop stack event on the OpenMP IR
1170 // Builder if one is present.
1171 struct PushAndPopStackRAII {
1172 PushAndPopStackRAII(llvm::OpenMPIRBuilder *OMPBuilder, CodeGenFunction &CGF,
1173 bool HasCancel, llvm::omp::Directive Kind)
1174 : OMPBuilder(OMPBuilder) {
1175 if (!OMPBuilder)
1176 return;
1177
1178 // The following callback is the crucial part of clangs cleanup process.
1179 //
1180 // NOTE:
1181 // Once the OpenMPIRBuilder is used to create parallel regions (and
1182 // similar), the cancellation destination (Dest below) is determined via
1183 // IP. That means if we have variables to finalize we split the block at IP,
1184 // use the new block (=BB) as destination to build a JumpDest (via
1185 // getJumpDestInCurrentScope(BB)) which then is fed to
1186 // EmitBranchThroughCleanup. Furthermore, there will not be the need
1187 // to push & pop an FinalizationInfo object.
1188 // The FiniCB will still be needed but at the point where the
1189 // OpenMPIRBuilder is asked to construct a parallel (or similar) construct.
1190 auto FiniCB = [&CGF](llvm::OpenMPIRBuilder::InsertPointTy IP) {
1191 assert(IP.getBlock()->end() == IP.getPoint() &&
1192 "Clang CG should cause non-terminated block!");
1193 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1194 CGF.Builder.restoreIP(IP);
1195 CodeGenFunction::JumpDest Dest =
1196 CGF.getOMPCancelDestination(OMPD_parallel);
1197 CGF.EmitBranchThroughCleanup(Dest);
1198 return llvm::Error::success();
1199 };
1200
1201 // TODO: Remove this once we emit parallel regions through the
1202 // OpenMPIRBuilder as it can do this setup internally.
1203 llvm::OpenMPIRBuilder::FinalizationInfo FI({FiniCB, Kind, HasCancel});
1204 OMPBuilder->pushFinalizationCB(std::move(FI));
1205 }
1206 ~PushAndPopStackRAII() {
1207 if (OMPBuilder)
1208 OMPBuilder->popFinalizationCB();
1209 }
1210 llvm::OpenMPIRBuilder *OMPBuilder;
1211 };
1212 } // namespace
1213
1214 static llvm::Function *emitParallelOrTeamsOutlinedFunction(
1215 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1216 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1217 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1218 assert(ThreadIDVar->getType()->isPointerType() &&
1219 "thread id variable must be of type kmp_int32 *");
1220 CodeGenFunction CGF(CGM, true);
1221 bool HasCancel = false;
1222 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1223 HasCancel = OPD->hasCancel();
1224 else if (const auto *OPD = dyn_cast<OMPTargetParallelDirective>(&D))
1225 HasCancel = OPD->hasCancel();
1226 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1227 HasCancel = OPSD->hasCancel();
1228 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1229 HasCancel = OPFD->hasCancel();
1230 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1231 HasCancel = OPFD->hasCancel();
1232 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1233 HasCancel = OPFD->hasCancel();
1234 else if (const auto *OPFD =
1235 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1236 HasCancel = OPFD->hasCancel();
1237 else if (const auto *OPFD =
1238 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1239 HasCancel = OPFD->hasCancel();
1240
1241 // TODO: Temporarily inform the OpenMPIRBuilder, if any, about the new
1242 // parallel region to make cancellation barriers work properly.
1243 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1244 PushAndPopStackRAII PSR(&OMPBuilder, CGF, HasCancel, InnermostKind);
1245 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1246 HasCancel, OutlinedHelperName);
1247 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1248 return CGF.GenerateOpenMPCapturedStmtFunction(*CS, D);
1249 }
1250
1251 std::string CGOpenMPRuntime::getOutlinedHelperName(StringRef Name) const {
1252 std::string Suffix = getName({"omp_outlined"});
1253 return (Name + Suffix).str();
1254 }
1255
1256 std::string CGOpenMPRuntime::getOutlinedHelperName(CodeGenFunction &CGF) const {
1257 return getOutlinedHelperName(CGF.CurFn->getName());
1258 }
1259
1260 std::string CGOpenMPRuntime::getReductionFuncName(StringRef Name) const {
1261 std::string Suffix = getName({"omp", "reduction", "reduction_func"});
1262 return (Name + Suffix).str();
1263 }
1264
1265 llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
1266 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1267 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1268 const RegionCodeGenTy &CodeGen) {
1269 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1270 return emitParallelOrTeamsOutlinedFunction(
1271 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(CGF),
1272 CodeGen);
1273 }
1274
1275 llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1276 CodeGenFunction &CGF, const OMPExecutableDirective &D,
1277 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1278 const RegionCodeGenTy &CodeGen) {
1279 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1280 return emitParallelOrTeamsOutlinedFunction(
1281 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(CGF),
1282 CodeGen);
1283 }
1284
1285 llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
1286 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1287 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1288 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1289 bool Tied, unsigned &NumberOfParts) {
1290 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1291 PrePostActionTy &) {
1292 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1293 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
1294 llvm::Value *TaskArgs[] = {
1295 UpLoc, ThreadID,
1296 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1297 TaskTVar->getType()->castAs<PointerType>())
1298 .getPointer(CGF)};
1299 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1300 CGM.getModule(), OMPRTL___kmpc_omp_task),
1301 TaskArgs);
1302 };
1303 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1304 UntiedCodeGen);
1305 CodeGen.setAction(Action);
1306 assert(!ThreadIDVar->getType()->isPointerType() &&
1307 "thread id variable must be of type kmp_int32 for tasks");
1308 const OpenMPDirectiveKind Region =
1309 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1310 : OMPD_task;
1311 const CapturedStmt *CS = D.getCapturedStmt(Region);
1312 bool HasCancel = false;
1313 if (const auto *TD = dyn_cast<OMPTaskDirective>(&D))
1314 HasCancel = TD->hasCancel();
1315 else if (const auto *TD = dyn_cast<OMPTaskLoopDirective>(&D))
1316 HasCancel = TD->hasCancel();
1317 else if (const auto *TD = dyn_cast<OMPMasterTaskLoopDirective>(&D))
1318 HasCancel = TD->hasCancel();
1319 else if (const auto *TD = dyn_cast<OMPParallelMasterTaskLoopDirective>(&D))
1320 HasCancel = TD->hasCancel();
1321
1322 CodeGenFunction CGF(CGM, true);
1323 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1324 InnermostKind, HasCancel, Action);
1325 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1326 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
1327 if (!Tied)
1328 NumberOfParts = Action.getNumberOfParts();
1329 return Res;
1330 }
1331
1332 void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1333 bool AtCurrentPoint) {
1334 auto &Elem = OpenMPLocThreadIDMap[CGF.CurFn];
1335 assert(!Elem.ServiceInsertPt && "Insert point is set already.");
1336
1337 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1338 if (AtCurrentPoint) {
1339 Elem.ServiceInsertPt = new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt",
1340 CGF.Builder.GetInsertBlock());
1341 } else {
1342 Elem.ServiceInsertPt = new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1343 Elem.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt->getIterator());
1344 }
1345 }
1346
1347 void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1348 auto &Elem = OpenMPLocThreadIDMap[CGF.CurFn];
1349 if (Elem.ServiceInsertPt) {
1350 llvm::Instruction *Ptr = Elem.ServiceInsertPt;
1351 Elem.ServiceInsertPt = nullptr;
1352 Ptr->eraseFromParent();
1353 }
1354 }
1355
1356 static StringRef getIdentStringFromSourceLocation(CodeGenFunction &CGF,
1357 SourceLocation Loc,
1358 SmallString<128> &Buffer) {
1359 llvm::raw_svector_ostream OS(Buffer);
1360 // Build debug location
1361 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1362 OS << ";";
1363 if (auto *DbgInfo = CGF.getDebugInfo())
1364 OS << DbgInfo->remapDIPath(PLoc.getFilename());
1365 else
1366 OS << PLoc.getFilename();
1367 OS << ";";
1368 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1369 OS << FD->getQualifiedNameAsString();
1370 OS << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1371 return OS.str();
1372 }
1373
1374 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1375 SourceLocation Loc,
1376 unsigned Flags, bool EmitLoc) {
1377 uint32_t SrcLocStrSize;
1378 llvm::Constant *SrcLocStr;
1379 if ((!EmitLoc && CGM.getCodeGenOpts().getDebugInfo() ==
1380 llvm::codegenoptions::NoDebugInfo) ||
1381 Loc.isInvalid()) {
1382 SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
1383 } else {
1384 std::string FunctionName;
1385 std::string FileName;
1386 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1387 FunctionName = FD->getQualifiedNameAsString();
1388 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1389 if (auto *DbgInfo = CGF.getDebugInfo())
1390 FileName = DbgInfo->remapDIPath(PLoc.getFilename());
1391 else
1392 FileName = PLoc.getFilename();
1393 unsigned Line = PLoc.getLine();
1394 unsigned Column = PLoc.getColumn();
1395 SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(FunctionName, FileName, Line,
1396 Column, SrcLocStrSize);
1397 }
1398 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1399 return OMPBuilder.getOrCreateIdent(
1400 SrcLocStr, SrcLocStrSize, llvm::omp::IdentFlag(Flags), Reserved2Flags);
1401 }
1402
1403 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1404 SourceLocation Loc) {
1405 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1406 // If the OpenMPIRBuilder is used we need to use it for all thread id calls as
1407 // the clang invariants used below might be broken.
1408 if (CGM.getLangOpts().OpenMPIRBuilder) {
1409 SmallString<128> Buffer;
1410 OMPBuilder.updateToLocation(CGF.Builder.saveIP());
1411 uint32_t SrcLocStrSize;
1412 auto *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(
1413 getIdentStringFromSourceLocation(CGF, Loc, Buffer), SrcLocStrSize);
1414 return OMPBuilder.getOrCreateThreadID(
1415 OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize));
1416 }
1417
1418 llvm::Value *ThreadID = nullptr;
1419 // Check whether we've already cached a load of the thread id in this
1420 // function.
1421 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1422 if (I != OpenMPLocThreadIDMap.end()) {
1423 ThreadID = I->second.ThreadID;
1424 if (ThreadID != nullptr)
1425 return ThreadID;
1426 }
1427 // If exceptions are enabled, do not use parameter to avoid possible crash.
1428 if (auto *OMPRegionInfo =
1429 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1430 if (OMPRegionInfo->getThreadIDVariable()) {
1431 // Check if this an outlined function with thread id passed as argument.
1432 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1433 llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent();
1434 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1435 !CGF.getLangOpts().CXXExceptions ||
1436 CGF.Builder.GetInsertBlock() == TopBlock ||
1437 !isa<llvm::Instruction>(LVal.getPointer(CGF)) ||
1438 cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1439 TopBlock ||
1440 cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1441 CGF.Builder.GetInsertBlock()) {
1442 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1443 // If value loaded in entry block, cache it and use it everywhere in
1444 // function.
1445 if (CGF.Builder.GetInsertBlock() == TopBlock)
1446 OpenMPLocThreadIDMap[CGF.CurFn].ThreadID = ThreadID;
1447 return ThreadID;
1448 }
1449 }
1450 }
1451
1452 // This is not an outlined function region - need to call __kmpc_int32
1453 // kmpc_global_thread_num(ident_t *loc).
1454 // Generate thread id value and cache this value for use across the
1455 // function.
1456 auto &Elem = OpenMPLocThreadIDMap[CGF.CurFn];
1457 if (!Elem.ServiceInsertPt)
1458 setLocThreadIdInsertPt(CGF);
1459 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1460 CGF.Builder.SetInsertPoint(Elem.ServiceInsertPt);
1461 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
1462 llvm::CallInst *Call = CGF.Builder.CreateCall(
1463 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
1464 OMPRTL___kmpc_global_thread_num),
1465 emitUpdateLocation(CGF, Loc));
1466 Call->setCallingConv(CGF.getRuntimeCC());
1467 Elem.ThreadID = Call;
1468 return Call;
1469 }
1470
1471 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1472 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1473 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1474 clearLocThreadIdInsertPt(CGF);
1475 OpenMPLocThreadIDMap.erase(CGF.CurFn);
1476 }
1477 if (auto I = FunctionUDRMap.find(CGF.CurFn); I != FunctionUDRMap.end()) {
1478 for (const auto *D : I->second)
1479 UDRMap.erase(D);
1480 FunctionUDRMap.erase(I);
1481 }
1482 if (auto I = FunctionUDMMap.find(CGF.CurFn); I != FunctionUDMMap.end()) {
1483 for (const auto *D : I->second)
1484 UDMMap.erase(D);
1485 FunctionUDMMap.erase(I);
1486 }
1487 LastprivateConditionalToTypes.erase(CGF.CurFn);
1488 FunctionToUntiedTaskStackMap.erase(CGF.CurFn);
1489 }
1490
1491 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1492 return OMPBuilder.IdentPtr;
1493 }
1494
1495 static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
1496 convertDeviceClause(const VarDecl *VD) {
1497 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
1498 OMPDeclareTargetDeclAttr::getDeviceType(VD);
1499 if (!DevTy)
1500 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNone;
1501
1502 switch ((int)*DevTy) { // Avoid -Wcovered-switch-default
1503 case OMPDeclareTargetDeclAttr::DT_Host:
1504 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseHost;
1505 break;
1506 case OMPDeclareTargetDeclAttr::DT_NoHost:
1507 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNoHost;
1508 break;
1509 case OMPDeclareTargetDeclAttr::DT_Any:
1510 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny;
1511 break;
1512 default:
1513 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNone;
1514 break;
1515 }
1516 }
1517
1518 static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind
1519 convertCaptureClause(const VarDecl *VD) {
1520 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapType =
1521 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
1522 if (!MapType)
1523 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
1524 switch ((int)*MapType) { // Avoid -Wcovered-switch-default
1525 case OMPDeclareTargetDeclAttr::MapTypeTy::MT_To:
1526 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
1527 break;
1528 case OMPDeclareTargetDeclAttr::MapTypeTy::MT_Enter:
1529 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter;
1530 break;
1531 case OMPDeclareTargetDeclAttr::MapTypeTy::MT_Link:
1532 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
1533 break;
1534 default:
1535 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
1536 break;
1537 }
1538 }
1539
1540 static llvm::TargetRegionEntryInfo getEntryInfoFromPresumedLoc(
1541 CodeGenModule &CGM, llvm::OpenMPIRBuilder &OMPBuilder,
1542 SourceLocation BeginLoc, llvm::StringRef ParentName = "") {
1543
1544 auto FileInfoCallBack = [&]() {
1545 SourceManager &SM = CGM.getContext().getSourceManager();
1546 PresumedLoc PLoc = SM.getPresumedLoc(BeginLoc);
1547
1548 if (!CGM.getFileSystem()->exists(PLoc.getFilename()))
1549 PLoc = SM.getPresumedLoc(BeginLoc, /*UseLineDirectives=*/false);
1550
1551 return std::pair<std::string, uint64_t>(PLoc.getFilename(), PLoc.getLine());
1552 };
1553
1554 return OMPBuilder.getTargetEntryUniqueInfo(FileInfoCallBack,
1555 *CGM.getFileSystem(), ParentName);
1556 }
1557
1558 ConstantAddress CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
1559 auto AddrOfGlobal = [&VD, this]() { return CGM.GetAddrOfGlobal(VD); };
1560
1561 auto LinkageForVariable = [&VD, this]() {
1562 return CGM.getLLVMLinkageVarDefinition(VD);
1563 };
1564
1565 std::vector<llvm::GlobalVariable *> GeneratedRefs;
1566
1567 llvm::Type *LlvmPtrTy = CGM.getTypes().ConvertTypeForMem(
1568 CGM.getContext().getPointerType(VD->getType()));
1569 llvm::Constant *addr = OMPBuilder.getAddrOfDeclareTargetVar(
1570 convertCaptureClause(VD), convertDeviceClause(VD),
1571 VD->hasDefinition(CGM.getContext()) == VarDecl::DeclarationOnly,
1572 VD->isExternallyVisible(),
1573 getEntryInfoFromPresumedLoc(CGM, OMPBuilder,
1574 VD->getCanonicalDecl()->getBeginLoc()),
1575 CGM.getMangledName(VD), GeneratedRefs, CGM.getLangOpts().OpenMPSimd,
1576 CGM.getLangOpts().OMPTargetTriples, LlvmPtrTy, AddrOfGlobal,
1577 LinkageForVariable);
1578
1579 if (!addr)
1580 return ConstantAddress::invalid();
1581 return ConstantAddress(addr, LlvmPtrTy, CGM.getContext().getDeclAlign(VD));
1582 }
1583
1584 llvm::Constant *
1585 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1586 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1587 !CGM.getContext().getTargetInfo().isTLSSupported());
1588 // Lookup the entry, lazily creating it if necessary.
1589 std::string Suffix = getName({"cache", ""});
1590 return OMPBuilder.getOrCreateInternalVariable(
1591 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix).str());
1592 }
1593
1594 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1595 const VarDecl *VD,
1596 Address VDAddr,
1597 SourceLocation Loc) {
1598 if (CGM.getLangOpts().OpenMPUseTLS &&
1599 CGM.getContext().getTargetInfo().isTLSSupported())
1600 return VDAddr;
1601
1602 llvm::Type *VarTy = VDAddr.getElementType();
1603 llvm::Value *Args[] = {
1604 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1605 CGF.Builder.CreatePointerCast(VDAddr.emitRawPointer(CGF), CGM.Int8PtrTy),
1606 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1607 getOrCreateThreadPrivateCache(VD)};
1608 return Address(
1609 CGF.EmitRuntimeCall(
1610 OMPBuilder.getOrCreateRuntimeFunction(
1611 CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
1612 Args),
1613 CGF.Int8Ty, VDAddr.getAlignment());
1614 }
1615
1616 void CGOpenMPRuntime::emitThreadPrivateVarInit(
1617 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1618 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1619 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1620 // library.
1621 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
1622 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1623 CGM.getModule(), OMPRTL___kmpc_global_thread_num),
1624 OMPLoc);
1625 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1626 // to register constructor/destructor for variable.
1627 llvm::Value *Args[] = {
1628 OMPLoc,
1629 CGF.Builder.CreatePointerCast(VDAddr.emitRawPointer(CGF), CGM.VoidPtrTy),
1630 Ctor, CopyCtor, Dtor};
1631 CGF.EmitRuntimeCall(
1632 OMPBuilder.getOrCreateRuntimeFunction(
1633 CGM.getModule(), OMPRTL___kmpc_threadprivate_register),
1634 Args);
1635 }
1636
1637 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1638 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1639 bool PerformInit, CodeGenFunction *CGF) {
1640 if (CGM.getLangOpts().OpenMPUseTLS &&
1641 CGM.getContext().getTargetInfo().isTLSSupported())
1642 return nullptr;
1643
1644 VD = VD->getDefinition(CGM.getContext());
1645 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
1646 QualType ASTTy = VD->getType();
1647
1648 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1649 const Expr *Init = VD->getAnyInitializer();
1650 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1651 // Generate function that re-emits the declaration's initializer into the
1652 // threadprivate copy of the variable VD
1653 CodeGenFunction CtorCGF(CGM);
1654 FunctionArgList Args;
1655 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1656 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1657 ImplicitParamKind::Other);
1658 Args.push_back(&Dst);
1659
1660 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1661 CGM.getContext().VoidPtrTy, Args);
1662 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1663 std::string Name = getName({"__kmpc_global_ctor_", ""});
1664 llvm::Function *Fn =
1665 CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1666 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1667 Args, Loc, Loc);
1668 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
1669 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1670 CGM.getContext().VoidPtrTy, Dst.getLocation());
1671 Address Arg(ArgVal, CtorCGF.ConvertTypeForMem(ASTTy),
1672 VDAddr.getAlignment());
1673 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1674 /*IsInitializer=*/true);
1675 ArgVal = CtorCGF.EmitLoadOfScalar(
1676 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1677 CGM.getContext().VoidPtrTy, Dst.getLocation());
1678 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1679 CtorCGF.FinishFunction();
1680 Ctor = Fn;
1681 }
1682 if (VD->getType().isDestructedType() != QualType::DK_none) {
1683 // Generate function that emits destructor call for the threadprivate copy
1684 // of the variable VD
1685 CodeGenFunction DtorCGF(CGM);
1686 FunctionArgList Args;
1687 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1688 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1689 ImplicitParamKind::Other);
1690 Args.push_back(&Dst);
1691
1692 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1693 CGM.getContext().VoidTy, Args);
1694 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1695 std::string Name = getName({"__kmpc_global_dtor_", ""});
1696 llvm::Function *Fn =
1697 CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1698 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1699 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1700 Loc, Loc);
1701 // Create a scope with an artificial location for the body of this function.
1702 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1703 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
1704 DtorCGF.GetAddrOfLocalVar(&Dst),
1705 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1706 DtorCGF.emitDestroy(
1707 Address(ArgVal, DtorCGF.Int8Ty, VDAddr.getAlignment()), ASTTy,
1708 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1709 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1710 DtorCGF.FinishFunction();
1711 Dtor = Fn;
1712 }
1713 // Do not emit init function if it is not required.
1714 if (!Ctor && !Dtor)
1715 return nullptr;
1716
1717 // Copying constructor for the threadprivate variable.
1718 // Must be NULL - reserved by runtime, but currently it requires that this
1719 // parameter is always NULL. Otherwise it fires assertion.
1720 CopyCtor = llvm::Constant::getNullValue(CGM.DefaultPtrTy);
1721 if (Ctor == nullptr) {
1722 Ctor = llvm::Constant::getNullValue(CGM.DefaultPtrTy);
1723 }
1724 if (Dtor == nullptr) {
1725 Dtor = llvm::Constant::getNullValue(CGM.DefaultPtrTy);
1726 }
1727 if (!CGF) {
1728 auto *InitFunctionTy =
1729 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1730 std::string Name = getName({"__omp_threadprivate_init_", ""});
1731 llvm::Function *InitFunction = CGM.CreateGlobalInitOrCleanUpFunction(
1732 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
1733 CodeGenFunction InitCGF(CGM);
1734 FunctionArgList ArgList;
1735 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1736 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1737 Loc, Loc);
1738 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1739 InitCGF.FinishFunction();
1740 return InitFunction;
1741 }
1742 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1743 }
1744 return nullptr;
1745 }
1746
1747 void CGOpenMPRuntime::emitDeclareTargetFunction(const FunctionDecl *FD,
1748 llvm::GlobalValue *GV) {
1749 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
1750 OMPDeclareTargetDeclAttr::getActiveAttr(FD);
1751
1752 // We only need to handle active 'indirect' declare target functions.
1753 if (!ActiveAttr || !(*ActiveAttr)->getIndirect())
1754 return;
1755
1756 // Get a mangled name to store the new device global in.
1757 llvm::TargetRegionEntryInfo EntryInfo = getEntryInfoFromPresumedLoc(
1758 CGM, OMPBuilder, FD->getCanonicalDecl()->getBeginLoc(), FD->getName());
1759 SmallString<128> Name;
1760 OMPBuilder.OffloadInfoManager.getTargetRegionEntryFnName(Name, EntryInfo);
1761
1762 // We need to generate a new global to hold the address of the indirectly
1763 // called device function. Doing this allows us to keep the visibility and
1764 // linkage of the associated function unchanged while allowing the runtime to
1765 // access its value.
1766 llvm::GlobalValue *Addr = GV;
1767 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
1768 llvm::PointerType *FnPtrTy = llvm::PointerType::get(
1769 CGM.getLLVMContext(),
1770 CGM.getModule().getDataLayout().getProgramAddressSpace());
1771 Addr = new llvm::GlobalVariable(
1772 CGM.getModule(), FnPtrTy,
1773 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, GV, Name,
1774 nullptr, llvm::GlobalValue::NotThreadLocal,
1775 CGM.getModule().getDataLayout().getDefaultGlobalsAddressSpace());
1776 Addr->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1777 }
1778
1779 // Register the indirect Vtable:
1780 // This is similar to OMPTargetGlobalVarEntryIndirect, except that the
1781 // size field refers to the size of memory pointed to, not the size of
1782 // the pointer symbol itself (which is implicitly the size of a pointer).
1783 OMPBuilder.OffloadInfoManager.registerDeviceGlobalVarEntryInfo(
1784 Name, Addr, CGM.GetTargetTypeStoreSize(CGM.VoidPtrTy).getQuantity(),
1785 llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryIndirect,
1786 llvm::GlobalValue::WeakODRLinkage);
1787 }
1788
1789 void CGOpenMPRuntime::registerVTableOffloadEntry(llvm::GlobalVariable *VTable,
1790 const VarDecl *VD) {
1791 // TODO: add logic to avoid duplicate vtable registrations per
1792 // translation unit; though for external linkage, this should no
1793 // longer be an issue - or at least we can avoid the issue by
1794 // checking for an existing offloading entry. But, perhaps the
1795 // better approach is to defer emission of the vtables and offload
1796 // entries until later (by tracking a list of items that need to be
1797 // emitted).
1798
1799 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1800
1801 // Generate a new externally visible global to point to the
1802 // internally visible vtable. Doing this allows us to keep the
1803 // visibility and linkage of the associated vtable unchanged while
1804 // allowing the runtime to access its value. The externally
1805 // visible global var needs to be emitted with a unique mangled
1806 // name that won't conflict with similarly named (internal)
1807 // vtables in other translation units.
1808
1809 // Register vtable with source location of dynamic object in map
1810 // clause.
1811 llvm::TargetRegionEntryInfo EntryInfo = getEntryInfoFromPresumedLoc(
1812 CGM, OMPBuilder, VD->getCanonicalDecl()->getBeginLoc(),
1813 VTable->getName());
1814
1815 llvm::GlobalVariable *Addr = VTable;
1816 SmallString<128> AddrName;
1817 OMPBuilder.OffloadInfoManager.getTargetRegionEntryFnName(AddrName, EntryInfo);
1818 AddrName.append("addr");
1819
1820 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
1821 Addr = new llvm::GlobalVariable(
1822 CGM.getModule(), VTable->getType(),
1823 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, VTable,
1824 AddrName,
1825 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1826 CGM.getModule().getDataLayout().getDefaultGlobalsAddressSpace());
1827 Addr->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1828 }
1829 OMPBuilder.OffloadInfoManager.registerDeviceGlobalVarEntryInfo(
1830 AddrName, VTable,
1831 CGM.getDataLayout().getTypeAllocSize(VTable->getInitializer()->getType()),
1832 llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryIndirectVTable,
1833 llvm::GlobalValue::WeakODRLinkage);
1834 }
1835
1836 void CGOpenMPRuntime::emitAndRegisterVTable(CodeGenModule &CGM,
1837 CXXRecordDecl *CXXRecord,
1838 const VarDecl *VD) {
1839 // Register C++ VTable to OpenMP Offload Entry if it's a new
1840 // CXXRecordDecl.
1841 if (CXXRecord && CXXRecord->isDynamicClass() &&
1842 !CGM.getOpenMPRuntime().VTableDeclMap.contains(CXXRecord)) {
1843 auto Res = CGM.getOpenMPRuntime().VTableDeclMap.try_emplace(CXXRecord, VD);
1844 if (Res.second) {
1845 CGM.EmitVTable(CXXRecord);
1846 CodeGenVTables VTables = CGM.getVTables();
1847 llvm::GlobalVariable *VTablesAddr = VTables.GetAddrOfVTable(CXXRecord);
1848 assert(VTablesAddr && "Expected non-null VTable address");
1849 CGM.getOpenMPRuntime().registerVTableOffloadEntry(VTablesAddr, VD);
1850 // Emit VTable for all the fields containing dynamic CXXRecord
1851 for (const FieldDecl *Field : CXXRecord->fields()) {
1852 if (CXXRecordDecl *RecordDecl = Field->getType()->getAsCXXRecordDecl())
1853 emitAndRegisterVTable(CGM, RecordDecl, VD);
1854 }
1855 // Emit VTable for all dynamic parent class
1856 for (CXXBaseSpecifier &Base : CXXRecord->bases()) {
1857 if (CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl())
1858 emitAndRegisterVTable(CGM, BaseDecl, VD);
1859 }
1860 }
1861 }
1862 }
1863
1864 void CGOpenMPRuntime::registerVTable(const OMPExecutableDirective &D) {
1865 // Register VTable by scanning through the map clause of OpenMP target region.
1866 // Get CXXRecordDecl and VarDecl from Expr.
1867 auto GetVTableDecl = [](const Expr *E) {
1868 QualType VDTy = E->getType();
1869 CXXRecordDecl *CXXRecord = nullptr;
1870 if (const auto *RefType = VDTy->getAs<LValueReferenceType>())
1871 VDTy = RefType->getPointeeType();
1872 if (VDTy->isPointerType())
1873 CXXRecord = VDTy->getPointeeType()->getAsCXXRecordDecl();
1874 else
1875 CXXRecord = VDTy->getAsCXXRecordDecl();
1876
1877 const VarDecl *VD = nullptr;
1878 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
1879 VD = cast<VarDecl>(DRE->getDecl());
1880 } else if (auto *MRE = dyn_cast<MemberExpr>(E)) {
1881 if (auto *BaseDRE = dyn_cast<DeclRefExpr>(MRE->getBase())) {
1882 if (auto *BaseVD = dyn_cast<VarDecl>(BaseDRE->getDecl()))
1883 VD = BaseVD;
1884 }
1885 }
1886 return std::pair<CXXRecordDecl *, const VarDecl *>(CXXRecord, VD);
1887 };
1888 // Collect VTable from OpenMP map clause.
1889 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
1890 for (const auto *E : C->varlist()) {
1891 auto DeclPair = GetVTableDecl(E);
1892 // Ensure VD is not null
1893 if (DeclPair.second)
1894 emitAndRegisterVTable(CGM, DeclPair.first, DeclPair.second);
1895 }
1896 }
1897 }
1898
1899 Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
1900 QualType VarType,
1901 StringRef Name) {
1902 std::string Suffix = getName({"artificial", ""});
1903 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
1904 llvm::GlobalVariable *GAddr = OMPBuilder.getOrCreateInternalVariable(
1905 VarLVType, Twine(Name).concat(Suffix).str());
1906 if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS &&
1907 CGM.getTarget().isTLSSupported()) {
1908 GAddr->setThreadLocal(/*Val=*/true);
1909 return Address(GAddr, GAddr->getValueType(),
1910 CGM.getContext().getTypeAlignInChars(VarType));
1911 }
1912 std::string CacheSuffix = getName({"cache", ""});
1913 llvm::Value *Args[] = {
1914 emitUpdateLocation(CGF, SourceLocation()),
1915 getThreadID(CGF, SourceLocation()),
1916 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
1917 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
1918 /*isSigned=*/false),
1919 OMPBuilder.getOrCreateInternalVariable(
1920 CGM.VoidPtrPtrTy,
1921 Twine(Name).concat(Suffix).concat(CacheSuffix).str())};
1922 return Address(
1923 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1924 CGF.EmitRuntimeCall(
1925 OMPBuilder.getOrCreateRuntimeFunction(
1926 CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
1927 Args),
1928 CGF.Builder.getPtrTy(0)),
1929 VarLVType, CGM.getContext().getTypeAlignInChars(VarType));
1930 }
1931
1932 void CGOpenMPRuntime::emitIfClause(CodeGenFunction &CGF, const Expr *Cond,
1933 const RegionCodeGenTy &ThenGen,
1934 const RegionCodeGenTy &ElseGen) {
1935 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1936
1937 // If the condition constant folds and can be elided, try to avoid emitting
1938 // the condition and the dead arm of the if/else.
1939 bool CondConstant;
1940 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1941 if (CondConstant)
1942 ThenGen(CGF);
1943 else
1944 ElseGen(CGF);
1945 return;
1946 }
1947
1948 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1949 // emit the conditional branch.
1950 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
1951 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
1952 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
1953 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1954
1955 // Emit the 'then' code.
1956 CGF.EmitBlock(ThenBlock);
1957 ThenGen(CGF);
1958 CGF.EmitBranch(ContBlock);
1959 // Emit the 'else' code if present.
1960 // There is no need to emit line number for unconditional branch.
1961 (void)ApplyDebugLocation::CreateEmpty(CGF);
1962 CGF.EmitBlock(ElseBlock);
1963 ElseGen(CGF);
1964 // There is no need to emit line number for unconditional branch.
1965 (void)ApplyDebugLocation::CreateEmpty(CGF);
1966 CGF.EmitBranch(ContBlock);
1967 // Emit the continuation block for code after the if.
1968 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
1969 }
1970
1971 void CGOpenMPRuntime::emitParallelCall(
1972 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
1973 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond,
1974 llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier,
1975 OpenMPSeverityClauseKind Severity, const Expr *Message) {
1976 if (!CGF.HaveInsertPoint())
1977 return;
1978 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1979 auto &M = CGM.getModule();
1980 auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc,
1981 this](CodeGenFunction &CGF, PrePostActionTy &) {
1982 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1983 llvm::Value *Args[] = {
1984 RTLoc,
1985 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1986 OutlinedFn};
1987 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1988 RealArgs.append(std::begin(Args), std::end(Args));
1989 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1990
1991 llvm::FunctionCallee RTLFn =
1992 OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_fork_call);
1993 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1994 };
1995 auto &&ElseGen = [&M, OutlinedFn, CapturedVars, RTLoc, Loc,
1996 this](CodeGenFunction &CGF, PrePostActionTy &) {
1997 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
1998 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
1999 // Build calls:
2000 // __kmpc_serialized_parallel(&Loc, GTid);
2001 llvm::Value *Args[] = {RTLoc, ThreadID};
2002 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2003 M, OMPRTL___kmpc_serialized_parallel),
2004 Args);
2005
2006 // OutlinedFn(&GTid, &zero_bound, CapturedStruct);
2007 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2008 RawAddress ZeroAddrBound =
2009 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2010 /*Name=*/".bound.zero.addr");
2011 CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddrBound);
2012 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2013 // ThreadId for serialized parallels is 0.
2014 OutlinedFnArgs.push_back(ThreadIDAddr.emitRawPointer(CGF));
2015 OutlinedFnArgs.push_back(ZeroAddrBound.getPointer());
2016 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2017
2018 // Ensure we do not inline the function. This is trivially true for the ones
2019 // passed to __kmpc_fork_call but the ones called in serialized regions
2020 // could be inlined. This is not a perfect but it is closer to the invariant
2021 // we want, namely, every data environment starts with a new function.
2022 // TODO: We should pass the if condition to the runtime function and do the
2023 // handling there. Much cleaner code.
2024 OutlinedFn->removeFnAttr(llvm::Attribute::AlwaysInline);
2025 OutlinedFn->addFnAttr(llvm::Attribute::NoInline);
2026 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2027
2028 // __kmpc_end_serialized_parallel(&Loc, GTid);
2029 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2030 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2031 M, OMPRTL___kmpc_end_serialized_parallel),
2032 EndArgs);
2033 };
2034 if (IfCond) {
2035 emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2036 } else {
2037 RegionCodeGenTy ThenRCG(ThenGen);
2038 ThenRCG(CGF);
2039 }
2040 }
2041
2042 // If we're inside an (outlined) parallel region, use the region info's
2043 // thread-ID variable (it is passed in a first argument of the outlined function
2044 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2045 // regular serial code region, get thread ID by calling kmp_int32
2046 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2047 // return the address of that temp.
2048 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2049 SourceLocation Loc) {
2050 if (auto *OMPRegionInfo =
2051 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2052 if (OMPRegionInfo->getThreadIDVariable())
2053 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2054
2055 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2056 QualType Int32Ty =
2057 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2058 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2059 CGF.EmitStoreOfScalar(ThreadID,
2060 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2061
2062 return ThreadIDTemp;
2063 }
2064
2065 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2066 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2067 std::string Name = getName({Prefix, "var"});
2068 return OMPBuilder.getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2069 }
2070
2071 namespace {
2072 /// Common pre(post)-action for different OpenMP constructs.
2073 class CommonActionTy final : public PrePostActionTy {
2074 llvm::FunctionCallee EnterCallee;
2075 ArrayRef<llvm::Value *> EnterArgs;
2076 llvm::FunctionCallee ExitCallee;
2077 ArrayRef<llvm::Value *> ExitArgs;
2078 bool Conditional;
2079 llvm::BasicBlock *ContBlock = nullptr;
2080
2081 public:
2082 CommonActionTy(llvm::FunctionCallee EnterCallee,
2083 ArrayRef<llvm::Value *> EnterArgs,
2084 llvm::FunctionCallee ExitCallee,
2085 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
2086 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2087 ExitArgs(ExitArgs), Conditional(Conditional) {}
2088 void Enter(CodeGenFunction &CGF) override {
2089 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2090 if (Conditional) {
2091 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2092 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2093 ContBlock = CGF.createBasicBlock("omp_if.end");
2094 // Generate the branch (If-stmt)
2095 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2096 CGF.EmitBlock(ThenBlock);
2097 }
2098 }
2099 void Done(CodeGenFunction &CGF) {
2100 // Emit the rest of blocks/branches
2101 CGF.EmitBranch(ContBlock);
2102 CGF.EmitBlock(ContBlock, true);
2103 }
2104 void Exit(CodeGenFunction &CGF) override {
2105 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2106 }
2107 };
2108 } // anonymous namespace
2109
2110 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2111 StringRef CriticalName,
2112 const RegionCodeGenTy &CriticalOpGen,
2113 SourceLocation Loc, const Expr *Hint) {
2114 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2115 // CriticalOpGen();
2116 // __kmpc_end_critical(ident_t *, gtid, Lock);
2117 // Prepare arguments and build a call to __kmpc_critical
2118 if (!CGF.HaveInsertPoint())
2119 return;
2120 llvm::FunctionCallee RuntimeFcn = OMPBuilder.getOrCreateRuntimeFunction(
2121 CGM.getModule(),
2122 Hint ? OMPRTL___kmpc_critical_with_hint : OMPRTL___kmpc_critical);
2123 llvm::Value *LockVar = getCriticalRegionLock(CriticalName);
2124 unsigned LockVarArgIdx = 2;
2125 if (cast<llvm::GlobalVariable>(LockVar)->getAddressSpace() !=
2126 RuntimeFcn.getFunctionType()
2127 ->getParamType(LockVarArgIdx)
2128 ->getPointerAddressSpace())
2129 LockVar = CGF.Builder.CreateAddrSpaceCast(
2130 LockVar, RuntimeFcn.getFunctionType()->getParamType(LockVarArgIdx));
2131 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2132 LockVar};
2133 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2134 std::end(Args));
2135 if (Hint) {
2136 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2137 CGF.EmitScalarExpr(Hint), CGM.Int32Ty, /*isSigned=*/false));
2138 }
2139 CommonActionTy Action(RuntimeFcn, EnterArgs,
2140 OMPBuilder.getOrCreateRuntimeFunction(
2141 CGM.getModule(), OMPRTL___kmpc_end_critical),
2142 Args);
2143 CriticalOpGen.setAction(Action);
2144 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2145 }
2146
2147 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2148 const RegionCodeGenTy &MasterOpGen,
2149 SourceLocation Loc) {
2150 if (!CGF.HaveInsertPoint())
2151 return;
2152 // if(__kmpc_master(ident_t *, gtid)) {
2153 // MasterOpGen();
2154 // __kmpc_end_master(ident_t *, gtid);
2155 // }
2156 // Prepare arguments and build a call to __kmpc_master
2157 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2158 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2159 CGM.getModule(), OMPRTL___kmpc_master),
2160 Args,
2161 OMPBuilder.getOrCreateRuntimeFunction(
2162 CGM.getModule(), OMPRTL___kmpc_end_master),
2163 Args,
2164 /*Conditional=*/true);
2165 MasterOpGen.setAction(Action);
2166 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2167 Action.Done(CGF);
2168 }
2169
2170 void CGOpenMPRuntime::emitMaskedRegion(CodeGenFunction &CGF,
2171 const RegionCodeGenTy &MaskedOpGen,
2172 SourceLocation Loc, const Expr *Filter) {
2173 if (!CGF.HaveInsertPoint())
2174 return;
2175 // if(__kmpc_masked(ident_t *, gtid, filter)) {
2176 // MaskedOpGen();
2177 // __kmpc_end_masked(iden_t *, gtid);
2178 // }
2179 // Prepare arguments and build a call to __kmpc_masked
2180 llvm::Value *FilterVal = Filter
2181 ? CGF.EmitScalarExpr(Filter, CGF.Int32Ty)
2182 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
2183 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2184 FilterVal};
2185 llvm::Value *ArgsEnd[] = {emitUpdateLocation(CGF, Loc),
2186 getThreadID(CGF, Loc)};
2187 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2188 CGM.getModule(), OMPRTL___kmpc_masked),
2189 Args,
2190 OMPBuilder.getOrCreateRuntimeFunction(
2191 CGM.getModule(), OMPRTL___kmpc_end_masked),
2192 ArgsEnd,
2193 /*Conditional=*/true);
2194 MaskedOpGen.setAction(Action);
2195 emitInlinedDirective(CGF, OMPD_masked, MaskedOpGen);
2196 Action.Done(CGF);
2197 }
2198
2199 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2200 SourceLocation Loc) {
2201 if (!CGF.HaveInsertPoint())
2202 return;
2203 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2204 OMPBuilder.createTaskyield(CGF.Builder);
2205 } else {
2206 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2207 llvm::Value *Args[] = {
2208 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2209 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2210 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2211 CGM.getModule(), OMPRTL___kmpc_omp_taskyield),
2212 Args);
2213 }
2214
2215 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2216 Region->emitUntiedSwitch(CGF);
2217 }
2218
2219 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2220 const RegionCodeGenTy &TaskgroupOpGen,
2221 SourceLocation Loc) {
2222 if (!CGF.HaveInsertPoint())
2223 return;
2224 // __kmpc_taskgroup(ident_t *, gtid);
2225 // TaskgroupOpGen();
2226 // __kmpc_end_taskgroup(ident_t *, gtid);
2227 // Prepare arguments and build a call to __kmpc_taskgroup
2228 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2229 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2230 CGM.getModule(), OMPRTL___kmpc_taskgroup),
2231 Args,
2232 OMPBuilder.getOrCreateRuntimeFunction(
2233 CGM.getModule(), OMPRTL___kmpc_end_taskgroup),
2234 Args);
2235 TaskgroupOpGen.setAction(Action);
2236 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2237 }
2238
2239 /// Given an array of pointers to variables, project the address of a
2240 /// given variable.
2241 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2242 unsigned Index, const VarDecl *Var) {
2243 // Pull out the pointer to the variable.
2244 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
2245 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2246
2247 llvm::Type *ElemTy = CGF.ConvertTypeForMem(Var->getType());
2248 return Address(Ptr, ElemTy, CGF.getContext().getDeclAlign(Var));
2249 }
2250
2251 static llvm::Value *emitCopyprivateCopyFunction(
2252 CodeGenModule &CGM, llvm::Type *ArgsElemType,
2253 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2254 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2255 SourceLocation Loc) {
2256 ASTContext &C = CGM.getContext();
2257 // void copy_func(void *LHSArg, void *RHSArg);
2258 FunctionArgList Args;
2259 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2260 ImplicitParamKind::Other);
2261 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2262 ImplicitParamKind::Other);
2263 Args.push_back(&LHSArg);
2264 Args.push_back(&RHSArg);
2265 const auto &CGFI =
2266 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2267 std::string Name =
2268 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
2269 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2270 llvm::GlobalValue::InternalLinkage, Name,
2271 &CGM.getModule());
2272 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2273 Fn->setDoesNotRecurse();
2274 CodeGenFunction CGF(CGM);
2275 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2276 // Dest = (void*[n])(LHSArg);
2277 // Src = (void*[n])(RHSArg);
2278 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2279 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2280 CGF.Builder.getPtrTy(0)),
2281 ArgsElemType, CGF.getPointerAlign());
2282 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2283 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2284 CGF.Builder.getPtrTy(0)),
2285 ArgsElemType, CGF.getPointerAlign());
2286 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2287 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2288 // ...
2289 // *(Typen*)Dst[n] = *(Typen*)Src[n];
2290 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2291 const auto *DestVar =
2292 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2293 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2294
2295 const auto *SrcVar =
2296 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2297 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2298
2299 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2300 QualType Type = VD->getType();
2301 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2302 }
2303 CGF.FinishFunction();
2304 return Fn;
2305 }
2306
2307 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2308 const RegionCodeGenTy &SingleOpGen,
2309 SourceLocation Loc,
2310 ArrayRef<const Expr *> CopyprivateVars,
2311 ArrayRef<const Expr *> SrcExprs,
2312 ArrayRef<const Expr *> DstExprs,
2313 ArrayRef<const Expr *> AssignmentOps) {
2314 if (!CGF.HaveInsertPoint())
2315 return;
2316 assert(CopyprivateVars.size() == SrcExprs.size() &&
2317 CopyprivateVars.size() == DstExprs.size() &&
2318 CopyprivateVars.size() == AssignmentOps.size());
2319 ASTContext &C = CGM.getContext();
2320 // int32 did_it = 0;
2321 // if(__kmpc_single(ident_t *, gtid)) {
2322 // SingleOpGen();
2323 // __kmpc_end_single(ident_t *, gtid);
2324 // did_it = 1;
2325 // }
2326 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2327 // <copy_func>, did_it);
2328
2329 Address DidIt = Address::invalid();
2330 if (!CopyprivateVars.empty()) {
2331 // int32 did_it = 0;
2332 QualType KmpInt32Ty =
2333 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2334 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2335 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2336 }
2337 // Prepare arguments and build a call to __kmpc_single
2338 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2339 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2340 CGM.getModule(), OMPRTL___kmpc_single),
2341 Args,
2342 OMPBuilder.getOrCreateRuntimeFunction(
2343 CGM.getModule(), OMPRTL___kmpc_end_single),
2344 Args,
2345 /*Conditional=*/true);
2346 SingleOpGen.setAction(Action);
2347 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2348 if (DidIt.isValid()) {
2349 // did_it = 1;
2350 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2351 }
2352 Action.Done(CGF);
2353 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2354 // <copy_func>, did_it);
2355 if (DidIt.isValid()) {
2356 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2357 QualType CopyprivateArrayTy = C.getConstantArrayType(
2358 C.VoidPtrTy, ArraySize, nullptr, ArraySizeModifier::Normal,
2359 /*IndexTypeQuals=*/0);
2360 // Create a list of all private variables for copyprivate.
2361 Address CopyprivateList =
2362 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2363 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2364 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
2365 CGF.Builder.CreateStore(
2366 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2367 CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF),
2368 CGF.VoidPtrTy),
2369 Elem);
2370 }
2371 // Build function that copies private values from single region to all other
2372 // threads in the corresponding parallel region.
2373 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
2374 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), CopyprivateVars,
2375 SrcExprs, DstExprs, AssignmentOps, Loc);
2376 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2377 Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2378 CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty);
2379 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
2380 llvm::Value *Args[] = {
2381 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2382 getThreadID(CGF, Loc), // i32 <gtid>
2383 BufSize, // size_t <buf_size>
2384 CL.emitRawPointer(CGF), // void *<copyprivate list>
2385 CpyFn, // void (*) (void *, void *) <copy_func>
2386 DidItVal // i32 did_it
2387 };
2388 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2389 CGM.getModule(), OMPRTL___kmpc_copyprivate),
2390 Args);
2391 }
2392 }
2393
2394 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2395 const RegionCodeGenTy &OrderedOpGen,
2396 SourceLocation Loc, bool IsThreads) {
2397 if (!CGF.HaveInsertPoint())
2398 return;
2399 // __kmpc_ordered(ident_t *, gtid);
2400 // OrderedOpGen();
2401 // __kmpc_end_ordered(ident_t *, gtid);
2402 // Prepare arguments and build a call to __kmpc_ordered
2403 if (IsThreads) {
2404 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2405 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2406 CGM.getModule(), OMPRTL___kmpc_ordered),
2407 Args,
2408 OMPBuilder.getOrCreateRuntimeFunction(
2409 CGM.getModule(), OMPRTL___kmpc_end_ordered),
2410 Args);
2411 OrderedOpGen.setAction(Action);
2412 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2413 return;
2414 }
2415 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2416 }
2417
2418 unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
2419 unsigned Flags;
2420 if (Kind == OMPD_for)
2421 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2422 else if (Kind == OMPD_sections)
2423 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2424 else if (Kind == OMPD_single)
2425 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2426 else if (Kind == OMPD_barrier)
2427 Flags = OMP_IDENT_BARRIER_EXPL;
2428 else
2429 Flags = OMP_IDENT_BARRIER_IMPL;
2430 return Flags;
2431 }
2432
2433 void CGOpenMPRuntime::getDefaultScheduleAndChunk(
2434 CodeGenFunction &CGF, const OMPLoopDirective &S,
2435 OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
2436 // Check if the loop directive is actually a doacross loop directive. In this
2437 // case choose static, 1 schedule.
2438 if (llvm::any_of(
2439 S.getClausesOfKind<OMPOrderedClause>(),
2440 [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
2441 ScheduleKind = OMPC_SCHEDULE_static;
2442 // Chunk size is 1 in this case.
2443 llvm::APInt ChunkSize(32, 1);
2444 ChunkExpr = IntegerLiteral::Create(
2445 CGF.getContext(), ChunkSize,
2446 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2447 SourceLocation());
2448 }
2449 }
2450
2451 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2452 OpenMPDirectiveKind Kind, bool EmitChecks,
2453 bool ForceSimpleCall) {
2454 // Check if we should use the OMPBuilder
2455 auto *OMPRegionInfo =
2456 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo);
2457 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2458 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
2459 cantFail(OMPBuilder.createBarrier(CGF.Builder, Kind, ForceSimpleCall,
2460 EmitChecks));
2461 CGF.Builder.restoreIP(AfterIP);
2462 return;
2463 }
2464
2465 if (!CGF.HaveInsertPoint())
2466 return;
2467 // Build call __kmpc_cancel_barrier(loc, thread_id);
2468 // Build call __kmpc_barrier(loc, thread_id);
2469 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2470 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2471 // thread_id);
2472 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2473 getThreadID(CGF, Loc)};
2474 if (OMPRegionInfo) {
2475 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2476 llvm::Value *Result = CGF.EmitRuntimeCall(
2477 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2478 OMPRTL___kmpc_cancel_barrier),
2479 Args);
2480 if (EmitChecks) {
2481 // if (__kmpc_cancel_barrier()) {
2482 // exit from construct;
2483 // }
2484 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
2485 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
2486 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
2487 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2488 CGF.EmitBlock(ExitBB);
2489 // exit from construct;
2490 CodeGenFunction::JumpDest CancelDestination =
2491 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2492 CGF.EmitBranchThroughCleanup(CancelDestination);
2493 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2494 }
2495 return;
2496 }
2497 }
2498 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2499 CGM.getModule(), OMPRTL___kmpc_barrier),
2500 Args);
2501 }
2502
2503 void CGOpenMPRuntime::emitErrorCall(CodeGenFunction &CGF, SourceLocation Loc,
2504 Expr *ME, bool IsFatal) {
2505 llvm::Value *MVL = ME ? CGF.EmitScalarExpr(ME)
2506 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2507 // Build call void __kmpc_error(ident_t *loc, int severity, const char
2508 // *message)
2509 llvm::Value *Args[] = {
2510 emitUpdateLocation(CGF, Loc, /*Flags=*/0, /*GenLoc=*/true),
2511 llvm::ConstantInt::get(CGM.Int32Ty, IsFatal ? 2 : 1),
2512 CGF.Builder.CreatePointerCast(MVL, CGM.Int8PtrTy)};
2513 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2514 CGM.getModule(), OMPRTL___kmpc_error),
2515 Args);
2516 }
2517
2518 /// Map the OpenMP loop schedule to the runtime enumeration.
2519 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2520 bool Chunked, bool Ordered) {
2521 switch (ScheduleKind) {
2522 case OMPC_SCHEDULE_static:
2523 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2524 : (Ordered ? OMP_ord_static : OMP_sch_static);
2525 case OMPC_SCHEDULE_dynamic:
2526 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2527 case OMPC_SCHEDULE_guided:
2528 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2529 case OMPC_SCHEDULE_runtime:
2530 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2531 case OMPC_SCHEDULE_auto:
2532 return Ordered ? OMP_ord_auto : OMP_sch_auto;
2533 case OMPC_SCHEDULE_unknown:
2534 assert(!Chunked && "chunk was specified but schedule kind not known");
2535 return Ordered ? OMP_ord_static : OMP_sch_static;
2536 }
2537 llvm_unreachable("Unexpected runtime schedule");
2538 }
2539
2540 /// Map the OpenMP distribute schedule to the runtime enumeration.
2541 static OpenMPSchedType
2542 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2543 // only static is allowed for dist_schedule
2544 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2545 }
2546
2547 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2548 bool Chunked) const {
2549 OpenMPSchedType Schedule =
2550 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2551 return Schedule == OMP_sch_static;
2552 }
2553
2554 bool CGOpenMPRuntime::isStaticNonchunked(
2555 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2556 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2557 return Schedule == OMP_dist_sch_static;
2558 }
2559
2560 bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
2561 bool Chunked) const {
2562 OpenMPSchedType Schedule =
2563 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2564 return Schedule == OMP_sch_static_chunked;
2565 }
2566
2567 bool CGOpenMPRuntime::isStaticChunked(
2568 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2569 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2570 return Schedule == OMP_dist_sch_static_chunked;
2571 }
2572
2573 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2574 OpenMPSchedType Schedule =
2575 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2576 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2577 return Schedule != OMP_sch_static;
2578 }
2579
2580 static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule,
2581 OpenMPScheduleClauseModifier M1,
2582 OpenMPScheduleClauseModifier M2) {
2583 int Modifier = 0;
2584 switch (M1) {
2585 case OMPC_SCHEDULE_MODIFIER_monotonic:
2586 Modifier = OMP_sch_modifier_monotonic;
2587 break;
2588 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2589 Modifier = OMP_sch_modifier_nonmonotonic;
2590 break;
2591 case OMPC_SCHEDULE_MODIFIER_simd:
2592 if (Schedule == OMP_sch_static_chunked)
2593 Schedule = OMP_sch_static_balanced_chunked;
2594 break;
2595 case OMPC_SCHEDULE_MODIFIER_last:
2596 case OMPC_SCHEDULE_MODIFIER_unknown:
2597 break;
2598 }
2599 switch (M2) {
2600 case OMPC_SCHEDULE_MODIFIER_monotonic:
2601 Modifier = OMP_sch_modifier_monotonic;
2602 break;
2603 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2604 Modifier = OMP_sch_modifier_nonmonotonic;
2605 break;
2606 case OMPC_SCHEDULE_MODIFIER_simd:
2607 if (Schedule == OMP_sch_static_chunked)
2608 Schedule = OMP_sch_static_balanced_chunked;
2609 break;
2610 case OMPC_SCHEDULE_MODIFIER_last:
2611 case OMPC_SCHEDULE_MODIFIER_unknown:
2612 break;
2613 }
2614 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription.
2615 // If the static schedule kind is specified or if the ordered clause is
2616 // specified, and if the nonmonotonic modifier is not specified, the effect is
2617 // as if the monotonic modifier is specified. Otherwise, unless the monotonic
2618 // modifier is specified, the effect is as if the nonmonotonic modifier is
2619 // specified.
2620 if (CGM.getLangOpts().OpenMP >= 50 && Modifier == 0) {
2621 if (!(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static ||
2622 Schedule == OMP_sch_static_balanced_chunked ||
2623 Schedule == OMP_ord_static_chunked || Schedule == OMP_ord_static ||
2624 Schedule == OMP_dist_sch_static_chunked ||
2625 Schedule == OMP_dist_sch_static))
2626 Modifier = OMP_sch_modifier_nonmonotonic;
2627 }
2628 return Schedule | Modifier;
2629 }
2630
2631 void CGOpenMPRuntime::emitForDispatchInit(
2632 CodeGenFunction &CGF, SourceLocation Loc,
2633 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2634 bool Ordered, const DispatchRTInput &DispatchValues) {
2635 if (!CGF.HaveInsertPoint())
2636 return;
2637 OpenMPSchedType Schedule = getRuntimeSchedule(
2638 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
2639 assert(Ordered ||
2640 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2641 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2642 Schedule != OMP_sch_static_balanced_chunked));
2643 // Call __kmpc_dispatch_init(
2644 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2645 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2646 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
2647
2648 // If the Chunk was not specified in the clause - use default value 1.
2649 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2650 : CGF.Builder.getIntN(IVSize, 1);
2651 llvm::Value *Args[] = {
2652 emitUpdateLocation(CGF, Loc),
2653 getThreadID(CGF, Loc),
2654 CGF.Builder.getInt32(addMonoNonMonoModifier(
2655 CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2656 DispatchValues.LB, // Lower
2657 DispatchValues.UB, // Upper
2658 CGF.Builder.getIntN(IVSize, 1), // Stride
2659 Chunk // Chunk
2660 };
2661 CGF.EmitRuntimeCall(OMPBuilder.createDispatchInitFunction(IVSize, IVSigned),
2662 Args);
2663 }
2664
2665 void CGOpenMPRuntime::emitForDispatchDeinit(CodeGenFunction &CGF,
2666 SourceLocation Loc) {
2667 if (!CGF.HaveInsertPoint())
2668 return;
2669 // Call __kmpc_dispatch_deinit(ident_t *loc, kmp_int32 tid);
2670 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2671 CGF.EmitRuntimeCall(OMPBuilder.createDispatchDeinitFunction(), Args);
2672 }
2673
2674 static void emitForStaticInitCall(
2675 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2676 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
2677 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2678 const CGOpenMPRuntime::StaticRTInput &Values) {
2679 if (!CGF.HaveInsertPoint())
2680 return;
2681
2682 assert(!Values.Ordered);
2683 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2684 Schedule == OMP_sch_static_balanced_chunked ||
2685 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2686 Schedule == OMP_dist_sch_static ||
2687 Schedule == OMP_dist_sch_static_chunked);
2688
2689 // Call __kmpc_for_static_init(
2690 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2691 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2692 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2693 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2694 llvm::Value *Chunk = Values.Chunk;
2695 if (Chunk == nullptr) {
2696 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2697 Schedule == OMP_dist_sch_static) &&
2698 "expected static non-chunked schedule");
2699 // If the Chunk was not specified in the clause - use default value 1.
2700 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2701 } else {
2702 assert((Schedule == OMP_sch_static_chunked ||
2703 Schedule == OMP_sch_static_balanced_chunked ||
2704 Schedule == OMP_ord_static_chunked ||
2705 Schedule == OMP_dist_sch_static_chunked) &&
2706 "expected static chunked schedule");
2707 }
2708 llvm::Value *Args[] = {
2709 UpdateLocation,
2710 ThreadId,
2711 CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1,
2712 M2)), // Schedule type
2713 Values.IL.emitRawPointer(CGF), // &isLastIter
2714 Values.LB.emitRawPointer(CGF), // &LB
2715 Values.UB.emitRawPointer(CGF), // &UB
2716 Values.ST.emitRawPointer(CGF), // &Stride
2717 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
2718 Chunk // Chunk
2719 };
2720 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2721 }
2722
2723 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2724 SourceLocation Loc,
2725 OpenMPDirectiveKind DKind,
2726 const OpenMPScheduleTy &ScheduleKind,
2727 const StaticRTInput &Values) {
2728 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
2729 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
2730 assert((isOpenMPWorksharingDirective(DKind) || (DKind == OMPD_loop)) &&
2731 "Expected loop-based or sections-based directive.");
2732 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
2733 isOpenMPLoopDirective(DKind)
2734 ? OMP_IDENT_WORK_LOOP
2735 : OMP_IDENT_WORK_SECTIONS);
2736 llvm::Value *ThreadId = getThreadID(CGF, Loc);
2737 llvm::FunctionCallee StaticInitFunction =
2738 OMPBuilder.createForStaticInitFunction(Values.IVSize, Values.IVSigned,
2739 false);
2740 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
2741 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2742 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
2743 }
2744
2745 void CGOpenMPRuntime::emitDistributeStaticInit(
2746 CodeGenFunction &CGF, SourceLocation Loc,
2747 OpenMPDistScheduleClauseKind SchedKind,
2748 const CGOpenMPRuntime::StaticRTInput &Values) {
2749 OpenMPSchedType ScheduleNum =
2750 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
2751 llvm::Value *UpdatedLocation =
2752 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
2753 llvm::Value *ThreadId = getThreadID(CGF, Loc);
2754 llvm::FunctionCallee StaticInitFunction;
2755 bool isGPUDistribute =
2756 CGM.getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU();
2757 StaticInitFunction = OMPBuilder.createForStaticInitFunction(
2758 Values.IVSize, Values.IVSigned, isGPUDistribute);
2759
2760 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2761 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2762 OMPC_SCHEDULE_MODIFIER_unknown, Values);
2763 }
2764
2765 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2766 SourceLocation Loc,
2767 OpenMPDirectiveKind DKind) {
2768 assert((DKind == OMPD_distribute || DKind == OMPD_for ||
2769 DKind == OMPD_sections) &&
2770 "Expected distribute, for, or sections directive kind");
2771 if (!CGF.HaveInsertPoint())
2772 return;
2773 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2774 llvm::Value *Args[] = {
2775 emitUpdateLocation(CGF, Loc,
2776 isOpenMPDistributeDirective(DKind) ||
2777 (DKind == OMPD_target_teams_loop)
2778 ? OMP_IDENT_WORK_DISTRIBUTE
2779 : isOpenMPLoopDirective(DKind)
2780 ? OMP_IDENT_WORK_LOOP
2781 : OMP_IDENT_WORK_SECTIONS),
2782 getThreadID(CGF, Loc)};
2783 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
2784 if (isOpenMPDistributeDirective(DKind) &&
2785 CGM.getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU())
2786 CGF.EmitRuntimeCall(
2787 OMPBuilder.getOrCreateRuntimeFunction(
2788 CGM.getModule(), OMPRTL___kmpc_distribute_static_fini),
2789 Args);
2790 else
2791 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2792 CGM.getModule(), OMPRTL___kmpc_for_static_fini),
2793 Args);
2794 }
2795
2796 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2797 SourceLocation Loc,
2798 unsigned IVSize,
2799 bool IVSigned) {
2800 if (!CGF.HaveInsertPoint())
2801 return;
2802 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2803 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2804 CGF.EmitRuntimeCall(OMPBuilder.createDispatchFiniFunction(IVSize, IVSigned),
2805 Args);
2806 }
2807
2808 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2809 SourceLocation Loc, unsigned IVSize,
2810 bool IVSigned, Address IL,
2811 Address LB, Address UB,
2812 Address ST) {
2813 // Call __kmpc_dispatch_next(
2814 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2815 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2816 // kmp_int[32|64] *p_stride);
2817 llvm::Value *Args[] = {
2818 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2819 IL.emitRawPointer(CGF), // &isLastIter
2820 LB.emitRawPointer(CGF), // &Lower
2821 UB.emitRawPointer(CGF), // &Upper
2822 ST.emitRawPointer(CGF) // &Stride
2823 };
2824 llvm::Value *Call = CGF.EmitRuntimeCall(
2825 OMPBuilder.createDispatchNextFunction(IVSize, IVSigned), Args);
2826 return CGF.EmitScalarConversion(
2827 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
2828 CGF.getContext().BoolTy, Loc);
2829 }
2830
2831 llvm::Value *CGOpenMPRuntime::emitMessageClause(CodeGenFunction &CGF,
2832 const Expr *Message,
2833 SourceLocation Loc) {
2834 if (!Message)
2835 return llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
2836 return CGF.EmitScalarExpr(Message);
2837 }
2838
2839 llvm::Value *
2840 CGOpenMPRuntime::emitSeverityClause(OpenMPSeverityClauseKind Severity,
2841 SourceLocation Loc) {
2842 // OpenMP 6.0, 10.4: "If no severity clause is specified then the effect is
2843 // as if sev-level is fatal."
2844 return llvm::ConstantInt::get(CGM.Int32Ty,
2845 Severity == OMPC_SEVERITY_warning ? 1 : 2);
2846 }
2847
2848 void CGOpenMPRuntime::emitNumThreadsClause(
2849 CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc,
2850 OpenMPNumThreadsClauseModifier Modifier, OpenMPSeverityClauseKind Severity,
2851 SourceLocation SeverityLoc, const Expr *Message,
2852 SourceLocation MessageLoc) {
2853 if (!CGF.HaveInsertPoint())
2854 return;
2855 llvm::SmallVector<llvm::Value *, 4> Args(
2856 {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2857 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)});
2858 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2859 // or __kmpc_push_num_threads_strict(&loc, global_tid, num_threads, severity,
2860 // messsage) if strict modifier is used.
2861 RuntimeFunction FnID = OMPRTL___kmpc_push_num_threads;
2862 if (Modifier == OMPC_NUMTHREADS_strict) {
2863 FnID = OMPRTL___kmpc_push_num_threads_strict;
2864 Args.push_back(emitSeverityClause(Severity, SeverityLoc));
2865 Args.push_back(emitMessageClause(CGF, Message, MessageLoc));
2866 }
2867 CGF.EmitRuntimeCall(
2868 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), FnID), Args);
2869 }
2870
2871 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2872 ProcBindKind ProcBind,
2873 SourceLocation Loc) {
2874 if (!CGF.HaveInsertPoint())
2875 return;
2876 assert(ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.");
2877 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2878 llvm::Value *Args[] = {
2879 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2880 llvm::ConstantInt::get(CGM.IntTy, unsigned(ProcBind), /*isSigned=*/true)};
2881 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2882 CGM.getModule(), OMPRTL___kmpc_push_proc_bind),
2883 Args);
2884 }
2885
2886 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2887 SourceLocation Loc, llvm::AtomicOrdering AO) {
2888 if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2889 OMPBuilder.createFlush(CGF.Builder);
2890 } else {
2891 if (!CGF.HaveInsertPoint())
2892 return;
2893 // Build call void __kmpc_flush(ident_t *loc)
2894 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2895 CGM.getModule(), OMPRTL___kmpc_flush),
2896 emitUpdateLocation(CGF, Loc));
2897 }
2898 }
2899
2900 namespace {
2901 /// Indexes of fields for type kmp_task_t.
2902 enum KmpTaskTFields {
2903 /// List of shared variables.
2904 KmpTaskTShareds,
2905 /// Task routine.
2906 KmpTaskTRoutine,
2907 /// Partition id for the untied tasks.
2908 KmpTaskTPartId,
2909 /// Function with call of destructors for private variables.
2910 Data1,
2911 /// Task priority.
2912 Data2,
2913 /// (Taskloops only) Lower bound.
2914 KmpTaskTLowerBound,
2915 /// (Taskloops only) Upper bound.
2916 KmpTaskTUpperBound,
2917 /// (Taskloops only) Stride.
2918 KmpTaskTStride,
2919 /// (Taskloops only) Is last iteration flag.
2920 KmpTaskTLastIter,
2921 /// (Taskloops only) Reduction data.
2922 KmpTaskTReductions,
2923 };
2924 } // anonymous namespace
2925
2926 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2927 // If we are in simd mode or there are no entries, we don't need to do
2928 // anything.
2929 if (CGM.getLangOpts().OpenMPSimd || OMPBuilder.OffloadInfoManager.empty())
2930 return;
2931
2932 llvm::OpenMPIRBuilder::EmitMetadataErrorReportFunctionTy &&ErrorReportFn =
2933 [this](llvm::OpenMPIRBuilder::EmitMetadataErrorKind Kind,
2934 const llvm::TargetRegionEntryInfo &EntryInfo) -> void {
2935 SourceLocation Loc;
2936 if (Kind != llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR) {
2937 for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(),
2938 E = CGM.getContext().getSourceManager().fileinfo_end();
2939 I != E; ++I) {
2940 if (I->getFirst().getUniqueID().getDevice() == EntryInfo.DeviceID &&
2941 I->getFirst().getUniqueID().getFile() == EntryInfo.FileID) {
2942 Loc = CGM.getContext().getSourceManager().translateFileLineCol(
2943 I->getFirst(), EntryInfo.Line, 1);
2944 break;
2945 }
2946 }
2947 }
2948 switch (Kind) {
2949 case llvm::OpenMPIRBuilder::EMIT_MD_TARGET_REGION_ERROR: {
2950 CGM.getDiags().Report(Loc,
2951 diag::err_target_region_offloading_entry_incorrect)
2952 << EntryInfo.ParentName;
2953 } break;
2954 case llvm::OpenMPIRBuilder::EMIT_MD_DECLARE_TARGET_ERROR: {
2955 CGM.getDiags().Report(
2956 Loc, diag::err_target_var_offloading_entry_incorrect_with_parent)
2957 << EntryInfo.ParentName;
2958 } break;
2959 case llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_LINK_ERROR: {
2960 CGM.getDiags().Report(diag::err_target_var_offloading_entry_incorrect);
2961 } break;
2962 case llvm::OpenMPIRBuilder::EMIT_MD_GLOBAL_VAR_INDIRECT_ERROR: {
2963 unsigned DiagID = CGM.getDiags().getCustomDiagID(
2964 DiagnosticsEngine::Error, "Offloading entry for indirect declare "
2965 "target variable is incorrect: the "
2966 "address is invalid.");
2967 CGM.getDiags().Report(DiagID);
2968 } break;
2969 }
2970 };
2971
2972 OMPBuilder.createOffloadEntriesAndInfoMetadata(ErrorReportFn);
2973 }
2974
2975 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2976 if (!KmpRoutineEntryPtrTy) {
2977 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2978 ASTContext &C = CGM.getContext();
2979 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2980 FunctionProtoType::ExtProtoInfo EPI;
2981 KmpRoutineEntryPtrQTy = C.getPointerType(
2982 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2983 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2984 }
2985 }
2986
2987 namespace {
2988 struct PrivateHelpersTy {
2989 PrivateHelpersTy(const Expr *OriginalRef, const VarDecl *Original,
2990 const VarDecl *PrivateCopy, const VarDecl *PrivateElemInit)
2991 : OriginalRef(OriginalRef), Original(Original), PrivateCopy(PrivateCopy),
2992 PrivateElemInit(PrivateElemInit) {}
2993 PrivateHelpersTy(const VarDecl *Original) : Original(Original) {}
2994 const Expr *OriginalRef = nullptr;
2995 const VarDecl *Original = nullptr;
2996 const VarDecl *PrivateCopy = nullptr;
2997 const VarDecl *PrivateElemInit = nullptr;
2998 bool isLocalPrivate() const {
2999 return !OriginalRef && !PrivateCopy && !PrivateElemInit;
3000 }
3001 };
3002 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3003 } // anonymous namespace
3004
3005 static bool isAllocatableDecl(const VarDecl *VD) {
3006 const VarDecl *CVD = VD->getCanonicalDecl();
3007 if (!CVD->hasAttr<OMPAllocateDeclAttr>())
3008 return false;
3009 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
3010 // Use the default allocation.
3011 return !(AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc &&
3012 !AA->getAllocator());
3013 }
3014
3015 static RecordDecl *
3016 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3017 if (!Privates.empty()) {
3018 ASTContext &C = CGM.getContext();
3019 // Build struct .kmp_privates_t. {
3020 // /* private vars */
3021 // };
3022 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
3023 RD->startDefinition();
3024 for (const auto &Pair : Privates) {
3025 const VarDecl *VD = Pair.second.Original;
3026 QualType Type = VD->getType().getNonReferenceType();
3027 // If the private variable is a local variable with lvalue ref type,
3028 // allocate the pointer instead of the pointee type.
3029 if (Pair.second.isLocalPrivate()) {
3030 if (VD->getType()->isLValueReferenceType())
3031 Type = C.getPointerType(Type);
3032 if (isAllocatableDecl(VD))
3033 Type = C.getPointerType(Type);
3034 }
3035 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
3036 if (VD->hasAttrs()) {
3037 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3038 E(VD->getAttrs().end());
3039 I != E; ++I)
3040 FD->addAttr(*I);
3041 }
3042 }
3043 RD->completeDefinition();
3044 return RD;
3045 }
3046 return nullptr;
3047 }
3048
3049 static RecordDecl *
3050 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3051 QualType KmpInt32Ty,
3052 QualType KmpRoutineEntryPointerQTy) {
3053 ASTContext &C = CGM.getContext();
3054 // Build struct kmp_task_t {
3055 // void * shareds;
3056 // kmp_routine_entry_t routine;
3057 // kmp_int32 part_id;
3058 // kmp_cmplrdata_t data1;
3059 // kmp_cmplrdata_t data2;
3060 // For taskloops additional fields:
3061 // kmp_uint64 lb;
3062 // kmp_uint64 ub;
3063 // kmp_int64 st;
3064 // kmp_int32 liter;
3065 // void * reductions;
3066 // };
3067 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TagTypeKind::Union);
3068 UD->startDefinition();
3069 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3070 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3071 UD->completeDefinition();
3072 CanQualType KmpCmplrdataTy = C.getCanonicalTagType(UD);
3073 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
3074 RD->startDefinition();
3075 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3076 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3077 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3078 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3079 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3080 if (isOpenMPTaskLoopDirective(Kind)) {
3081 QualType KmpUInt64Ty =
3082 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3083 QualType KmpInt64Ty =
3084 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3085 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3086 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3087 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3088 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3089 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3090 }
3091 RD->completeDefinition();
3092 return RD;
3093 }
3094
3095 static RecordDecl *
3096 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3097 ArrayRef<PrivateDataTy> Privates) {
3098 ASTContext &C = CGM.getContext();
3099 // Build struct kmp_task_t_with_privates {
3100 // kmp_task_t task_data;
3101 // .kmp_privates_t. privates;
3102 // };
3103 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3104 RD->startDefinition();
3105 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3106 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
3107 addFieldToRecordDecl(C, RD, C.getCanonicalTagType(PrivateRD));
3108 RD->completeDefinition();
3109 return RD;
3110 }
3111
3112 /// Emit a proxy function which accepts kmp_task_t as the second
3113 /// argument.
3114 /// \code
3115 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3116 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3117 /// For taskloops:
3118 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3119 /// tt->reductions, tt->shareds);
3120 /// return 0;
3121 /// }
3122 /// \endcode
3123 static llvm::Function *
3124 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3125 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3126 QualType KmpTaskTWithPrivatesPtrQTy,
3127 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3128 QualType SharedsPtrTy, llvm::Function *TaskFunction,
3129 llvm::Value *TaskPrivatesMap) {
3130 ASTContext &C = CGM.getContext();
3131 FunctionArgList Args;
3132 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3133 ImplicitParamKind::Other);
3134 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3135 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3136 ImplicitParamKind::Other);
3137 Args.push_back(&GtidArg);
3138 Args.push_back(&TaskTypeArg);
3139 const auto &TaskEntryFnInfo =
3140 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3141 llvm::FunctionType *TaskEntryTy =
3142 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3143 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
3144 auto *TaskEntry = llvm::Function::Create(
3145 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
3146 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
3147 TaskEntry->setDoesNotRecurse();
3148 CodeGenFunction CGF(CGM);
3149 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
3150 Loc, Loc);
3151
3152 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3153 // tt,
3154 // For taskloops:
3155 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3156 // tt->task_data.shareds);
3157 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
3158 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3159 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3160 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3161 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3162 const auto *KmpTaskTWithPrivatesQTyRD =
3163 KmpTaskTWithPrivatesQTy->castAsRecordDecl();
3164 LValue Base =
3165 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3166 const auto *KmpTaskTQTyRD = KmpTaskTQTy->castAsRecordDecl();
3167 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3168 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3169 llvm::Value *PartidParam = PartIdLVal.getPointer(CGF);
3170
3171 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3172 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3173 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3174 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
3175 CGF.ConvertTypeForMem(SharedsPtrTy));
3176
3177 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3178 llvm::Value *PrivatesParam;
3179 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3180 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3181 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3182 PrivatesLVal.getPointer(CGF), CGF.VoidPtrTy);
3183 } else {
3184 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3185 }
3186
3187 llvm::Value *CommonArgs[] = {
3188 GtidParam, PartidParam, PrivatesParam, TaskPrivatesMap,
3189 CGF.Builder
3190 .CreatePointerBitCastOrAddrSpaceCast(TDBase.getAddress(),
3191 CGF.VoidPtrTy, CGF.Int8Ty)
3192 .emitRawPointer(CGF)};
3193 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3194 std::end(CommonArgs));
3195 if (isOpenMPTaskLoopDirective(Kind)) {
3196 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3197 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3198 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
3199 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3200 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3201 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
3202 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3203 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
3204 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
3205 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3206 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3207 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
3208 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3209 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
3210 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
3211 CallArgs.push_back(LBParam);
3212 CallArgs.push_back(UBParam);
3213 CallArgs.push_back(StParam);
3214 CallArgs.push_back(LIParam);
3215 CallArgs.push_back(RParam);
3216 }
3217 CallArgs.push_back(SharedsParam);
3218
3219 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3220 CallArgs);
3221 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3222 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3223 CGF.FinishFunction();
3224 return TaskEntry;
3225 }
3226
3227 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3228 SourceLocation Loc,
3229 QualType KmpInt32Ty,
3230 QualType KmpTaskTWithPrivatesPtrQTy,
3231 QualType KmpTaskTWithPrivatesQTy) {
3232 ASTContext &C = CGM.getContext();
3233 FunctionArgList Args;
3234 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3235 ImplicitParamKind::Other);
3236 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3237 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3238 ImplicitParamKind::Other);
3239 Args.push_back(&GtidArg);
3240 Args.push_back(&TaskTypeArg);
3241 const auto &DestructorFnInfo =
3242 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3243 llvm::FunctionType *DestructorFnTy =
3244 CGM.getTypes().GetFunctionType(DestructorFnInfo);
3245 std::string Name =
3246 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
3247 auto *DestructorFn =
3248 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3249 Name, &CGM.getModule());
3250 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
3251 DestructorFnInfo);
3252 DestructorFn->setDoesNotRecurse();
3253 CodeGenFunction CGF(CGM);
3254 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3255 Args, Loc, Loc);
3256
3257 LValue Base = CGF.EmitLoadOfPointerLValue(
3258 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3259 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3260 const auto *KmpTaskTWithPrivatesQTyRD =
3261 KmpTaskTWithPrivatesQTy->castAsRecordDecl();
3262 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3263 Base = CGF.EmitLValueForField(Base, *FI);
3264 for (const auto *Field : FI->getType()->castAsRecordDecl()->fields()) {
3265 if (QualType::DestructionKind DtorKind =
3266 Field->getType().isDestructedType()) {
3267 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
3268 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3269 }
3270 }
3271 CGF.FinishFunction();
3272 return DestructorFn;
3273 }
3274
3275 /// Emit a privates mapping function for correct handling of private and
3276 /// firstprivate variables.
3277 /// \code
3278 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3279 /// **noalias priv1,..., <tyn> **noalias privn) {
3280 /// *priv1 = &.privates.priv1;
3281 /// ...;
3282 /// *privn = &.privates.privn;
3283 /// }
3284 /// \endcode
3285 static llvm::Value *
3286 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3287 const OMPTaskDataTy &Data, QualType PrivatesQTy,
3288 ArrayRef<PrivateDataTy> Privates) {
3289 ASTContext &C = CGM.getContext();
3290 FunctionArgList Args;
3291 ImplicitParamDecl TaskPrivatesArg(
3292 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3293 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3294 ImplicitParamKind::Other);
3295 Args.push_back(&TaskPrivatesArg);
3296 llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, unsigned> PrivateVarsPos;
3297 unsigned Counter = 1;
3298 for (const Expr *E : Data.PrivateVars) {
3299 Args.push_back(ImplicitParamDecl::Create(
3300 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3301 C.getPointerType(C.getPointerType(E->getType()))
3302 .withConst()
3303 .withRestrict(),
3304 ImplicitParamKind::Other));
3305 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3306 PrivateVarsPos[VD] = Counter;
3307 ++Counter;
3308 }
3309 for (const Expr *E : Data.FirstprivateVars) {
3310 Args.push_back(ImplicitParamDecl::Create(
3311 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3312 C.getPointerType(C.getPointerType(E->getType()))
3313 .withConst()
3314 .withRestrict(),
3315 ImplicitParamKind::Other));
3316 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3317 PrivateVarsPos[VD] = Counter;
3318 ++Counter;
3319 }
3320 for (const Expr *E : Data.LastprivateVars) {
3321 Args.push_back(ImplicitParamDecl::Create(
3322 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3323 C.getPointerType(C.getPointerType(E->getType()))
3324 .withConst()
3325 .withRestrict(),
3326 ImplicitParamKind::Other));
3327 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3328 PrivateVarsPos[VD] = Counter;
3329 ++Counter;
3330 }
3331 for (const VarDecl *VD : Data.PrivateLocals) {
3332 QualType Ty = VD->getType().getNonReferenceType();
3333 if (VD->getType()->isLValueReferenceType())
3334 Ty = C.getPointerType(Ty);
3335 if (isAllocatableDecl(VD))
3336 Ty = C.getPointerType(Ty);
3337 Args.push_back(ImplicitParamDecl::Create(
3338 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3339 C.getPointerType(C.getPointerType(Ty)).withConst().withRestrict(),
3340 ImplicitParamKind::Other));
3341 PrivateVarsPos[VD] = Counter;
3342 ++Counter;
3343 }
3344 const auto &TaskPrivatesMapFnInfo =
3345 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3346 llvm::FunctionType *TaskPrivatesMapTy =
3347 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3348 std::string Name =
3349 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
3350 auto *TaskPrivatesMap = llvm::Function::Create(
3351 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
3352 &CGM.getModule());
3353 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
3354 TaskPrivatesMapFnInfo);
3355 if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
3356 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3357 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
3358 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3359 }
3360 CodeGenFunction CGF(CGM);
3361 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3362 TaskPrivatesMapFnInfo, Args, Loc, Loc);
3363
3364 // *privi = &.privates.privi;
3365 LValue Base = CGF.EmitLoadOfPointerLValue(
3366 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3367 TaskPrivatesArg.getType()->castAs<PointerType>());
3368 const auto *PrivatesQTyRD = PrivatesQTy->castAsRecordDecl();
3369 Counter = 0;
3370 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
3371 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
3372 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3373 LValue RefLVal =
3374 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3375 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3376 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
3377 CGF.EmitStoreOfScalar(FieldLVal.getPointer(CGF), RefLoadLVal);
3378 ++Counter;
3379 }
3380 CGF.FinishFunction();
3381 return TaskPrivatesMap;
3382 }
3383
3384 /// Emit initialization for private variables in task-based directives.
3385 static void emitPrivatesInit(CodeGenFunction &CGF,
3386 const OMPExecutableDirective &D,
3387 Address KmpTaskSharedsPtr, LValue TDBase,
3388 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3389 QualType SharedsTy, QualType SharedsPtrTy,
3390 const OMPTaskDataTy &Data,
3391 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3392 ASTContext &C = CGF.getContext();
3393 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3394 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3395 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
3396 ? OMPD_taskloop
3397 : OMPD_task;
3398 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
3399 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
3400 LValue SrcBase;
3401 bool IsTargetTask =
3402 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
3403 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
3404 // For target-based directives skip 4 firstprivate arrays BasePointersArray,
3405 // PointersArray, SizesArray, and MappersArray. The original variables for
3406 // these arrays are not captured and we get their addresses explicitly.
3407 if ((!IsTargetTask && !Data.FirstprivateVars.empty() && ForDup) ||
3408 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
3409 SrcBase = CGF.MakeAddrLValue(
3410 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3411 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy),
3412 CGF.ConvertTypeForMem(SharedsTy)),
3413 SharedsTy);
3414 }
3415 FI = FI->getType()->castAsRecordDecl()->field_begin();
3416 for (const PrivateDataTy &Pair : Privates) {
3417 // Do not initialize private locals.
3418 if (Pair.second.isLocalPrivate()) {
3419 ++FI;
3420 continue;
3421 }
3422 const VarDecl *VD = Pair.second.PrivateCopy;
3423 const Expr *Init = VD->getAnyInitializer();
3424 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3425 !CGF.isTrivialInitializer(Init)))) {
3426 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3427 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
3428 const VarDecl *OriginalVD = Pair.second.Original;
3429 // Check if the variable is the target-based BasePointersArray,
3430 // PointersArray, SizesArray, or MappersArray.
3431 LValue SharedRefLValue;
3432 QualType Type = PrivateLValue.getType();
3433 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
3434 if (IsTargetTask && !SharedField) {
3435 assert(isa<ImplicitParamDecl>(OriginalVD) &&
3436 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
3437 cast<CapturedDecl>(OriginalVD->getDeclContext())
3438 ->getNumParams() == 0 &&
3439 isa<TranslationUnitDecl>(
3440 cast<CapturedDecl>(OriginalVD->getDeclContext())
3441 ->getDeclContext()) &&
3442 "Expected artificial target data variable.");
3443 SharedRefLValue =
3444 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
3445 } else if (ForDup) {
3446 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3447 SharedRefLValue = CGF.MakeAddrLValue(
3448 SharedRefLValue.getAddress().withAlignment(
3449 C.getDeclAlign(OriginalVD)),
3450 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
3451 SharedRefLValue.getTBAAInfo());
3452 } else if (CGF.LambdaCaptureFields.count(
3453 Pair.second.Original->getCanonicalDecl()) > 0 ||
3454 isa_and_nonnull<BlockDecl>(CGF.CurCodeDecl)) {
3455 SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3456 } else {
3457 // Processing for implicitly captured variables.
3458 InlinedOpenMPRegionRAII Region(
3459 CGF, [](CodeGenFunction &, PrePostActionTy &) {}, OMPD_unknown,
3460 /*HasCancel=*/false, /*NoInheritance=*/true);
3461 SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3462 }
3463 if (Type->isArrayType()) {
3464 // Initialize firstprivate array.
3465 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3466 // Perform simple memcpy.
3467 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
3468 } else {
3469 // Initialize firstprivate array using element-by-element
3470 // initialization.
3471 CGF.EmitOMPAggregateAssign(
3472 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3473 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3474 Address SrcElement) {
3475 // Clean up any temporaries needed by the initialization.
3476 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3477 InitScope.addPrivate(Elem, SrcElement);
3478 (void)InitScope.Privatize();
3479 // Emit initialization for single element.
3480 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3481 CGF, &CapturesInfo);
3482 CGF.EmitAnyExprToMem(Init, DestElement,
3483 Init->getType().getQualifiers(),
3484 /*IsInitializer=*/false);
3485 });
3486 }
3487 } else {
3488 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3489 InitScope.addPrivate(Elem, SharedRefLValue.getAddress());
3490 (void)InitScope.Privatize();
3491 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3492 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3493 /*capturedByInit=*/false);
3494 }
3495 } else {
3496 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3497 }
3498 }
3499 ++FI;
3500 }
3501 }
3502
3503 /// Check if duplication function is required for taskloops.
3504 static bool checkInitIsRequired(CodeGenFunction &CGF,
3505 ArrayRef<PrivateDataTy> Privates) {
3506 bool InitRequired = false;
3507 for (const PrivateDataTy &Pair : Privates) {
3508 if (Pair.second.isLocalPrivate())
3509 continue;
3510 const VarDecl *VD = Pair.second.PrivateCopy;
3511 const Expr *Init = VD->getAnyInitializer();
3512 InitRequired = InitRequired || (isa_and_nonnull<CXXConstructExpr>(Init) &&
3513 !CGF.isTrivialInitializer(Init));
3514 if (InitRequired)
3515 break;
3516 }
3517 return InitRequired;
3518 }
3519
3520
3521 /// Emit task_dup function (for initialization of
3522 /// private/firstprivate/lastprivate vars and last_iter flag)
3523 /// \code
3524 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3525 /// lastpriv) {
3526 /// // setup lastprivate flag
3527 /// task_dst->last = lastpriv;
3528 /// // could be constructor calls here...
3529 /// }
3530 /// \endcode
3531 static llvm::Value *
3532 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3533 const OMPExecutableDirective &D,
3534 QualType KmpTaskTWithPrivatesPtrQTy,
3535 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3536 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3537 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3538 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3539 ASTContext &C = CGM.getContext();
3540 FunctionArgList Args;
3541 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3542 KmpTaskTWithPrivatesPtrQTy,
3543 ImplicitParamKind::Other);
3544 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3545 KmpTaskTWithPrivatesPtrQTy,
3546 ImplicitParamKind::Other);
3547 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3548 ImplicitParamKind::Other);
3549 Args.push_back(&DstArg);
3550 Args.push_back(&SrcArg);
3551 Args.push_back(&LastprivArg);
3552 const auto &TaskDupFnInfo =
3553 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3554 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3555 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
3556 auto *TaskDup = llvm::Function::Create(
3557 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
3558 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
3559 TaskDup->setDoesNotRecurse();
3560 CodeGenFunction CGF(CGM);
3561 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
3562 Loc);
3563
3564 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3565 CGF.GetAddrOfLocalVar(&DstArg),
3566 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3567 // task_dst->liter = lastpriv;
3568 if (WithLastIter) {
3569 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3570 LValue Base = CGF.EmitLValueForField(
3571 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3572 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3573 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3574 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3575 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3576 }
3577
3578 // Emit initial values for private copies (if any).
3579 assert(!Privates.empty());
3580 Address KmpTaskSharedsPtr = Address::invalid();
3581 if (!Data.FirstprivateVars.empty()) {
3582 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3583 CGF.GetAddrOfLocalVar(&SrcArg),
3584 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3585 LValue Base = CGF.EmitLValueForField(
3586 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3587 KmpTaskSharedsPtr = Address(
3588 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3589 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3590 KmpTaskTShareds)),
3591 Loc),
3592 CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy));
3593 }
3594 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3595 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
3596 CGF.FinishFunction();
3597 return TaskDup;
3598 }
3599
3600 /// Checks if destructor function is required to be generated.
3601 /// \return true if cleanups are required, false otherwise.
3602 static bool
3603 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3604 ArrayRef<PrivateDataTy> Privates) {
3605 for (const PrivateDataTy &P : Privates) {
3606 if (P.second.isLocalPrivate())
3607 continue;
3608 QualType Ty = P.second.Original->getType().getNonReferenceType();
3609 if (Ty.isDestructedType())
3610 return true;
3611 }
3612 return false;
3613 }
3614
3615 namespace {
3616 /// Loop generator for OpenMP iterator expression.
3617 class OMPIteratorGeneratorScope final
3618 : public CodeGenFunction::OMPPrivateScope {
3619 CodeGenFunction &CGF;
3620 const OMPIteratorExpr *E = nullptr;
3621 SmallVector<CodeGenFunction::JumpDest, 4> ContDests;
3622 SmallVector<CodeGenFunction::JumpDest, 4> ExitDests;
3623 OMPIteratorGeneratorScope() = delete;
3624 OMPIteratorGeneratorScope(OMPIteratorGeneratorScope &) = delete;
3625
3626 public:
3627 OMPIteratorGeneratorScope(CodeGenFunction &CGF, const OMPIteratorExpr *E)
3628 : CodeGenFunction::OMPPrivateScope(CGF), CGF(CGF), E(E) {
3629 if (!E)
3630 return;
3631 SmallVector<llvm::Value *, 4> Uppers;
3632 for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) {
3633 Uppers.push_back(CGF.EmitScalarExpr(E->getHelper(I).Upper));
3634 const auto *VD = cast<VarDecl>(E->getIteratorDecl(I));
3635 addPrivate(VD, CGF.CreateMemTemp(VD->getType(), VD->getName()));
3636 const OMPIteratorHelperData &HelperData = E->getHelper(I);
3637 addPrivate(
3638 HelperData.CounterVD,
3639 CGF.CreateMemTemp(HelperData.CounterVD->getType(), "counter.addr"));
3640 }
3641 Privatize();
3642
3643 for (unsigned I = 0, End = E->numOfIterators(); I < End; ++I) {
3644 const OMPIteratorHelperData &HelperData = E->getHelper(I);
3645 LValue CLVal =
3646 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(HelperData.CounterVD),
3647 HelperData.CounterVD->getType());
3648 // Counter = 0;
3649 CGF.EmitStoreOfScalar(
3650 llvm::ConstantInt::get(CLVal.getAddress().getElementType(), 0),
3651 CLVal);
3652 CodeGenFunction::JumpDest &ContDest =
3653 ContDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.cont"));
3654 CodeGenFunction::JumpDest &ExitDest =
3655 ExitDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.exit"));
3656 // N = <number-of_iterations>;
3657 llvm::Value *N = Uppers[I];
3658 // cont:
3659 // if (Counter < N) goto body; else goto exit;
3660 CGF.EmitBlock(ContDest.getBlock());
3661 auto *CVal =
3662 CGF.EmitLoadOfScalar(CLVal, HelperData.CounterVD->getLocation());
3663 llvm::Value *Cmp =
3664 HelperData.CounterVD->getType()->isSignedIntegerOrEnumerationType()
3665 ? CGF.Builder.CreateICmpSLT(CVal, N)
3666 : CGF.Builder.CreateICmpULT(CVal, N);
3667 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("iter.body");
3668 CGF.Builder.CreateCondBr(Cmp, BodyBB, ExitDest.getBlock());
3669 // body:
3670 CGF.EmitBlock(BodyBB);
3671 // Iteri = Begini + Counter * Stepi;
3672 CGF.EmitIgnoredExpr(HelperData.Update);
3673 }
3674 }
3675 ~OMPIteratorGeneratorScope() {
3676 if (!E)
3677 return;
3678 for (unsigned I = E->numOfIterators(); I > 0; --I) {
3679 // Counter = Counter + 1;
3680 const OMPIteratorHelperData &HelperData = E->getHelper(I - 1);
3681 CGF.EmitIgnoredExpr(HelperData.CounterUpdate);
3682 // goto cont;
3683 CGF.EmitBranchThroughCleanup(ContDests[I - 1]);
3684 // exit:
3685 CGF.EmitBlock(ExitDests[I - 1].getBlock(), /*IsFinished=*/I == 1);
3686 }
3687 }
3688 };
3689 } // namespace
3690
3691 static std::pair<llvm::Value *, llvm::Value *>
3692 getPointerAndSize(CodeGenFunction &CGF, const Expr *E) {
3693 const auto *OASE = dyn_cast<OMPArrayShapingExpr>(E);
3694 llvm::Value *Addr;
3695 if (OASE) {
3696 const Expr *Base = OASE->getBase();
3697 Addr = CGF.EmitScalarExpr(Base);
3698 } else {
3699 Addr = CGF.EmitLValue(E).getPointer(CGF);
3700 }
3701 llvm::Value *SizeVal;
3702 QualType Ty = E->getType();
3703 if (OASE) {
3704 SizeVal = CGF.getTypeSize(OASE->getBase()->getType()->getPointeeType());
3705 for (const Expr *SE : OASE->getDimensions()) {
3706 llvm::Value *Sz = CGF.EmitScalarExpr(SE);
3707 Sz = CGF.EmitScalarConversion(
3708 Sz, SE->getType(), CGF.getContext().getSizeType(), SE->getExprLoc());
3709 SizeVal = CGF.Builder.CreateNUWMul(SizeVal, Sz);
3710 }
3711 } else if (const auto *ASE =
3712 dyn_cast<ArraySectionExpr>(E->IgnoreParenImpCasts())) {
3713 LValue UpAddrLVal = CGF.EmitArraySectionExpr(ASE, /*IsLowerBound=*/false);
3714 Address UpAddrAddress = UpAddrLVal.getAddress();
3715 llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32(
3716 UpAddrAddress.getElementType(), UpAddrAddress.emitRawPointer(CGF),
3717 /*Idx0=*/1);
3718 llvm::Value *LowIntPtr = CGF.Builder.CreatePtrToInt(Addr, CGF.SizeTy);
3719 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGF.SizeTy);
3720 SizeVal = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3721 } else {
3722 SizeVal = CGF.getTypeSize(Ty);
3723 }
3724 return std::make_pair(Addr, SizeVal);
3725 }
3726
3727 /// Builds kmp_depend_info, if it is not built yet, and builds flags type.
3728 static void getKmpAffinityType(ASTContext &C, QualType &KmpTaskAffinityInfoTy) {
3729 QualType FlagsTy = C.getIntTypeForBitwidth(32, /*Signed=*/false);
3730 if (KmpTaskAffinityInfoTy.isNull()) {
3731 RecordDecl *KmpAffinityInfoRD =
3732 C.buildImplicitRecord("kmp_task_affinity_info_t");
3733 KmpAffinityInfoRD->startDefinition();
3734 addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getIntPtrType());
3735 addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getSizeType());
3736 addFieldToRecordDecl(C, KmpAffinityInfoRD, FlagsTy);
3737 KmpAffinityInfoRD->completeDefinition();
3738 KmpTaskAffinityInfoTy = C.getCanonicalTagType(KmpAffinityInfoRD);
3739 }
3740 }
3741
3742 CGOpenMPRuntime::TaskResultTy
3743 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3744 const OMPExecutableDirective &D,
3745 llvm::Function *TaskFunction, QualType SharedsTy,
3746 Address Shareds, const OMPTaskDataTy &Data) {
3747 ASTContext &C = CGM.getContext();
3748 llvm::SmallVector<PrivateDataTy, 4> Privates;
3749 // Aggregate privates and sort them by the alignment.
3750 const auto *I = Data.PrivateCopies.begin();
3751 for (const Expr *E : Data.PrivateVars) {
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 I = Data.FirstprivateCopies.begin();
3760 const auto *IElemInitRef = Data.FirstprivateInits.begin();
3761 for (const Expr *E : Data.FirstprivateVars) {
3762 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3763 Privates.emplace_back(
3764 C.getDeclAlign(VD),
3765 PrivateHelpersTy(
3766 E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3767 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
3768 ++I;
3769 ++IElemInitRef;
3770 }
3771 I = Data.LastprivateCopies.begin();
3772 for (const Expr *E : Data.LastprivateVars) {
3773 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3774 Privates.emplace_back(
3775 C.getDeclAlign(VD),
3776 PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3777 /*PrivateElemInit=*/nullptr));
3778 ++I;
3779 }
3780 for (const VarDecl *VD : Data.PrivateLocals) {
3781 if (isAllocatableDecl(VD))
3782 Privates.emplace_back(CGM.getPointerAlign(), PrivateHelpersTy(VD));
3783 else
3784 Privates.emplace_back(C.getDeclAlign(VD), PrivateHelpersTy(VD));
3785 }
3786 llvm::stable_sort(Privates,
3787 [](const PrivateDataTy &L, const PrivateDataTy &R) {
3788 return L.first > R.first;
3789 });
3790 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3791 // Build type kmp_routine_entry_t (if not built yet).
3792 emitKmpRoutineEntryT(KmpInt32Ty);
3793 // Build type kmp_task_t (if not built yet).
3794 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
3795 if (SavedKmpTaskloopTQTy.isNull()) {
3796 SavedKmpTaskloopTQTy = C.getCanonicalTagType(createKmpTaskTRecordDecl(
3797 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3798 }
3799 KmpTaskTQTy = SavedKmpTaskloopTQTy;
3800 } else {
3801 assert((D.getDirectiveKind() == OMPD_task ||
3802 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
3803 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
3804 "Expected taskloop, task or target directive");
3805 if (SavedKmpTaskTQTy.isNull()) {
3806 SavedKmpTaskTQTy = C.getCanonicalTagType(createKmpTaskTRecordDecl(
3807 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
3808 }
3809 KmpTaskTQTy = SavedKmpTaskTQTy;
3810 }
3811 const auto *KmpTaskTQTyRD = KmpTaskTQTy->castAsRecordDecl();
3812 // Build particular struct kmp_task_t for the given task.
3813 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
3814 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3815 CanQualType KmpTaskTWithPrivatesQTy =
3816 C.getCanonicalTagType(KmpTaskTWithPrivatesQTyRD);
3817 QualType KmpTaskTWithPrivatesPtrQTy =
3818 C.getPointerType(KmpTaskTWithPrivatesQTy);
3819 llvm::Type *KmpTaskTWithPrivatesPtrTy = CGF.Builder.getPtrTy(0);
3820 llvm::Value *KmpTaskTWithPrivatesTySize =
3821 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3822 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3823
3824 // Emit initial values for private copies (if any).
3825 llvm::Value *TaskPrivatesMap = nullptr;
3826 llvm::Type *TaskPrivatesMapTy =
3827 std::next(TaskFunction->arg_begin(), 3)->getType();
3828 if (!Privates.empty()) {
3829 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3830 TaskPrivatesMap =
3831 emitTaskPrivateMappingFunction(CGM, Loc, Data, FI->getType(), Privates);
3832 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3833 TaskPrivatesMap, TaskPrivatesMapTy);
3834 } else {
3835 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3836 cast<llvm::PointerType>(TaskPrivatesMapTy));
3837 }
3838 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3839 // kmp_task_t *tt);
3840 llvm::Function *TaskEntry = emitProxyTaskFunction(
3841 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3842 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3843 TaskPrivatesMap);
3844
3845 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3846 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3847 // kmp_routine_entry_t *task_entry);
3848 // Task flags. Format is taken from
3849 // https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h,
3850 // description of kmp_tasking_flags struct.
3851 enum {
3852 TiedFlag = 0x1,
3853 FinalFlag = 0x2,
3854 DestructorsFlag = 0x8,
3855 PriorityFlag = 0x20,
3856 DetachableFlag = 0x40,
3857 FreeAgentFlag = 0x80,
3858 };
3859 unsigned Flags = Data.Tied ? TiedFlag : 0;
3860 bool NeedsCleanup = false;
3861 if (!Privates.empty()) {
3862 NeedsCleanup =
3863 checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD, Privates);
3864 if (NeedsCleanup)
3865 Flags = Flags | DestructorsFlag;
3866 }
3867 if (const auto *Clause = D.getSingleClause<OMPThreadsetClause>()) {
3868 OpenMPThreadsetKind Kind = Clause->getThreadsetKind();
3869 if (Kind == OMPC_THREADSET_omp_pool)
3870 Flags = Flags | FreeAgentFlag;
3871 }
3872 if (Data.Priority.getInt())
3873 Flags = Flags | PriorityFlag;
3874 if (D.hasClausesOfKind<OMPDetachClause>())
3875 Flags = Flags | DetachableFlag;
3876 llvm::Value *TaskFlags =
3877 Data.Final.getPointer()
3878 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
3879 CGF.Builder.getInt32(FinalFlag),
3880 CGF.Builder.getInt32(/*C=*/0))
3881 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
3882 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3883 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3884 SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc),
3885 getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize,
3886 SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3887 TaskEntry, KmpRoutineEntryPtrTy)};
3888 llvm::Value *NewTask;
3889 if (D.hasClausesOfKind<OMPNowaitClause>()) {
3890 // Check if we have any device clause associated with the directive.
3891 const Expr *Device = nullptr;
3892 if (auto *C = D.getSingleClause<OMPDeviceClause>())
3893 Device = C->getDevice();
3894 // Emit device ID if any otherwise use default value.
3895 llvm::Value *DeviceID;
3896 if (Device)
3897 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
3898 CGF.Int64Ty, /*isSigned=*/true);
3899 else
3900 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
3901 AllocArgs.push_back(DeviceID);
3902 NewTask = CGF.EmitRuntimeCall(
3903 OMPBuilder.getOrCreateRuntimeFunction(
3904 CGM.getModule(), OMPRTL___kmpc_omp_target_task_alloc),
3905 AllocArgs);
3906 } else {
3907 NewTask =
3908 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
3909 CGM.getModule(), OMPRTL___kmpc_omp_task_alloc),
3910 AllocArgs);
3911 }
3912 // Emit detach clause initialization.
3913 // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid,
3914 // task_descriptor);
3915 if (const auto *DC = D.getSingleClause<OMPDetachClause>()) {
3916 const Expr *Evt = DC->getEventHandler()->IgnoreParenImpCasts();
3917 LValue EvtLVal = CGF.EmitLValue(Evt);
3918
3919 // Build kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref,
3920 // int gtid, kmp_task_t *task);
3921 llvm::Value *Loc = emitUpdateLocation(CGF, DC->getBeginLoc());
3922 llvm::Value *Tid = getThreadID(CGF, DC->getBeginLoc());
3923 Tid = CGF.Builder.CreateIntCast(Tid, CGF.IntTy, /*isSigned=*/false);
3924 llvm::Value *EvtVal = CGF.EmitRuntimeCall(
3925 OMPBuilder.getOrCreateRuntimeFunction(
3926 CGM.getModule(), OMPRTL___kmpc_task_allow_completion_event),
3927 {Loc, Tid, NewTask});
3928 EvtVal = CGF.EmitScalarConversion(EvtVal, C.VoidPtrTy, Evt->getType(),
3929 Evt->getExprLoc());
3930 CGF.EmitStoreOfScalar(EvtVal, EvtLVal);
3931 }
3932 // Process affinity clauses.
3933 if (D.hasClausesOfKind<OMPAffinityClause>()) {
3934 // Process list of affinity data.
3935 ASTContext &C = CGM.getContext();
3936 Address AffinitiesArray = Address::invalid();
3937 // Calculate number of elements to form the array of affinity data.
3938 llvm::Value *NumOfElements = nullptr;
3939 unsigned NumAffinities = 0;
3940 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
3941 if (const Expr *Modifier = C->getModifier()) {
3942 const auto *IE = cast<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts());
3943 for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) {
3944 llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
3945 Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false);
3946 NumOfElements =
3947 NumOfElements ? CGF.Builder.CreateNUWMul(NumOfElements, Sz) : Sz;
3948 }
3949 } else {
3950 NumAffinities += C->varlist_size();
3951 }
3952 }
3953 getKmpAffinityType(CGM.getContext(), KmpTaskAffinityInfoTy);
3954 // Fields ids in kmp_task_affinity_info record.
3955 enum RTLAffinityInfoFieldsTy { BaseAddr, Len, Flags };
3956
3957 QualType KmpTaskAffinityInfoArrayTy;
3958 if (NumOfElements) {
3959 NumOfElements = CGF.Builder.CreateNUWAdd(
3960 llvm::ConstantInt::get(CGF.SizeTy, NumAffinities), NumOfElements);
3961 auto *OVE = new (C) OpaqueValueExpr(
3962 Loc,
3963 C.getIntTypeForBitwidth(C.getTypeSize(C.getSizeType()), /*Signed=*/0),
3964 VK_PRValue);
3965 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
3966 RValue::get(NumOfElements));
3967 KmpTaskAffinityInfoArrayTy = C.getVariableArrayType(
3968 KmpTaskAffinityInfoTy, OVE, ArraySizeModifier::Normal,
3969 /*IndexTypeQuals=*/0);
3970 // Properly emit variable-sized array.
3971 auto *PD = ImplicitParamDecl::Create(C, KmpTaskAffinityInfoArrayTy,
3972 ImplicitParamKind::Other);
3973 CGF.EmitVarDecl(*PD);
3974 AffinitiesArray = CGF.GetAddrOfLocalVar(PD);
3975 NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
3976 /*isSigned=*/false);
3977 } else {
3978 KmpTaskAffinityInfoArrayTy = C.getConstantArrayType(
3979 KmpTaskAffinityInfoTy,
3980 llvm::APInt(C.getTypeSize(C.getSizeType()), NumAffinities), nullptr,
3981 ArraySizeModifier::Normal, /*IndexTypeQuals=*/0);
3982 AffinitiesArray =
3983 CGF.CreateMemTemp(KmpTaskAffinityInfoArrayTy, ".affs.arr.addr");
3984 AffinitiesArray = CGF.Builder.CreateConstArrayGEP(AffinitiesArray, 0);
3985 NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumAffinities,
3986 /*isSigned=*/false);
3987 }
3988
3989 const auto *KmpAffinityInfoRD = KmpTaskAffinityInfoTy->getAsRecordDecl();
3990 // Fill array by elements without iterators.
3991 unsigned Pos = 0;
3992 bool HasIterator = false;
3993 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
3994 if (C->getModifier()) {
3995 HasIterator = true;
3996 continue;
3997 }
3998 for (const Expr *E : C->varlist()) {
3999 llvm::Value *Addr;
4000 llvm::Value *Size;
4001 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4002 LValue Base =
4003 CGF.MakeAddrLValue(CGF.Builder.CreateConstGEP(AffinitiesArray, Pos),
4004 KmpTaskAffinityInfoTy);
4005 // affs[i].base_addr = &<Affinities[i].second>;
4006 LValue BaseAddrLVal = CGF.EmitLValueForField(
4007 Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4008 CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4009 BaseAddrLVal);
4010 // affs[i].len = sizeof(<Affinities[i].second>);
4011 LValue LenLVal = CGF.EmitLValueForField(
4012 Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4013 CGF.EmitStoreOfScalar(Size, LenLVal);
4014 ++Pos;
4015 }
4016 }
4017 LValue PosLVal;
4018 if (HasIterator) {
4019 PosLVal = CGF.MakeAddrLValue(
4020 CGF.CreateMemTemp(C.getSizeType(), "affs.counter.addr"),
4021 C.getSizeType());
4022 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4023 }
4024 // Process elements with iterators.
4025 for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4026 const Expr *Modifier = C->getModifier();
4027 if (!Modifier)
4028 continue;
4029 OMPIteratorGeneratorScope IteratorScope(
4030 CGF, cast_or_null<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts()));
4031 for (const Expr *E : C->varlist()) {
4032 llvm::Value *Addr;
4033 llvm::Value *Size;
4034 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4035 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4036 LValue Base =
4037 CGF.MakeAddrLValue(CGF.Builder.CreateGEP(CGF, AffinitiesArray, Idx),
4038 KmpTaskAffinityInfoTy);
4039 // affs[i].base_addr = &<Affinities[i].second>;
4040 LValue BaseAddrLVal = CGF.EmitLValueForField(
4041 Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4042 CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4043 BaseAddrLVal);
4044 // affs[i].len = sizeof(<Affinities[i].second>);
4045 LValue LenLVal = CGF.EmitLValueForField(
4046 Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4047 CGF.EmitStoreOfScalar(Size, LenLVal);
4048 Idx = CGF.Builder.CreateNUWAdd(
4049 Idx, llvm::ConstantInt::get(Idx->getType(), 1));
4050 CGF.EmitStoreOfScalar(Idx, PosLVal);
4051 }
4052 }
4053 // Call to kmp_int32 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref,
4054 // kmp_int32 gtid, kmp_task_t *new_task, kmp_int32
4055 // naffins, kmp_task_affinity_info_t *affin_list);
4056 llvm::Value *LocRef = emitUpdateLocation(CGF, Loc);
4057 llvm::Value *GTid = getThreadID(CGF, Loc);
4058 llvm::Value *AffinListPtr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4059 AffinitiesArray.emitRawPointer(CGF), CGM.VoidPtrTy);
4060 // FIXME: Emit the function and ignore its result for now unless the
4061 // runtime function is properly implemented.
4062 (void)CGF.EmitRuntimeCall(
4063 OMPBuilder.getOrCreateRuntimeFunction(
4064 CGM.getModule(), OMPRTL___kmpc_omp_reg_task_with_affinity),
4065 {LocRef, GTid, NewTask, NumOfElements, AffinListPtr});
4066 }
4067 llvm::Value *NewTaskNewTaskTTy =
4068 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4069 NewTask, KmpTaskTWithPrivatesPtrTy);
4070 LValue Base = CGF.MakeNaturalAlignRawAddrLValue(NewTaskNewTaskTTy,
4071 KmpTaskTWithPrivatesQTy);
4072 LValue TDBase =
4073 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4074 // Fill the data in the resulting kmp_task_t record.
4075 // Copy shareds if there are any.
4076 Address KmpTaskSharedsPtr = Address::invalid();
4077 if (!SharedsTy->castAsRecordDecl()->field_empty()) {
4078 KmpTaskSharedsPtr = Address(
4079 CGF.EmitLoadOfScalar(
4080 CGF.EmitLValueForField(
4081 TDBase,
4082 *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
4083 Loc),
4084 CGF.Int8Ty, CGM.getNaturalTypeAlignment(SharedsTy));
4085 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4086 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4087 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
4088 }
4089 // Emit initial values for private copies (if any).
4090 TaskResultTy Result;
4091 if (!Privates.empty()) {
4092 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4093 SharedsTy, SharedsPtrTy, Data, Privates,
4094 /*ForDup=*/false);
4095 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4096 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4097 Result.TaskDupFn = emitTaskDupFunction(
4098 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4099 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4100 /*WithLastIter=*/!Data.LastprivateVars.empty());
4101 }
4102 }
4103 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4104 enum { Priority = 0, Destructors = 1 };
4105 // Provide pointer to function with destructors for privates.
4106 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4107 const auto *KmpCmplrdataUD = (*FI)->getType()->castAsRecordDecl();
4108 assert(KmpCmplrdataUD->isUnion());
4109 if (NeedsCleanup) {
4110 llvm::Value *DestructorFn = emitDestructorsFunction(
4111 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4112 KmpTaskTWithPrivatesQTy);
4113 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4114 LValue DestructorsLV = CGF.EmitLValueForField(
4115 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4116 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4117 DestructorFn, KmpRoutineEntryPtrTy),
4118 DestructorsLV);
4119 }
4120 // Set priority.
4121 if (Data.Priority.getInt()) {
4122 LValue Data2LV = CGF.EmitLValueForField(
4123 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4124 LValue PriorityLV = CGF.EmitLValueForField(
4125 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4126 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4127 }
4128 Result.NewTask = NewTask;
4129 Result.TaskEntry = TaskEntry;
4130 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4131 Result.TDBase = TDBase;
4132 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4133 return Result;
4134 }
4135
4136 /// Translates internal dependency kind into the runtime kind.
4137 static RTLDependenceKindTy translateDependencyKind(OpenMPDependClauseKind K) {
4138 RTLDependenceKindTy DepKind;
4139 switch (K) {
4140 case OMPC_DEPEND_in:
4141 DepKind = RTLDependenceKindTy::DepIn;
4142 break;
4143 // Out and InOut dependencies must use the same code.
4144 case OMPC_DEPEND_out:
4145 case OMPC_DEPEND_inout:
4146 DepKind = RTLDependenceKindTy::DepInOut;
4147 break;
4148 case OMPC_DEPEND_mutexinoutset:
4149 DepKind = RTLDependenceKindTy::DepMutexInOutSet;
4150 break;
4151 case OMPC_DEPEND_inoutset:
4152 DepKind = RTLDependenceKindTy::DepInOutSet;
4153 break;
4154 case OMPC_DEPEND_outallmemory:
4155 DepKind = RTLDependenceKindTy::DepOmpAllMem;
4156 break;
4157 case OMPC_DEPEND_source:
4158 case OMPC_DEPEND_sink:
4159 case OMPC_DEPEND_depobj:
4160 case OMPC_DEPEND_inoutallmemory:
4161 case OMPC_DEPEND_unknown:
4162 llvm_unreachable("Unknown task dependence type");
4163 }
4164 return DepKind;
4165 }
4166
4167 /// Builds kmp_depend_info, if it is not built yet, and builds flags type.
4168 static void getDependTypes(ASTContext &C, QualType &KmpDependInfoTy,
4169 QualType &FlagsTy) {
4170 FlagsTy = C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4171 if (KmpDependInfoTy.isNull()) {
4172 RecordDecl *KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4173 KmpDependInfoRD->startDefinition();
4174 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4175 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4176 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4177 KmpDependInfoRD->completeDefinition();
4178 KmpDependInfoTy = C.getCanonicalTagType(KmpDependInfoRD);
4179 }
4180 }
4181
4182 std::pair<llvm::Value *, LValue>
4183 CGOpenMPRuntime::getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal,
4184 SourceLocation Loc) {
4185 ASTContext &C = CGM.getContext();
4186 QualType FlagsTy;
4187 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4188 auto *KmpDependInfoRD = KmpDependInfoTy->castAsRecordDecl();
4189 QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4190 LValue Base = CGF.EmitLoadOfPointerLValue(
4191 DepobjLVal.getAddress().withElementType(
4192 CGF.ConvertTypeForMem(KmpDependInfoPtrTy)),
4193 KmpDependInfoPtrTy->castAs<PointerType>());
4194 Address DepObjAddr = CGF.Builder.CreateGEP(
4195 CGF, Base.getAddress(),
4196 llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4197 LValue NumDepsBase = CGF.MakeAddrLValue(
4198 DepObjAddr, KmpDependInfoTy, Base.getBaseInfo(), Base.getTBAAInfo());
4199 // NumDeps = deps[i].base_addr;
4200 LValue BaseAddrLVal = CGF.EmitLValueForField(
4201 NumDepsBase,
4202 *std::next(KmpDependInfoRD->field_begin(),
4203 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr)));
4204 llvm::Value *NumDeps = CGF.EmitLoadOfScalar(BaseAddrLVal, Loc);
4205 return std::make_pair(NumDeps, Base);
4206 }
4207
4208 static void emitDependData(CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4209 llvm::PointerUnion<unsigned *, LValue *> Pos,
4210 const OMPTaskDataTy::DependData &Data,
4211 Address DependenciesArray) {
4212 CodeGenModule &CGM = CGF.CGM;
4213 ASTContext &C = CGM.getContext();
4214 QualType FlagsTy;
4215 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4216 auto *KmpDependInfoRD = KmpDependInfoTy->castAsRecordDecl();
4217 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4218
4219 OMPIteratorGeneratorScope IteratorScope(
4220 CGF, cast_or_null<OMPIteratorExpr>(
4221 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4222 : nullptr));
4223 for (const Expr *E : Data.DepExprs) {
4224 llvm::Value *Addr;
4225 llvm::Value *Size;
4226
4227 // The expression will be a nullptr in the 'omp_all_memory' case.
4228 if (E) {
4229 std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4230 Addr = CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy);
4231 } else {
4232 Addr = llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4233 Size = llvm::ConstantInt::get(CGF.SizeTy, 0);
4234 }
4235 LValue Base;
4236 if (unsigned *P = dyn_cast<unsigned *>(Pos)) {
4237 Base = CGF.MakeAddrLValue(
4238 CGF.Builder.CreateConstGEP(DependenciesArray, *P), KmpDependInfoTy);
4239 } else {
4240 assert(E && "Expected a non-null expression");
4241 LValue &PosLVal = *cast<LValue *>(Pos);
4242 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4243 Base = CGF.MakeAddrLValue(
4244 CGF.Builder.CreateGEP(CGF, DependenciesArray, Idx), KmpDependInfoTy);
4245 }
4246 // deps[i].base_addr = &<Dependencies[i].second>;
4247 LValue BaseAddrLVal = CGF.EmitLValueForField(
4248 Base,
4249 *std::next(KmpDependInfoRD->field_begin(),
4250 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr)));
4251 CGF.EmitStoreOfScalar(Addr, BaseAddrLVal);
4252 // deps[i].len = sizeof(<Dependencies[i].second>);
4253 LValue LenLVal = CGF.EmitLValueForField(
4254 Base, *std::next(KmpDependInfoRD->field_begin(),
4255 static_cast<unsigned int>(RTLDependInfoFields::Len)));
4256 CGF.EmitStoreOfScalar(Size, LenLVal);
4257 // deps[i].flags = <Dependencies[i].first>;
4258 RTLDependenceKindTy DepKind = translateDependencyKind(Data.DepKind);
4259 LValue FlagsLVal = CGF.EmitLValueForField(
4260 Base,
4261 *std::next(KmpDependInfoRD->field_begin(),
4262 static_cast<unsigned int>(RTLDependInfoFields::Flags)));
4263 CGF.EmitStoreOfScalar(
4264 llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)),
4265 FlagsLVal);
4266 if (unsigned *P = dyn_cast<unsigned *>(Pos)) {
4267 ++(*P);
4268 } else {
4269 LValue &PosLVal = *cast<LValue *>(Pos);
4270 llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4271 Idx = CGF.Builder.CreateNUWAdd(Idx,
4272 llvm::ConstantInt::get(Idx->getType(), 1));
4273 CGF.EmitStoreOfScalar(Idx, PosLVal);
4274 }
4275 }
4276 }
4277
4278 SmallVector<llvm::Value *, 4> CGOpenMPRuntime::emitDepobjElementsSizes(
4279 CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4280 const OMPTaskDataTy::DependData &Data) {
4281 assert(Data.DepKind == OMPC_DEPEND_depobj &&
4282 "Expected depobj dependency kind.");
4283 SmallVector<llvm::Value *, 4> Sizes;
4284 SmallVector<LValue, 4> SizeLVals;
4285 ASTContext &C = CGF.getContext();
4286 {
4287 OMPIteratorGeneratorScope IteratorScope(
4288 CGF, cast_or_null<OMPIteratorExpr>(
4289 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4290 : nullptr));
4291 for (const Expr *E : Data.DepExprs) {
4292 llvm::Value *NumDeps;
4293 LValue Base;
4294 LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4295 std::tie(NumDeps, Base) =
4296 getDepobjElements(CGF, DepobjLVal, E->getExprLoc());
4297 LValue NumLVal = CGF.MakeAddrLValue(
4298 CGF.CreateMemTemp(C.getUIntPtrType(), "depobj.size.addr"),
4299 C.getUIntPtrType());
4300 CGF.Builder.CreateStore(llvm::ConstantInt::get(CGF.IntPtrTy, 0),
4301 NumLVal.getAddress());
4302 llvm::Value *PrevVal = CGF.EmitLoadOfScalar(NumLVal, E->getExprLoc());
4303 llvm::Value *Add = CGF.Builder.CreateNUWAdd(PrevVal, NumDeps);
4304 CGF.EmitStoreOfScalar(Add, NumLVal);
4305 SizeLVals.push_back(NumLVal);
4306 }
4307 }
4308 for (unsigned I = 0, E = SizeLVals.size(); I < E; ++I) {
4309 llvm::Value *Size =
4310 CGF.EmitLoadOfScalar(SizeLVals[I], Data.DepExprs[I]->getExprLoc());
4311 Sizes.push_back(Size);
4312 }
4313 return Sizes;
4314 }
4315
4316 void CGOpenMPRuntime::emitDepobjElements(CodeGenFunction &CGF,
4317 QualType &KmpDependInfoTy,
4318 LValue PosLVal,
4319 const OMPTaskDataTy::DependData &Data,
4320 Address DependenciesArray) {
4321 assert(Data.DepKind == OMPC_DEPEND_depobj &&
4322 "Expected depobj dependency kind.");
4323 llvm::Value *ElSize = CGF.getTypeSize(KmpDependInfoTy);
4324 {
4325 OMPIteratorGeneratorScope IteratorScope(
4326 CGF, cast_or_null<OMPIteratorExpr>(
4327 Data.IteratorExpr ? Data.IteratorExpr->IgnoreParenImpCasts()
4328 : nullptr));
4329 for (const Expr *E : Data.DepExprs) {
4330 llvm::Value *NumDeps;
4331 LValue Base;
4332 LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4333 std::tie(NumDeps, Base) =
4334 getDepobjElements(CGF, DepobjLVal, E->getExprLoc());
4335
4336 // memcopy dependency data.
4337 llvm::Value *Size = CGF.Builder.CreateNUWMul(
4338 ElSize,
4339 CGF.Builder.CreateIntCast(NumDeps, CGF.SizeTy, /*isSigned=*/false));
4340 llvm::Value *Pos = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4341 Address DepAddr = CGF.Builder.CreateGEP(CGF, DependenciesArray, Pos);
4342 CGF.Builder.CreateMemCpy(DepAddr, Base.getAddress(), Size);
4343
4344 // Increase pos.
4345 // pos += size;
4346 llvm::Value *Add = CGF.Builder.CreateNUWAdd(Pos, NumDeps);
4347 CGF.EmitStoreOfScalar(Add, PosLVal);
4348 }
4349 }
4350 }
4351
4352 std::pair<llvm::Value *, Address> CGOpenMPRuntime::emitDependClause(
4353 CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies,
4354 SourceLocation Loc) {
4355 if (llvm::all_of(Dependencies, [](const OMPTaskDataTy::DependData &D) {
4356 return D.DepExprs.empty();
4357 }))
4358 return std::make_pair(nullptr, Address::invalid());
4359 // Process list of dependencies.
4360 ASTContext &C = CGM.getContext();
4361 Address DependenciesArray = Address::invalid();
4362 llvm::Value *NumOfElements = nullptr;
4363 unsigned NumDependencies = std::accumulate(
4364 Dependencies.begin(), Dependencies.end(), 0,
4365 [](unsigned V, const OMPTaskDataTy::DependData &D) {
4366 return D.DepKind == OMPC_DEPEND_depobj
4367 ? V
4368 : (V + (D.IteratorExpr ? 0 : D.DepExprs.size()));
4369 });
4370 QualType FlagsTy;
4371 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4372 bool HasDepobjDeps = false;
4373 bool HasRegularWithIterators = false;
4374 llvm::Value *NumOfDepobjElements = llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4375 llvm::Value *NumOfRegularWithIterators =
4376 llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4377 // Calculate number of depobj dependencies and regular deps with the
4378 // iterators.
4379 for (const OMPTaskDataTy::DependData &D : Dependencies) {
4380 if (D.DepKind == OMPC_DEPEND_depobj) {
4381 SmallVector<llvm::Value *, 4> Sizes =
4382 emitDepobjElementsSizes(CGF, KmpDependInfoTy, D);
4383 for (llvm::Value *Size : Sizes) {
4384 NumOfDepobjElements =
4385 CGF.Builder.CreateNUWAdd(NumOfDepobjElements, Size);
4386 }
4387 HasDepobjDeps = true;
4388 continue;
4389 }
4390 // Include number of iterations, if any.
4391
4392 if (const auto *IE = cast_or_null<OMPIteratorExpr>(D.IteratorExpr)) {
4393 llvm::Value *ClauseIteratorSpace =
4394 llvm::ConstantInt::get(CGF.IntPtrTy, 1);
4395 for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) {
4396 llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4397 Sz = CGF.Builder.CreateIntCast(Sz, CGF.IntPtrTy, /*isSigned=*/false);
4398 ClauseIteratorSpace = CGF.Builder.CreateNUWMul(Sz, ClauseIteratorSpace);
4399 }
4400 llvm::Value *NumClauseDeps = CGF.Builder.CreateNUWMul(
4401 ClauseIteratorSpace,
4402 llvm::ConstantInt::get(CGF.IntPtrTy, D.DepExprs.size()));
4403 NumOfRegularWithIterators =
4404 CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumClauseDeps);
4405 HasRegularWithIterators = true;
4406 continue;
4407 }
4408 }
4409
4410 QualType KmpDependInfoArrayTy;
4411 if (HasDepobjDeps || HasRegularWithIterators) {
4412 NumOfElements = llvm::ConstantInt::get(CGM.IntPtrTy, NumDependencies,
4413 /*isSigned=*/false);
4414 if (HasDepobjDeps) {
4415 NumOfElements =
4416 CGF.Builder.CreateNUWAdd(NumOfDepobjElements, NumOfElements);
4417 }
4418 if (HasRegularWithIterators) {
4419 NumOfElements =
4420 CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumOfElements);
4421 }
4422 auto *OVE = new (C) OpaqueValueExpr(
4423 Loc, C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0),
4424 VK_PRValue);
4425 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
4426 RValue::get(NumOfElements));
4427 KmpDependInfoArrayTy =
4428 C.getVariableArrayType(KmpDependInfoTy, OVE, ArraySizeModifier::Normal,
4429 /*IndexTypeQuals=*/0);
4430 // CGF.EmitVariablyModifiedType(KmpDependInfoArrayTy);
4431 // Properly emit variable-sized array.
4432 auto *PD = ImplicitParamDecl::Create(C, KmpDependInfoArrayTy,
4433 ImplicitParamKind::Other);
4434 CGF.EmitVarDecl(*PD);
4435 DependenciesArray = CGF.GetAddrOfLocalVar(PD);
4436 NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
4437 /*isSigned=*/false);
4438 } else {
4439 KmpDependInfoArrayTy = C.getConstantArrayType(
4440 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), nullptr,
4441 ArraySizeModifier::Normal, /*IndexTypeQuals=*/0);
4442 DependenciesArray =
4443 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4444 DependenciesArray = CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0);
4445 NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumDependencies,
4446 /*isSigned=*/false);
4447 }
4448 unsigned Pos = 0;
4449 for (const OMPTaskDataTy::DependData &Dep : Dependencies) {
4450 if (Dep.DepKind == OMPC_DEPEND_depobj || Dep.IteratorExpr)
4451 continue;
4452 emitDependData(CGF, KmpDependInfoTy, &Pos, Dep, DependenciesArray);
4453 }
4454 // Copy regular dependencies with iterators.
4455 LValue PosLVal = CGF.MakeAddrLValue(
4456 CGF.CreateMemTemp(C.getSizeType(), "dep.counter.addr"), C.getSizeType());
4457 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4458 for (const OMPTaskDataTy::DependData &Dep : Dependencies) {
4459 if (Dep.DepKind == OMPC_DEPEND_depobj || !Dep.IteratorExpr)
4460 continue;
4461 emitDependData(CGF, KmpDependInfoTy, &PosLVal, Dep, DependenciesArray);
4462 }
4463 // Copy final depobj arrays without iterators.
4464 if (HasDepobjDeps) {
4465 for (const OMPTaskDataTy::DependData &Dep : Dependencies) {
4466 if (Dep.DepKind != OMPC_DEPEND_depobj)
4467 continue;
4468 emitDepobjElements(CGF, KmpDependInfoTy, PosLVal, Dep, DependenciesArray);
4469 }
4470 }
4471 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4472 DependenciesArray, CGF.VoidPtrTy, CGF.Int8Ty);
4473 return std::make_pair(NumOfElements, DependenciesArray);
4474 }
4475
4476 Address CGOpenMPRuntime::emitDepobjDependClause(
4477 CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies,
4478 SourceLocation Loc) {
4479 if (Dependencies.DepExprs.empty())
4480 return Address::invalid();
4481 // Process list of dependencies.
4482 ASTContext &C = CGM.getContext();
4483 Address DependenciesArray = Address::invalid();
4484 unsigned NumDependencies = Dependencies.DepExprs.size();
4485 QualType FlagsTy;
4486 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4487 auto *KmpDependInfoRD = KmpDependInfoTy->castAsRecordDecl();
4488
4489 llvm::Value *Size;
4490 // Define type kmp_depend_info[<Dependencies.size()>];
4491 // For depobj reserve one extra element to store the number of elements.
4492 // It is required to handle depobj(x) update(in) construct.
4493 // kmp_depend_info[<Dependencies.size()>] deps;
4494 llvm::Value *NumDepsVal;
4495 CharUnits Align = C.getTypeAlignInChars(KmpDependInfoTy);
4496 if (const auto *IE =
4497 cast_or_null<OMPIteratorExpr>(Dependencies.IteratorExpr)) {
4498 NumDepsVal = llvm::ConstantInt::get(CGF.SizeTy, 1);
4499 for (unsigned I = 0, E = IE->numOfIterators(); I < E; ++I) {
4500 llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4501 Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false);
4502 NumDepsVal = CGF.Builder.CreateNUWMul(NumDepsVal, Sz);
4503 }
4504 Size = CGF.Builder.CreateNUWAdd(llvm::ConstantInt::get(CGF.SizeTy, 1),
4505 NumDepsVal);
4506 CharUnits SizeInBytes =
4507 C.getTypeSizeInChars(KmpDependInfoTy).alignTo(Align);
4508 llvm::Value *RecSize = CGM.getSize(SizeInBytes);
4509 Size = CGF.Builder.CreateNUWMul(Size, RecSize);
4510 NumDepsVal =
4511 CGF.Builder.CreateIntCast(NumDepsVal, CGF.IntPtrTy, /*isSigned=*/false);
4512 } else {
4513 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
4514 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies + 1),
4515 nullptr, ArraySizeModifier::Normal, /*IndexTypeQuals=*/0);
4516 CharUnits Sz = C.getTypeSizeInChars(KmpDependInfoArrayTy);
4517 Size = CGM.getSize(Sz.alignTo(Align));
4518 NumDepsVal = llvm::ConstantInt::get(CGF.IntPtrTy, NumDependencies);
4519 }
4520 // Need to allocate on the dynamic memory.
4521 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4522 // Use default allocator.
4523 llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4524 llvm::Value *Args[] = {ThreadID, Size, Allocator};
4525
4526 llvm::Value *Addr =
4527 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4528 CGM.getModule(), OMPRTL___kmpc_alloc),
4529 Args, ".dep.arr.addr");
4530 llvm::Type *KmpDependInfoLlvmTy = CGF.ConvertTypeForMem(KmpDependInfoTy);
4531 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4532 Addr, CGF.Builder.getPtrTy(0));
4533 DependenciesArray = Address(Addr, KmpDependInfoLlvmTy, Align);
4534 // Write number of elements in the first element of array for depobj.
4535 LValue Base = CGF.MakeAddrLValue(DependenciesArray, KmpDependInfoTy);
4536 // deps[i].base_addr = NumDependencies;
4537 LValue BaseAddrLVal = CGF.EmitLValueForField(
4538 Base,
4539 *std::next(KmpDependInfoRD->field_begin(),
4540 static_cast<unsigned int>(RTLDependInfoFields::BaseAddr)));
4541 CGF.EmitStoreOfScalar(NumDepsVal, BaseAddrLVal);
4542 llvm::PointerUnion<unsigned *, LValue *> Pos;
4543 unsigned Idx = 1;
4544 LValue PosLVal;
4545 if (Dependencies.IteratorExpr) {
4546 PosLVal = CGF.MakeAddrLValue(
4547 CGF.CreateMemTemp(C.getSizeType(), "iterator.counter.addr"),
4548 C.getSizeType());
4549 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Idx), PosLVal,
4550 /*IsInit=*/true);
4551 Pos = &PosLVal;
4552 } else {
4553 Pos = &Idx;
4554 }
4555 emitDependData(CGF, KmpDependInfoTy, Pos, Dependencies, DependenciesArray);
4556 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4557 CGF.Builder.CreateConstGEP(DependenciesArray, 1), CGF.VoidPtrTy,
4558 CGF.Int8Ty);
4559 return DependenciesArray;
4560 }
4561
4562 void CGOpenMPRuntime::emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal,
4563 SourceLocation Loc) {
4564 ASTContext &C = CGM.getContext();
4565 QualType FlagsTy;
4566 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4567 LValue Base = CGF.EmitLoadOfPointerLValue(DepobjLVal.getAddress(),
4568 C.VoidPtrTy.castAs<PointerType>());
4569 QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4570 Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4571 Base.getAddress(), CGF.ConvertTypeForMem(KmpDependInfoPtrTy),
4572 CGF.ConvertTypeForMem(KmpDependInfoTy));
4573 llvm::Value *DepObjAddr = CGF.Builder.CreateGEP(
4574 Addr.getElementType(), Addr.emitRawPointer(CGF),
4575 llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4576 DepObjAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(DepObjAddr,
4577 CGF.VoidPtrTy);
4578 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4579 // Use default allocator.
4580 llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4581 llvm::Value *Args[] = {ThreadID, DepObjAddr, Allocator};
4582
4583 // _kmpc_free(gtid, addr, nullptr);
4584 (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4585 CGM.getModule(), OMPRTL___kmpc_free),
4586 Args);
4587 }
4588
4589 void CGOpenMPRuntime::emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal,
4590 OpenMPDependClauseKind NewDepKind,
4591 SourceLocation Loc) {
4592 ASTContext &C = CGM.getContext();
4593 QualType FlagsTy;
4594 getDependTypes(C, KmpDependInfoTy, FlagsTy);
4595 auto *KmpDependInfoRD = KmpDependInfoTy->castAsRecordDecl();
4596 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4597 llvm::Value *NumDeps;
4598 LValue Base;
4599 std::tie(NumDeps, Base) = getDepobjElements(CGF, DepobjLVal, Loc);
4600
4601 Address Begin = Base.getAddress();
4602 // Cast from pointer to array type to pointer to single element.
4603 llvm::Value *End = CGF.Builder.CreateGEP(Begin.getElementType(),
4604 Begin.emitRawPointer(CGF), NumDeps);
4605 // The basic structure here is a while-do loop.
4606 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.body");
4607 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.done");
4608 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
4609 CGF.EmitBlock(BodyBB);
4610 llvm::PHINode *ElementPHI =
4611 CGF.Builder.CreatePHI(Begin.getType(), 2, "omp.elementPast");
4612 ElementPHI->addIncoming(Begin.emitRawPointer(CGF), EntryBB);
4613 Begin = Begin.withPointer(ElementPHI, KnownNonNull);
4614 Base = CGF.MakeAddrLValue(Begin, KmpDependInfoTy, Base.getBaseInfo(),
4615 Base.getTBAAInfo());
4616 // deps[i].flags = NewDepKind;
4617 RTLDependenceKindTy DepKind = translateDependencyKind(NewDepKind);
4618 LValue FlagsLVal = CGF.EmitLValueForField(
4619 Base, *std::next(KmpDependInfoRD->field_begin(),
4620 static_cast<unsigned int>(RTLDependInfoFields::Flags)));
4621 CGF.EmitStoreOfScalar(
4622 llvm::ConstantInt::get(LLVMFlagsTy, static_cast<unsigned int>(DepKind)),
4623 FlagsLVal);
4624
4625 // Shift the address forward by one element.
4626 llvm::Value *ElementNext =
4627 CGF.Builder.CreateConstGEP(Begin, /*Index=*/1, "omp.elementNext")
4628 .emitRawPointer(CGF);
4629 ElementPHI->addIncoming(ElementNext, CGF.Builder.GetInsertBlock());
4630 llvm::Value *IsEmpty =
4631 CGF.Builder.CreateICmpEQ(ElementNext, End, "omp.isempty");
4632 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4633 // Done.
4634 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4635 }
4636
4637 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4638 const OMPExecutableDirective &D,
4639 llvm::Function *TaskFunction,
4640 QualType SharedsTy, Address Shareds,
4641 const Expr *IfCond,
4642 const OMPTaskDataTy &Data) {
4643 if (!CGF.HaveInsertPoint())
4644 return;
4645
4646 TaskResultTy Result =
4647 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4648 llvm::Value *NewTask = Result.NewTask;
4649 llvm::Function *TaskEntry = Result.TaskEntry;
4650 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4651 LValue TDBase = Result.TDBase;
4652 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4653 // Process list of dependences.
4654 Address DependenciesArray = Address::invalid();
4655 llvm::Value *NumOfElements;
4656 std::tie(NumOfElements, DependenciesArray) =
4657 emitDependClause(CGF, Data.Dependences, Loc);
4658
4659 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
4660 // libcall.
4661 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4662 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4663 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4664 // list is not empty
4665 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4666 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4667 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4668 llvm::Value *DepTaskArgs[7];
4669 if (!Data.Dependences.empty()) {
4670 DepTaskArgs[0] = UpLoc;
4671 DepTaskArgs[1] = ThreadID;
4672 DepTaskArgs[2] = NewTask;
4673 DepTaskArgs[3] = NumOfElements;
4674 DepTaskArgs[4] = DependenciesArray.emitRawPointer(CGF);
4675 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4676 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4677 }
4678 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, &TaskArgs,
4679 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4680 if (!Data.Tied) {
4681 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4682 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4683 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4684 }
4685 if (!Data.Dependences.empty()) {
4686 CGF.EmitRuntimeCall(
4687 OMPBuilder.getOrCreateRuntimeFunction(
4688 CGM.getModule(), OMPRTL___kmpc_omp_task_with_deps),
4689 DepTaskArgs);
4690 } else {
4691 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4692 CGM.getModule(), OMPRTL___kmpc_omp_task),
4693 TaskArgs);
4694 }
4695 // Check if parent region is untied and build return for untied task;
4696 if (auto *Region =
4697 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4698 Region->emitUntiedSwitch(CGF);
4699 };
4700
4701 llvm::Value *DepWaitTaskArgs[7];
4702 if (!Data.Dependences.empty()) {
4703 DepWaitTaskArgs[0] = UpLoc;
4704 DepWaitTaskArgs[1] = ThreadID;
4705 DepWaitTaskArgs[2] = NumOfElements;
4706 DepWaitTaskArgs[3] = DependenciesArray.emitRawPointer(CGF);
4707 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4708 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4709 DepWaitTaskArgs[6] =
4710 llvm::ConstantInt::get(CGF.Int32Ty, Data.HasNowaitClause);
4711 }
4712 auto &M = CGM.getModule();
4713 auto &&ElseCodeGen = [this, &M, &TaskArgs, ThreadID, NewTaskNewTaskTTy,
4714 TaskEntry, &Data, &DepWaitTaskArgs,
4715 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
4716 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4717 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4718 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4719 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4720 // is specified.
4721 if (!Data.Dependences.empty())
4722 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4723 M, OMPRTL___kmpc_omp_taskwait_deps_51),
4724 DepWaitTaskArgs);
4725 // Call proxy_task_entry(gtid, new_task);
4726 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4727 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
4728 Action.Enter(CGF);
4729 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4730 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
4731 OutlinedFnArgs);
4732 };
4733
4734 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4735 // kmp_task_t *new_task);
4736 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4737 // kmp_task_t *new_task);
4738 RegionCodeGenTy RCG(CodeGen);
4739 CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
4740 M, OMPRTL___kmpc_omp_task_begin_if0),
4741 TaskArgs,
4742 OMPBuilder.getOrCreateRuntimeFunction(
4743 M, OMPRTL___kmpc_omp_task_complete_if0),
4744 TaskArgs);
4745 RCG.setAction(Action);
4746 RCG(CGF);
4747 };
4748
4749 if (IfCond) {
4750 emitIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
4751 } else {
4752 RegionCodeGenTy ThenRCG(ThenCodeGen);
4753 ThenRCG(CGF);
4754 }
4755 }
4756
4757 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4758 const OMPLoopDirective &D,
4759 llvm::Function *TaskFunction,
4760 QualType SharedsTy, Address Shareds,
4761 const Expr *IfCond,
4762 const OMPTaskDataTy &Data) {
4763 if (!CGF.HaveInsertPoint())
4764 return;
4765 TaskResultTy Result =
4766 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4767 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
4768 // libcall.
4769 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4770 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4771 // sched, kmp_uint64 grainsize, void *task_dup);
4772 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4773 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4774 llvm::Value *IfVal;
4775 if (IfCond) {
4776 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4777 /*isSigned=*/true);
4778 } else {
4779 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4780 }
4781
4782 LValue LBLVal = CGF.EmitLValueForField(
4783 Result.TDBase,
4784 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
4785 const auto *LBVar =
4786 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4787 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4788 /*IsInitializer=*/true);
4789 LValue UBLVal = CGF.EmitLValueForField(
4790 Result.TDBase,
4791 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
4792 const auto *UBVar =
4793 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4794 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4795 /*IsInitializer=*/true);
4796 LValue StLVal = CGF.EmitLValueForField(
4797 Result.TDBase,
4798 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
4799 const auto *StVar =
4800 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4801 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4802 /*IsInitializer=*/true);
4803 // Store reductions address.
4804 LValue RedLVal = CGF.EmitLValueForField(
4805 Result.TDBase,
4806 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4807 if (Data.Reductions) {
4808 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4809 } else {
4810 CGF.EmitNullInitialization(RedLVal.getAddress(),
4811 CGF.getContext().VoidPtrTy);
4812 }
4813 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
4814 llvm::SmallVector<llvm::Value *, 12> TaskArgs{
4815 UpLoc,
4816 ThreadID,
4817 Result.NewTask,
4818 IfVal,
4819 LBLVal.getPointer(CGF),
4820 UBLVal.getPointer(CGF),
4821 CGF.EmitLoadOfScalar(StLVal, Loc),
4822 llvm::ConstantInt::getSigned(
4823 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
4824 llvm::ConstantInt::getSigned(
4825 CGF.IntTy, Data.Schedule.getPointer()
4826 ? Data.Schedule.getInt() ? NumTasks : Grainsize
4827 : NoSchedule),
4828 Data.Schedule.getPointer()
4829 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
4830 /*isSigned=*/false)
4831 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0)};
4832 if (Data.HasModifier)
4833 TaskArgs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1));
4834
4835 TaskArgs.push_back(Result.TaskDupFn
4836 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4837 Result.TaskDupFn, CGF.VoidPtrTy)
4838 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy));
4839 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4840 CGM.getModule(), Data.HasModifier
4841 ? OMPRTL___kmpc_taskloop_5
4842 : OMPRTL___kmpc_taskloop),
4843 TaskArgs);
4844 }
4845
4846 /// Emit reduction operation for each element of array (required for
4847 /// array sections) LHS op = RHS.
4848 /// \param Type Type of array.
4849 /// \param LHSVar Variable on the left side of the reduction operation
4850 /// (references element of array in original variable).
4851 /// \param RHSVar Variable on the right side of the reduction operation
4852 /// (references element of array in original variable).
4853 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
4854 /// RHSVar.
4855 static void EmitOMPAggregateReduction(
4856 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4857 const VarDecl *RHSVar,
4858 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4859 const Expr *, const Expr *)> &RedOpGen,
4860 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4861 const Expr *UpExpr = nullptr) {
4862 // Perform element-by-element initialization.
4863 QualType ElementTy;
4864 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4865 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4866
4867 // Drill down to the base element type on both arrays.
4868 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
4869 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4870
4871 llvm::Value *RHSBegin = RHSAddr.emitRawPointer(CGF);
4872 llvm::Value *LHSBegin = LHSAddr.emitRawPointer(CGF);
4873 // Cast from pointer to array type to pointer to single element.
4874 llvm::Value *LHSEnd =
4875 CGF.Builder.CreateGEP(LHSAddr.getElementType(), LHSBegin, NumElements);
4876 // The basic structure here is a while-do loop.
4877 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4878 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4879 llvm::Value *IsEmpty =
4880 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4881 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4882
4883 // Enter the loop body, making that address the current address.
4884 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
4885 CGF.EmitBlock(BodyBB);
4886
4887 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4888
4889 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4890 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4891 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4892 Address RHSElementCurrent(
4893 RHSElementPHI, RHSAddr.getElementType(),
4894 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4895
4896 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4897 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4898 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4899 Address LHSElementCurrent(
4900 LHSElementPHI, LHSAddr.getElementType(),
4901 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4902
4903 // Emit copy.
4904 CodeGenFunction::OMPPrivateScope Scope(CGF);
4905 Scope.addPrivate(LHSVar, LHSElementCurrent);
4906 Scope.addPrivate(RHSVar, RHSElementCurrent);
4907 Scope.Privatize();
4908 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4909 Scope.ForceCleanup();
4910
4911 // Shift the address forward by one element.
4912 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4913 LHSAddr.getElementType(), LHSElementPHI, /*Idx0=*/1,
4914 "omp.arraycpy.dest.element");
4915 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4916 RHSAddr.getElementType(), RHSElementPHI, /*Idx0=*/1,
4917 "omp.arraycpy.src.element");
4918 // Check whether we've reached the end.
4919 llvm::Value *Done =
4920 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4921 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4922 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4923 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4924
4925 // Done.
4926 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4927 }
4928
4929 /// Emit reduction combiner. If the combiner is a simple expression emit it as
4930 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4931 /// UDR combiner function.
4932 static void emitReductionCombiner(CodeGenFunction &CGF,
4933 const Expr *ReductionOp) {
4934 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
4935 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4936 if (const auto *DRE =
4937 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4938 if (const auto *DRD =
4939 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4940 std::pair<llvm::Function *, llvm::Function *> Reduction =
4941 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4942 RValue Func = RValue::get(Reduction.first);
4943 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4944 CGF.EmitIgnoredExpr(ReductionOp);
4945 return;
4946 }
4947 CGF.EmitIgnoredExpr(ReductionOp);
4948 }
4949
4950 llvm::Function *CGOpenMPRuntime::emitReductionFunction(
4951 StringRef ReducerName, SourceLocation Loc, llvm::Type *ArgsElemType,
4952 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
4953 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
4954 ASTContext &C = CGM.getContext();
4955
4956 // void reduction_func(void *LHSArg, void *RHSArg);
4957 FunctionArgList Args;
4958 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4959 ImplicitParamKind::Other);
4960 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
4961 ImplicitParamKind::Other);
4962 Args.push_back(&LHSArg);
4963 Args.push_back(&RHSArg);
4964 const auto &CGFI =
4965 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4966 std::string Name = getReductionFuncName(ReducerName);
4967 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
4968 llvm::GlobalValue::InternalLinkage, Name,
4969 &CGM.getModule());
4970 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
4971 Fn->setDoesNotRecurse();
4972 CodeGenFunction CGF(CGM);
4973 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
4974
4975 // Dst = (void*[n])(LHSArg);
4976 // Src = (void*[n])(RHSArg);
4977 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4978 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4979 CGF.Builder.getPtrTy(0)),
4980 ArgsElemType, CGF.getPointerAlign());
4981 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4982 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4983 CGF.Builder.getPtrTy(0)),
4984 ArgsElemType, CGF.getPointerAlign());
4985
4986 // ...
4987 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4988 // ...
4989 CodeGenFunction::OMPPrivateScope Scope(CGF);
4990 const auto *IPriv = Privates.begin();
4991 unsigned Idx = 0;
4992 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
4993 const auto *RHSVar =
4994 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4995 Scope.addPrivate(RHSVar, emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar));
4996 const auto *LHSVar =
4997 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4998 Scope.addPrivate(LHSVar, emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar));
4999 QualType PrivTy = (*IPriv)->getType();
5000 if (PrivTy->isVariablyModifiedType()) {
5001 // Get array size and emit VLA type.
5002 ++Idx;
5003 Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
5004 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
5005 const VariableArrayType *VLA =
5006 CGF.getContext().getAsVariableArrayType(PrivTy);
5007 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
5008 CodeGenFunction::OpaqueValueMapping OpaqueMap(
5009 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
5010 CGF.EmitVariablyModifiedType(PrivTy);
5011 }
5012 }
5013 Scope.Privatize();
5014 IPriv = Privates.begin();
5015 const auto *ILHS = LHSExprs.begin();
5016 const auto *IRHS = RHSExprs.begin();
5017 for (const Expr *E : ReductionOps) {
5018 if ((*IPriv)->getType()->isArrayType()) {
5019 // Emit reduction for array section.
5020 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5021 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5022 EmitOMPAggregateReduction(
5023 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5024 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5025 emitReductionCombiner(CGF, E);
5026 });
5027 } else {
5028 // Emit reduction for array subscript or single variable.
5029 emitReductionCombiner(CGF, E);
5030 }
5031 ++IPriv;
5032 ++ILHS;
5033 ++IRHS;
5034 }
5035 Scope.ForceCleanup();
5036 CGF.FinishFunction();
5037 return Fn;
5038 }
5039
5040 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5041 const Expr *ReductionOp,
5042 const Expr *PrivateRef,
5043 const DeclRefExpr *LHS,
5044 const DeclRefExpr *RHS) {
5045 if (PrivateRef->getType()->isArrayType()) {
5046 // Emit reduction for array section.
5047 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5048 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5049 EmitOMPAggregateReduction(
5050 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5051 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5052 emitReductionCombiner(CGF, ReductionOp);
5053 });
5054 } else {
5055 // Emit reduction for array subscript or single variable.
5056 emitReductionCombiner(CGF, ReductionOp);
5057 }
5058 }
5059
5060 static std::string generateUniqueName(CodeGenModule &CGM,
5061 llvm::StringRef Prefix, const Expr *Ref);
5062
5063 void CGOpenMPRuntime::emitPrivateReduction(
5064 CodeGenFunction &CGF, SourceLocation Loc, const Expr *Privates,
5065 const Expr *LHSExprs, const Expr *RHSExprs, const Expr *ReductionOps) {
5066
5067 // Create a shared global variable (__shared_reduction_var) to accumulate the
5068 // final result.
5069 //
5070 // Call __kmpc_barrier to synchronize threads before initialization.
5071 //
5072 // The master thread (thread_id == 0) initializes __shared_reduction_var
5073 // with the identity value or initializer.
5074 //
5075 // Call __kmpc_barrier to synchronize before combining.
5076 // For each i:
5077 // - Thread enters critical section.
5078 // - Reads its private value from LHSExprs[i].
5079 // - Updates __shared_reduction_var[i] = RedOp_i(__shared_reduction_var[i],
5080 // Privates[i]).
5081 // - Exits critical section.
5082 //
5083 // Call __kmpc_barrier after combining.
5084 //
5085 // Each thread copies __shared_reduction_var[i] back to RHSExprs[i].
5086 //
5087 // Final __kmpc_barrier to synchronize after broadcasting
5088 QualType PrivateType = Privates->getType();
5089 llvm::Type *LLVMType = CGF.ConvertTypeForMem(PrivateType);
5090
5091 const OMPDeclareReductionDecl *UDR = getReductionInit(ReductionOps);
5092 std::string ReductionVarNameStr;
5093 if (const auto *DRE = dyn_cast<DeclRefExpr>(Privates->IgnoreParenCasts()))
5094 ReductionVarNameStr =
5095 generateUniqueName(CGM, DRE->getDecl()->getNameAsString(), Privates);
5096 else
5097 ReductionVarNameStr = "unnamed_priv_var";
5098
5099 // Create an internal shared variable
5100 std::string SharedName =
5101 CGM.getOpenMPRuntime().getName({"internal_pivate_", ReductionVarNameStr});
5102 llvm::GlobalVariable *SharedVar = OMPBuilder.getOrCreateInternalVariable(
5103 LLVMType, ".omp.reduction." + SharedName);
5104
5105 SharedVar->setAlignment(
5106 llvm::MaybeAlign(CGF.getContext().getTypeAlign(PrivateType) / 8));
5107
5108 Address SharedResult =
5109 CGF.MakeNaturalAlignRawAddrLValue(SharedVar, PrivateType).getAddress();
5110
5111 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5112 llvm::Value *BarrierLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5113 llvm::Value *BarrierArgs[] = {BarrierLoc, ThreadId};
5114
5115 llvm::BasicBlock *InitBB = CGF.createBasicBlock("init");
5116 llvm::BasicBlock *InitEndBB = CGF.createBasicBlock("init.end");
5117
5118 llvm::Value *IsWorker = CGF.Builder.CreateICmpEQ(
5119 ThreadId, llvm::ConstantInt::get(ThreadId->getType(), 0));
5120 CGF.Builder.CreateCondBr(IsWorker, InitBB, InitEndBB);
5121
5122 CGF.EmitBlock(InitBB);
5123
5124 auto EmitSharedInit = [&]() {
5125 if (UDR) { // Check if it's a User-Defined Reduction
5126 if (const Expr *UDRInitExpr = UDR->getInitializer()) {
5127 std::pair<llvm::Function *, llvm::Function *> FnPair =
5128 getUserDefinedReduction(UDR);
5129 llvm::Function *InitializerFn = FnPair.second;
5130 if (InitializerFn) {
5131 if (const auto *CE =
5132 dyn_cast<CallExpr>(UDRInitExpr->IgnoreParenImpCasts())) {
5133 const auto *OutDRE = cast<DeclRefExpr>(
5134 cast<UnaryOperator>(CE->getArg(0)->IgnoreParenImpCasts())
5135 ->getSubExpr());
5136 const VarDecl *OutVD = cast<VarDecl>(OutDRE->getDecl());
5137
5138 CodeGenFunction::OMPPrivateScope LocalScope(CGF);
5139 LocalScope.addPrivate(OutVD, SharedResult);
5140
5141 (void)LocalScope.Privatize();
5142 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(
5143 CE->getCallee()->IgnoreParenImpCasts())) {
5144 CodeGenFunction::OpaqueValueMapping OpaqueMap(
5145 CGF, OVE, RValue::get(InitializerFn));
5146 CGF.EmitIgnoredExpr(CE);
5147 } else {
5148 CGF.EmitAnyExprToMem(UDRInitExpr, SharedResult,
5149 PrivateType.getQualifiers(),
5150 /*IsInitializer=*/true);
5151 }
5152 } else {
5153 CGF.EmitAnyExprToMem(UDRInitExpr, SharedResult,
5154 PrivateType.getQualifiers(),
5155 /*IsInitializer=*/true);
5156 }
5157 } else {
5158 CGF.EmitAnyExprToMem(UDRInitExpr, SharedResult,
5159 PrivateType.getQualifiers(),
5160 /*IsInitializer=*/true);
5161 }
5162 } else {
5163 // EmitNullInitialization handles default construction for C++ classes
5164 // and zeroing for scalars, which is a reasonable default.
5165 CGF.EmitNullInitialization(SharedResult, PrivateType);
5166 }
5167 return; // UDR initialization handled
5168 }
5169 if (const auto *DRE = dyn_cast<DeclRefExpr>(Privates)) {
5170 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
5171 if (const Expr *InitExpr = VD->getInit()) {
5172 CGF.EmitAnyExprToMem(InitExpr, SharedResult,
5173 PrivateType.getQualifiers(), true);
5174 return;
5175 }
5176 }
5177 }
5178 CGF.EmitNullInitialization(SharedResult, PrivateType);
5179 };
5180 EmitSharedInit();
5181 CGF.Builder.CreateBr(InitEndBB);
5182 CGF.EmitBlock(InitEndBB);
5183
5184 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
5185 CGM.getModule(), OMPRTL___kmpc_barrier),
5186 BarrierArgs);
5187
5188 const Expr *ReductionOp = ReductionOps;
5189 const OMPDeclareReductionDecl *CurrentUDR = getReductionInit(ReductionOp);
5190 LValue SharedLV = CGF.MakeAddrLValue(SharedResult, PrivateType);
5191 LValue LHSLV = CGF.EmitLValue(Privates);
5192
5193 auto EmitCriticalReduction = [&](auto ReductionGen) {
5194 std::string CriticalName = getName({"reduction_critical"});
5195 emitCriticalRegion(CGF, CriticalName, ReductionGen, Loc);
5196 };
5197
5198 if (CurrentUDR) {
5199 // Handle user-defined reduction.
5200 auto ReductionGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
5201 Action.Enter(CGF);
5202 std::pair<llvm::Function *, llvm::Function *> FnPair =
5203 getUserDefinedReduction(CurrentUDR);
5204 if (FnPair.first) {
5205 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) {
5206 const auto *OutDRE = cast<DeclRefExpr>(
5207 cast<UnaryOperator>(CE->getArg(0)->IgnoreParenImpCasts())
5208 ->getSubExpr());
5209 const auto *InDRE = cast<DeclRefExpr>(
5210 cast<UnaryOperator>(CE->getArg(1)->IgnoreParenImpCasts())
5211 ->getSubExpr());
5212 CodeGenFunction::OMPPrivateScope LocalScope(CGF);
5213 LocalScope.addPrivate(cast<VarDecl>(OutDRE->getDecl()),
5214 SharedLV.getAddress());
5215 LocalScope.addPrivate(cast<VarDecl>(InDRE->getDecl()),
5216 LHSLV.getAddress());
5217 (void)LocalScope.Privatize();
5218 emitReductionCombiner(CGF, ReductionOp);
5219 }
5220 }
5221 };
5222 EmitCriticalReduction(ReductionGen);
5223 } else {
5224 // Handle built-in reduction operations.
5225 #ifndef NDEBUG
5226 const Expr *ReductionClauseExpr = ReductionOp->IgnoreParenCasts();
5227 if (const auto *Cleanup = dyn_cast<ExprWithCleanups>(ReductionClauseExpr))
5228 ReductionClauseExpr = Cleanup->getSubExpr()->IgnoreParenCasts();
5229
5230 const Expr *AssignRHS = nullptr;
5231 if (const auto *BinOp = dyn_cast<BinaryOperator>(ReductionClauseExpr)) {
5232 if (BinOp->getOpcode() == BO_Assign)
5233 AssignRHS = BinOp->getRHS();
5234 } else if (const auto *OpCall =
5235 dyn_cast<CXXOperatorCallExpr>(ReductionClauseExpr)) {
5236 if (OpCall->getOperator() == OO_Equal)
5237 AssignRHS = OpCall->getArg(1);
5238 }
5239
5240 assert(AssignRHS &&
5241 "Private Variable Reduction : Invalid ReductionOp expression");
5242 #endif
5243
5244 auto ReductionGen = [&](CodeGenFunction &CGF, PrePostActionTy &Action) {
5245 Action.Enter(CGF);
5246 const auto *OmpOutDRE =
5247 dyn_cast<DeclRefExpr>(LHSExprs->IgnoreParenImpCasts());
5248 const auto *OmpInDRE =
5249 dyn_cast<DeclRefExpr>(RHSExprs->IgnoreParenImpCasts());
5250 assert(
5251 OmpOutDRE && OmpInDRE &&
5252 "Private Variable Reduction : LHSExpr/RHSExpr must be DeclRefExprs");
5253 const VarDecl *OmpOutVD = cast<VarDecl>(OmpOutDRE->getDecl());
5254 const VarDecl *OmpInVD = cast<VarDecl>(OmpInDRE->getDecl());
5255 CodeGenFunction::OMPPrivateScope LocalScope(CGF);
5256 LocalScope.addPrivate(OmpOutVD, SharedLV.getAddress());
5257 LocalScope.addPrivate(OmpInVD, LHSLV.getAddress());
5258 (void)LocalScope.Privatize();
5259 // Emit the actual reduction operation
5260 CGF.EmitIgnoredExpr(ReductionOp);
5261 };
5262 EmitCriticalReduction(ReductionGen);
5263 }
5264
5265 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
5266 CGM.getModule(), OMPRTL___kmpc_barrier),
5267 BarrierArgs);
5268
5269 // Broadcast final result
5270 bool IsAggregate = PrivateType->isAggregateType();
5271 LValue SharedLV1 = CGF.MakeAddrLValue(SharedResult, PrivateType);
5272 llvm::Value *FinalResultVal = nullptr;
5273 Address FinalResultAddr = Address::invalid();
5274
5275 if (IsAggregate)
5276 FinalResultAddr = SharedResult;
5277 else
5278 FinalResultVal = CGF.EmitLoadOfScalar(SharedLV1, Loc);
5279
5280 LValue TargetLHSLV = CGF.EmitLValue(RHSExprs);
5281 if (IsAggregate) {
5282 CGF.EmitAggregateCopy(TargetLHSLV,
5283 CGF.MakeAddrLValue(FinalResultAddr, PrivateType),
5284 PrivateType, AggValueSlot::DoesNotOverlap, false);
5285 } else {
5286 CGF.EmitStoreOfScalar(FinalResultVal, TargetLHSLV);
5287 }
5288 // Final synchronization barrier
5289 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
5290 CGM.getModule(), OMPRTL___kmpc_barrier),
5291 BarrierArgs);
5292
5293 // Combiner with original list item
5294 auto OriginalListCombiner = [&](CodeGenFunction &CGF,
5295 PrePostActionTy &Action) {
5296 Action.Enter(CGF);
5297 emitSingleReductionCombiner(CGF, ReductionOps, Privates,
5298 cast<DeclRefExpr>(LHSExprs),
5299 cast<DeclRefExpr>(RHSExprs));
5300 };
5301 EmitCriticalReduction(OriginalListCombiner);
5302 }
5303
5304 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
5305 ArrayRef<const Expr *> OrgPrivates,
5306 ArrayRef<const Expr *> OrgLHSExprs,
5307 ArrayRef<const Expr *> OrgRHSExprs,
5308 ArrayRef<const Expr *> OrgReductionOps,
5309 ReductionOptionsTy Options) {
5310 if (!CGF.HaveInsertPoint())
5311 return;
5312
5313 bool WithNowait = Options.WithNowait;
5314 bool SimpleReduction = Options.SimpleReduction;
5315
5316 // Next code should be emitted for reduction:
5317 //
5318 // static kmp_critical_name lock = { 0 };
5319 //
5320 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5321 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5322 // ...
5323 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5324 // *(Type<n>-1*)rhs[<n>-1]);
5325 // }
5326 //
5327 // ...
5328 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5329 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5330 // RedList, reduce_func, &<lock>)) {
5331 // case 1:
5332 // ...
5333 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5334 // ...
5335 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5336 // break;
5337 // case 2:
5338 // ...
5339 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5340 // ...
5341 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
5342 // break;
5343 // default:;
5344 // }
5345 //
5346 // if SimpleReduction is true, only the next code is generated:
5347 // ...
5348 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5349 // ...
5350
5351 ASTContext &C = CGM.getContext();
5352
5353 if (SimpleReduction) {
5354 CodeGenFunction::RunCleanupsScope Scope(CGF);
5355 const auto *IPriv = OrgPrivates.begin();
5356 const auto *ILHS = OrgLHSExprs.begin();
5357 const auto *IRHS = OrgRHSExprs.begin();
5358 for (const Expr *E : OrgReductionOps) {
5359 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5360 cast<DeclRefExpr>(*IRHS));
5361 ++IPriv;
5362 ++ILHS;
5363 ++IRHS;
5364 }
5365 return;
5366 }
5367
5368 // Filter out shared reduction variables based on IsPrivateVarReduction flag.
5369 // Only keep entries where the corresponding variable is not private.
5370 SmallVector<const Expr *> FilteredPrivates, FilteredLHSExprs,
5371 FilteredRHSExprs, FilteredReductionOps;
5372 for (unsigned I : llvm::seq<unsigned>(
5373 std::min(OrgReductionOps.size(), OrgLHSExprs.size()))) {
5374 if (!Options.IsPrivateVarReduction[I]) {
5375 FilteredPrivates.emplace_back(OrgPrivates[I]);
5376 FilteredLHSExprs.emplace_back(OrgLHSExprs[I]);
5377 FilteredRHSExprs.emplace_back(OrgRHSExprs[I]);
5378 FilteredReductionOps.emplace_back(OrgReductionOps[I]);
5379 }
5380 }
5381 // Wrap filtered vectors in ArrayRef for downstream shared reduction
5382 // processing.
5383 ArrayRef<const Expr *> Privates = FilteredPrivates;
5384 ArrayRef<const Expr *> LHSExprs = FilteredLHSExprs;
5385 ArrayRef<const Expr *> RHSExprs = FilteredRHSExprs;
5386 ArrayRef<const Expr *> ReductionOps = FilteredReductionOps;
5387
5388 // 1. Build a list of reduction variables.
5389 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
5390 auto Size = RHSExprs.size();
5391 for (const Expr *E : Privates) {
5392 if (E->getType()->isVariablyModifiedType())
5393 // Reserve place for array size.
5394 ++Size;
5395 }
5396 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
5397 QualType ReductionArrayTy = C.getConstantArrayType(
5398 C.VoidPtrTy, ArraySize, nullptr, ArraySizeModifier::Normal,
5399 /*IndexTypeQuals=*/0);
5400 RawAddress ReductionList =
5401 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
5402 const auto *IPriv = Privates.begin();
5403 unsigned Idx = 0;
5404 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
5405 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
5406 CGF.Builder.CreateStore(
5407 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5408 CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
5409 Elem);
5410 if ((*IPriv)->getType()->isVariablyModifiedType()) {
5411 // Store array size.
5412 ++Idx;
5413 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
5414 llvm::Value *Size = CGF.Builder.CreateIntCast(
5415 CGF.getVLASize(
5416 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5417 .NumElts,
5418 CGF.SizeTy, /*isSigned=*/false);
5419 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5420 Elem);
5421 }
5422 }
5423
5424 // 2. Emit reduce_func().
5425 llvm::Function *ReductionFn = emitReductionFunction(
5426 CGF.CurFn->getName(), Loc, CGF.ConvertTypeForMem(ReductionArrayTy),
5427 Privates, LHSExprs, RHSExprs, ReductionOps);
5428
5429 // 3. Create static kmp_critical_name lock = { 0 };
5430 std::string Name = getName({"reduction"});
5431 llvm::Value *Lock = getCriticalRegionLock(Name);
5432
5433 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5434 // RedList, reduce_func, &<lock>);
5435 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5436 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5437 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5438 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5439 ReductionList.getPointer(), CGF.VoidPtrTy);
5440 llvm::Value *Args[] = {
5441 IdentTLoc, // ident_t *<loc>
5442 ThreadId, // i32 <gtid>
5443 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5444 ReductionArrayTySize, // size_type sizeof(RedList)
5445 RL, // void *RedList
5446 ReductionFn, // void (*) (void *, void *) <reduce_func>
5447 Lock // kmp_critical_name *&<lock>
5448 };
5449 llvm::Value *Res = CGF.EmitRuntimeCall(
5450 OMPBuilder.getOrCreateRuntimeFunction(
5451 CGM.getModule(),
5452 WithNowait ? OMPRTL___kmpc_reduce_nowait : OMPRTL___kmpc_reduce),
5453 Args);
5454
5455 // 5. Build switch(res)
5456 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5457 llvm::SwitchInst *SwInst =
5458 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5459
5460 // 6. Build case 1:
5461 // ...
5462 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5463 // ...
5464 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5465 // break;
5466 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5467 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5468 CGF.EmitBlock(Case1BB);
5469
5470 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5471 llvm::Value *EndArgs[] = {
5472 IdentTLoc, // ident_t *<loc>
5473 ThreadId, // i32 <gtid>
5474 Lock // kmp_critical_name *&<lock>
5475 };
5476 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5477 CodeGenFunction &CGF, PrePostActionTy &Action) {
5478 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
5479 const auto *IPriv = Privates.begin();
5480 const auto *ILHS = LHSExprs.begin();
5481 const auto *IRHS = RHSExprs.begin();
5482 for (const Expr *E : ReductionOps) {
5483 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5484 cast<DeclRefExpr>(*IRHS));
5485 ++IPriv;
5486 ++ILHS;
5487 ++IRHS;
5488 }
5489 };
5490 RegionCodeGenTy RCG(CodeGen);
5491 CommonActionTy Action(
5492 nullptr, {},
5493 OMPBuilder.getOrCreateRuntimeFunction(
5494 CGM.getModule(), WithNowait ? OMPRTL___kmpc_end_reduce_nowait
5495 : OMPRTL___kmpc_end_reduce),
5496 EndArgs);
5497 RCG.setAction(Action);
5498 RCG(CGF);
5499
5500 CGF.EmitBranch(DefaultBB);
5501
5502 // 7. Build case 2:
5503 // ...
5504 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5505 // ...
5506 // break;
5507 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5508 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5509 CGF.EmitBlock(Case2BB);
5510
5511 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5512 CodeGenFunction &CGF, PrePostActionTy &Action) {
5513 const auto *ILHS = LHSExprs.begin();
5514 const auto *IRHS = RHSExprs.begin();
5515 const auto *IPriv = Privates.begin();
5516 for (const Expr *E : ReductionOps) {
5517 const Expr *XExpr = nullptr;
5518 const Expr *EExpr = nullptr;
5519 const Expr *UpExpr = nullptr;
5520 BinaryOperatorKind BO = BO_Comma;
5521 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
5522 if (BO->getOpcode() == BO_Assign) {
5523 XExpr = BO->getLHS();
5524 UpExpr = BO->getRHS();
5525 }
5526 }
5527 // Try to emit update expression as a simple atomic.
5528 const Expr *RHSExpr = UpExpr;
5529 if (RHSExpr) {
5530 // Analyze RHS part of the whole expression.
5531 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
5532 RHSExpr->IgnoreParenImpCasts())) {
5533 // If this is a conditional operator, analyze its condition for
5534 // min/max reduction operator.
5535 RHSExpr = ACO->getCond();
5536 }
5537 if (const auto *BORHS =
5538 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5539 EExpr = BORHS->getRHS();
5540 BO = BORHS->getOpcode();
5541 }
5542 }
5543 if (XExpr) {
5544 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5545 auto &&AtomicRedGen = [BO, VD,
5546 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5547 const Expr *EExpr, const Expr *UpExpr) {
5548 LValue X = CGF.EmitLValue(XExpr);
5549 RValue E;
5550 if (EExpr)
5551 E = CGF.EmitAnyExpr(EExpr);
5552 CGF.EmitOMPAtomicSimpleUpdateExpr(
5553 X, E, BO, /*IsXLHSInRHSPart=*/true,
5554 llvm::AtomicOrdering::Monotonic, Loc,
5555 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
5556 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5557 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5558 CGF.emitOMPSimpleStore(
5559 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5560 VD->getType().getNonReferenceType(), Loc);
5561 PrivateScope.addPrivate(VD, LHSTemp);
5562 (void)PrivateScope.Privatize();
5563 return CGF.EmitAnyExpr(UpExpr);
5564 });
5565 };
5566 if ((*IPriv)->getType()->isArrayType()) {
5567 // Emit atomic reduction for array section.
5568 const auto *RHSVar =
5569 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5570 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5571 AtomicRedGen, XExpr, EExpr, UpExpr);
5572 } else {
5573 // Emit atomic reduction for array subscript or single variable.
5574 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5575 }
5576 } else {
5577 // Emit as a critical region.
5578 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5579 const Expr *, const Expr *) {
5580 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
5581 std::string Name = RT.getName({"atomic_reduction"});
5582 RT.emitCriticalRegion(
5583 CGF, Name,
5584 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5585 Action.Enter(CGF);
5586 emitReductionCombiner(CGF, E);
5587 },
5588 Loc);
5589 };
5590 if ((*IPriv)->getType()->isArrayType()) {
5591 const auto *LHSVar =
5592 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5593 const auto *RHSVar =
5594 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5595 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5596 CritRedGen);
5597 } else {
5598 CritRedGen(CGF, nullptr, nullptr, nullptr);
5599 }
5600 }
5601 ++ILHS;
5602 ++IRHS;
5603 ++IPriv;
5604 }
5605 };
5606 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5607 if (!WithNowait) {
5608 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5609 llvm::Value *EndArgs[] = {
5610 IdentTLoc, // ident_t *<loc>
5611 ThreadId, // i32 <gtid>
5612 Lock // kmp_critical_name *&<lock>
5613 };
5614 CommonActionTy Action(nullptr, {},
5615 OMPBuilder.getOrCreateRuntimeFunction(
5616 CGM.getModule(), OMPRTL___kmpc_end_reduce),
5617 EndArgs);
5618 AtomicRCG.setAction(Action);
5619 AtomicRCG(CGF);
5620 } else {
5621 AtomicRCG(CGF);
5622 }
5623
5624 CGF.EmitBranch(DefaultBB);
5625 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5626 assert(OrgLHSExprs.size() == OrgPrivates.size() &&
5627 "PrivateVarReduction: Privates size mismatch");
5628 assert(OrgLHSExprs.size() == OrgReductionOps.size() &&
5629 "PrivateVarReduction: ReductionOps size mismatch");
5630 for (unsigned I : llvm::seq<unsigned>(
5631 std::min(OrgReductionOps.size(), OrgLHSExprs.size()))) {
5632 if (Options.IsPrivateVarReduction[I])
5633 emitPrivateReduction(CGF, Loc, OrgPrivates[I], OrgLHSExprs[I],
5634 OrgRHSExprs[I], OrgReductionOps[I]);
5635 }
5636 }
5637
5638 /// Generates unique name for artificial threadprivate variables.
5639 /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5640 static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5641 const Expr *Ref) {
5642 SmallString<256> Buffer;
5643 llvm::raw_svector_ostream Out(Buffer);
5644 const clang::DeclRefExpr *DE;
5645 const VarDecl *D = ::getBaseDecl(Ref, DE);
5646 if (!D)
5647 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5648 D = D->getCanonicalDecl();
5649 std::string Name = CGM.getOpenMPRuntime().getName(
5650 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5651 Out << Prefix << Name << "_"
5652 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
5653 return std::string(Out.str());
5654 }
5655
5656 /// Emits reduction initializer function:
5657 /// \code
5658 /// void @.red_init(void* %arg, void* %orig) {
5659 /// %0 = bitcast void* %arg to <type>*
5660 /// store <type> <init>, <type>* %0
5661 /// ret void
5662 /// }
5663 /// \endcode
5664 static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5665 SourceLocation Loc,
5666 ReductionCodeGen &RCG, unsigned N) {
5667 ASTContext &C = CGM.getContext();
5668 QualType VoidPtrTy = C.VoidPtrTy;
5669 VoidPtrTy.addRestrict();
5670 FunctionArgList Args;
5671 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy,
5672 ImplicitParamKind::Other);
5673 ImplicitParamDecl ParamOrig(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, VoidPtrTy,
5674 ImplicitParamKind::Other);
5675 Args.emplace_back(&Param);
5676 Args.emplace_back(&ParamOrig);
5677 const auto &FnInfo =
5678 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5679 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5680 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
5681 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5682 Name, &CGM.getModule());
5683 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5684 Fn->setDoesNotRecurse();
5685 CodeGenFunction CGF(CGM);
5686 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5687 QualType PrivateType = RCG.getPrivateType(N);
5688 Address PrivateAddr = CGF.EmitLoadOfPointer(
5689 CGF.GetAddrOfLocalVar(&Param).withElementType(CGF.Builder.getPtrTy(0)),
5690 C.getPointerType(PrivateType)->castAs<PointerType>());
5691 llvm::Value *Size = nullptr;
5692 // If the size of the reduction item is non-constant, load it from global
5693 // threadprivate variable.
5694 if (RCG.getSizes(N).second) {
5695 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5696 CGF, CGM.getContext().getSizeType(),
5697 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5698 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5699 CGM.getContext().getSizeType(), Loc);
5700 }
5701 RCG.emitAggregateType(CGF, N, Size);
5702 Address OrigAddr = Address::invalid();
5703 // If initializer uses initializer from declare reduction construct, emit a
5704 // pointer to the address of the original reduction item (reuired by reduction
5705 // initializer)
5706 if (RCG.usesReductionInitializer(N)) {
5707 Address SharedAddr = CGF.GetAddrOfLocalVar(&ParamOrig);
5708 OrigAddr = CGF.EmitLoadOfPointer(
5709 SharedAddr,
5710 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
5711 }
5712 // Emit the initializer:
5713 // %0 = bitcast void* %arg to <type>*
5714 // store <type> <init>, <type>* %0
5715 RCG.emitInitialization(CGF, N, PrivateAddr, OrigAddr,
5716 [](CodeGenFunction &) { return false; });
5717 CGF.FinishFunction();
5718 return Fn;
5719 }
5720
5721 /// Emits reduction combiner function:
5722 /// \code
5723 /// void @.red_comb(void* %arg0, void* %arg1) {
5724 /// %lhs = bitcast void* %arg0 to <type>*
5725 /// %rhs = bitcast void* %arg1 to <type>*
5726 /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5727 /// store <type> %2, <type>* %lhs
5728 /// ret void
5729 /// }
5730 /// \endcode
5731 static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5732 SourceLocation Loc,
5733 ReductionCodeGen &RCG, unsigned N,
5734 const Expr *ReductionOp,
5735 const Expr *LHS, const Expr *RHS,
5736 const Expr *PrivateRef) {
5737 ASTContext &C = CGM.getContext();
5738 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5739 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5740 FunctionArgList Args;
5741 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5742 C.VoidPtrTy, ImplicitParamKind::Other);
5743 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5744 ImplicitParamKind::Other);
5745 Args.emplace_back(&ParamInOut);
5746 Args.emplace_back(&ParamIn);
5747 const auto &FnInfo =
5748 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5749 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5750 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
5751 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5752 Name, &CGM.getModule());
5753 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5754 Fn->setDoesNotRecurse();
5755 CodeGenFunction CGF(CGM);
5756 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5757 llvm::Value *Size = nullptr;
5758 // If the size of the reduction item is non-constant, load it from global
5759 // threadprivate variable.
5760 if (RCG.getSizes(N).second) {
5761 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5762 CGF, CGM.getContext().getSizeType(),
5763 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5764 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5765 CGM.getContext().getSizeType(), Loc);
5766 }
5767 RCG.emitAggregateType(CGF, N, Size);
5768 // Remap lhs and rhs variables to the addresses of the function arguments.
5769 // %lhs = bitcast void* %arg0 to <type>*
5770 // %rhs = bitcast void* %arg1 to <type>*
5771 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5772 PrivateScope.addPrivate(
5773 LHSVD,
5774 // Pull out the pointer to the variable.
5775 CGF.EmitLoadOfPointer(
5776 CGF.GetAddrOfLocalVar(&ParamInOut)
5777 .withElementType(CGF.Builder.getPtrTy(0)),
5778 C.getPointerType(LHSVD->getType())->castAs<PointerType>()));
5779 PrivateScope.addPrivate(
5780 RHSVD,
5781 // Pull out the pointer to the variable.
5782 CGF.EmitLoadOfPointer(
5783 CGF.GetAddrOfLocalVar(&ParamIn).withElementType(
5784 CGF.Builder.getPtrTy(0)),
5785 C.getPointerType(RHSVD->getType())->castAs<PointerType>()));
5786 PrivateScope.Privatize();
5787 // Emit the combiner body:
5788 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5789 // store <type> %2, <type>* %lhs
5790 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5791 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5792 cast<DeclRefExpr>(RHS));
5793 CGF.FinishFunction();
5794 return Fn;
5795 }
5796
5797 /// Emits reduction finalizer function:
5798 /// \code
5799 /// void @.red_fini(void* %arg) {
5800 /// %0 = bitcast void* %arg to <type>*
5801 /// <destroy>(<type>* %0)
5802 /// ret void
5803 /// }
5804 /// \endcode
5805 static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5806 SourceLocation Loc,
5807 ReductionCodeGen &RCG, unsigned N) {
5808 if (!RCG.needCleanups(N))
5809 return nullptr;
5810 ASTContext &C = CGM.getContext();
5811 FunctionArgList Args;
5812 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5813 ImplicitParamKind::Other);
5814 Args.emplace_back(&Param);
5815 const auto &FnInfo =
5816 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5817 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5818 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
5819 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5820 Name, &CGM.getModule());
5821 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5822 Fn->setDoesNotRecurse();
5823 CodeGenFunction CGF(CGM);
5824 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5825 Address PrivateAddr = CGF.EmitLoadOfPointer(
5826 CGF.GetAddrOfLocalVar(&Param), C.VoidPtrTy.castAs<PointerType>());
5827 llvm::Value *Size = nullptr;
5828 // If the size of the reduction item is non-constant, load it from global
5829 // threadprivate variable.
5830 if (RCG.getSizes(N).second) {
5831 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5832 CGF, CGM.getContext().getSizeType(),
5833 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5834 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5835 CGM.getContext().getSizeType(), Loc);
5836 }
5837 RCG.emitAggregateType(CGF, N, Size);
5838 // Emit the finalizer body:
5839 // <destroy>(<type>* %0)
5840 RCG.emitCleanups(CGF, N, PrivateAddr);
5841 CGF.FinishFunction(Loc);
5842 return Fn;
5843 }
5844
5845 llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5846 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5847 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5848 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5849 return nullptr;
5850
5851 // Build typedef struct:
5852 // kmp_taskred_input {
5853 // void *reduce_shar; // shared reduction item
5854 // void *reduce_orig; // original reduction item used for initialization
5855 // size_t reduce_size; // size of data item
5856 // void *reduce_init; // data initialization routine
5857 // void *reduce_fini; // data finalization routine
5858 // void *reduce_comb; // data combiner routine
5859 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5860 // } kmp_taskred_input_t;
5861 ASTContext &C = CGM.getContext();
5862 RecordDecl *RD = C.buildImplicitRecord("kmp_taskred_input_t");
5863 RD->startDefinition();
5864 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5865 const FieldDecl *OrigFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5866 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5867 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5868 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5869 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5870 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5871 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5872 RD->completeDefinition();
5873 CanQualType RDType = C.getCanonicalTagType(RD);
5874 unsigned Size = Data.ReductionVars.size();
5875 llvm::APInt ArraySize(/*numBits=*/64, Size);
5876 QualType ArrayRDType =
5877 C.getConstantArrayType(RDType, ArraySize, nullptr,
5878 ArraySizeModifier::Normal, /*IndexTypeQuals=*/0);
5879 // kmp_task_red_input_t .rd_input.[Size];
5880 RawAddress TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5881 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionOrigs,
5882 Data.ReductionCopies, Data.ReductionOps);
5883 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5884 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5885 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5886 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5887 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5888 TaskRedInput.getElementType(), TaskRedInput.getPointer(), Idxs,
5889 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5890 ".rd_input.gep.");
5891 LValue ElemLVal = CGF.MakeNaturalAlignRawAddrLValue(GEP, RDType);
5892 // ElemLVal.reduce_shar = &Shareds[Cnt];
5893 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5894 RCG.emitSharedOrigLValue(CGF, Cnt);
5895 llvm::Value *Shared = RCG.getSharedLValue(Cnt).getPointer(CGF);
5896 CGF.EmitStoreOfScalar(Shared, SharedLVal);
5897 // ElemLVal.reduce_orig = &Origs[Cnt];
5898 LValue OrigLVal = CGF.EmitLValueForField(ElemLVal, OrigFD);
5899 llvm::Value *Orig = RCG.getOrigLValue(Cnt).getPointer(CGF);
5900 CGF.EmitStoreOfScalar(Orig, OrigLVal);
5901 RCG.emitAggregateType(CGF, Cnt);
5902 llvm::Value *SizeValInChars;
5903 llvm::Value *SizeVal;
5904 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5905 // We use delayed creation/initialization for VLAs and array sections. It is
5906 // required because runtime does not provide the way to pass the sizes of
5907 // VLAs/array sections to initializer/combiner/finalizer functions. Instead
5908 // threadprivate global variables are used to store these values and use
5909 // them in the functions.
5910 bool DelayedCreation = !!SizeVal;
5911 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5912 /*isSigned=*/false);
5913 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5914 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5915 // ElemLVal.reduce_init = init;
5916 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5917 llvm::Value *InitAddr = emitReduceInitFunction(CGM, Loc, RCG, Cnt);
5918 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5919 // ElemLVal.reduce_fini = fini;
5920 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5921 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5922 llvm::Value *FiniAddr =
5923 Fini ? Fini : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5924 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5925 // ElemLVal.reduce_comb = comb;
5926 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5927 llvm::Value *CombAddr = emitReduceCombFunction(
5928 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5929 RHSExprs[Cnt], Data.ReductionCopies[Cnt]);
5930 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5931 // ElemLVal.flags = 0;
5932 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5933 if (DelayedCreation) {
5934 CGF.EmitStoreOfScalar(
5935 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*isSigned=*/true),
5936 FlagsLVal);
5937 } else
5938 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5939 }
5940 if (Data.IsReductionWithTaskMod) {
5941 // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int
5942 // is_ws, int num, void *data);
5943 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc);
5944 llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc),
5945 CGM.IntTy, /*isSigned=*/true);
5946 llvm::Value *Args[] = {
5947 IdentTLoc, GTid,
5948 llvm::ConstantInt::get(CGM.IntTy, Data.IsWorksharingReduction ? 1 : 0,
5949 /*isSigned=*/true),
5950 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5951 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5952 TaskRedInput.getPointer(), CGM.VoidPtrTy)};
5953 return CGF.EmitRuntimeCall(
5954 OMPBuilder.getOrCreateRuntimeFunction(
5955 CGM.getModule(), OMPRTL___kmpc_taskred_modifier_init),
5956 Args);
5957 }
5958 // Build call void *__kmpc_taskred_init(int gtid, int num_data, void *data);
5959 llvm::Value *Args[] = {
5960 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5961 /*isSigned=*/true),
5962 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5963 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5964 CGM.VoidPtrTy)};
5965 return CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
5966 CGM.getModule(), OMPRTL___kmpc_taskred_init),
5967 Args);
5968 }
5969
5970 void CGOpenMPRuntime::emitTaskReductionFini(CodeGenFunction &CGF,
5971 SourceLocation Loc,
5972 bool IsWorksharingReduction) {
5973 // Build call void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int
5974 // is_ws, int num, void *data);
5975 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc);
5976 llvm::Value *GTid = CGF.Builder.CreateIntCast(getThreadID(CGF, Loc),
5977 CGM.IntTy, /*isSigned=*/true);
5978 llvm::Value *Args[] = {IdentTLoc, GTid,
5979 llvm::ConstantInt::get(CGM.IntTy,
5980 IsWorksharingReduction ? 1 : 0,
5981 /*isSigned=*/true)};
5982 (void)CGF.EmitRuntimeCall(
5983 OMPBuilder.getOrCreateRuntimeFunction(
5984 CGM.getModule(), OMPRTL___kmpc_task_reduction_modifier_fini),
5985 Args);
5986 }
5987
5988 void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5989 SourceLocation Loc,
5990 ReductionCodeGen &RCG,
5991 unsigned N) {
5992 auto Sizes = RCG.getSizes(N);
5993 // Emit threadprivate global variable if the type is non-constant
5994 // (Sizes.second = nullptr).
5995 if (Sizes.second) {
5996 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5997 /*isSigned=*/false);
5998 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5999 CGF, CGM.getContext().getSizeType(),
6000 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
6001 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6002 }
6003 }
6004
6005 Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6006 SourceLocation Loc,
6007 llvm::Value *ReductionsPtr,
6008 LValue SharedLVal) {
6009 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6010 // *d);
6011 llvm::Value *Args[] = {CGF.Builder.CreateIntCast(getThreadID(CGF, Loc),
6012 CGM.IntTy,
6013 /*isSigned=*/true),
6014 ReductionsPtr,
6015 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6016 SharedLVal.getPointer(CGF), CGM.VoidPtrTy)};
6017 return Address(
6018 CGF.EmitRuntimeCall(
6019 OMPBuilder.getOrCreateRuntimeFunction(
6020 CGM.getModule(), OMPRTL___kmpc_task_reduction_get_th_data),
6021 Args),
6022 CGF.Int8Ty, SharedLVal.getAlignment());
6023 }
6024
6025 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc,
6026 const OMPTaskDataTy &Data) {
6027 if (!CGF.HaveInsertPoint())
6028 return;
6029
6030 if (CGF.CGM.getLangOpts().OpenMPIRBuilder && Data.Dependences.empty()) {
6031 // TODO: Need to support taskwait with dependences in the OpenMPIRBuilder.
6032 OMPBuilder.createTaskwait(CGF.Builder);
6033 } else {
6034 llvm::Value *ThreadID = getThreadID(CGF, Loc);
6035 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
6036 auto &M = CGM.getModule();
6037 Address DependenciesArray = Address::invalid();
6038 llvm::Value *NumOfElements;
6039 std::tie(NumOfElements, DependenciesArray) =
6040 emitDependClause(CGF, Data.Dependences, Loc);
6041 if (!Data.Dependences.empty()) {
6042 llvm::Value *DepWaitTaskArgs[7];
6043 DepWaitTaskArgs[0] = UpLoc;
6044 DepWaitTaskArgs[1] = ThreadID;
6045 DepWaitTaskArgs[2] = NumOfElements;
6046 DepWaitTaskArgs[3] = DependenciesArray.emitRawPointer(CGF);
6047 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
6048 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
6049 DepWaitTaskArgs[6] =
6050 llvm::ConstantInt::get(CGF.Int32Ty, Data.HasNowaitClause);
6051
6052 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
6053
6054 // Build void __kmpc_omp_taskwait_deps_51(ident_t *, kmp_int32 gtid,
6055 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
6056 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list,
6057 // kmp_int32 has_no_wait); if dependence info is specified.
6058 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
6059 M, OMPRTL___kmpc_omp_taskwait_deps_51),
6060 DepWaitTaskArgs);
6061
6062 } else {
6063
6064 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6065 // global_tid);
6066 llvm::Value *Args[] = {UpLoc, ThreadID};
6067 // Ignore return result until untied tasks are supported.
6068 CGF.EmitRuntimeCall(
6069 OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_omp_taskwait),
6070 Args);
6071 }
6072 }
6073
6074 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6075 Region->emitUntiedSwitch(CGF);
6076 }
6077
6078 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
6079 OpenMPDirectiveKind InnerKind,
6080 const RegionCodeGenTy &CodeGen,
6081 bool HasCancel) {
6082 if (!CGF.HaveInsertPoint())
6083 return;
6084 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel,
6085 InnerKind != OMPD_critical &&
6086 InnerKind != OMPD_master &&
6087 InnerKind != OMPD_masked);
6088 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
6089 }
6090
6091 namespace {
6092 enum RTCancelKind {
6093 CancelNoreq = 0,
6094 CancelParallel = 1,
6095 CancelLoop = 2,
6096 CancelSections = 3,
6097 CancelTaskgroup = 4
6098 };
6099 } // anonymous namespace
6100
6101 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6102 RTCancelKind CancelKind = CancelNoreq;
6103 if (CancelRegion == OMPD_parallel)
6104 CancelKind = CancelParallel;
6105 else if (CancelRegion == OMPD_for)
6106 CancelKind = CancelLoop;
6107 else if (CancelRegion == OMPD_sections)
6108 CancelKind = CancelSections;
6109 else {
6110 assert(CancelRegion == OMPD_taskgroup);
6111 CancelKind = CancelTaskgroup;
6112 }
6113 return CancelKind;
6114 }
6115
6116 void CGOpenMPRuntime::emitCancellationPointCall(
6117 CodeGenFunction &CGF, SourceLocation Loc,
6118 OpenMPDirectiveKind CancelRegion) {
6119 if (!CGF.HaveInsertPoint())
6120 return;
6121 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6122 // global_tid, kmp_int32 cncl_kind);
6123 if (auto *OMPRegionInfo =
6124 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
6125 // For 'cancellation point taskgroup', the task region info may not have a
6126 // cancel. This may instead happen in another adjacent task.
6127 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
6128 llvm::Value *Args[] = {
6129 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6130 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6131 // Ignore return result until untied tasks are supported.
6132 llvm::Value *Result = CGF.EmitRuntimeCall(
6133 OMPBuilder.getOrCreateRuntimeFunction(
6134 CGM.getModule(), OMPRTL___kmpc_cancellationpoint),
6135 Args);
6136 // if (__kmpc_cancellationpoint()) {
6137 // call i32 @__kmpc_cancel_barrier( // for parallel cancellation only
6138 // exit from construct;
6139 // }
6140 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6141 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6142 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
6143 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6144 CGF.EmitBlock(ExitBB);
6145 if (CancelRegion == OMPD_parallel)
6146 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
6147 // exit from construct;
6148 CodeGenFunction::JumpDest CancelDest =
6149 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6150 CGF.EmitBranchThroughCleanup(CancelDest);
6151 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6152 }
6153 }
6154 }
6155
6156 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
6157 const Expr *IfCond,
6158 OpenMPDirectiveKind CancelRegion) {
6159 if (!CGF.HaveInsertPoint())
6160 return;
6161 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6162 // kmp_int32 cncl_kind);
6163 auto &M = CGM.getModule();
6164 if (auto *OMPRegionInfo =
6165 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
6166 auto &&ThenGen = [this, &M, Loc, CancelRegion,
6167 OMPRegionInfo](CodeGenFunction &CGF, PrePostActionTy &) {
6168 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
6169 llvm::Value *Args[] = {
6170 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
6171 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6172 // Ignore return result until untied tasks are supported.
6173 llvm::Value *Result = CGF.EmitRuntimeCall(
6174 OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_cancel), Args);
6175 // if (__kmpc_cancel()) {
6176 // call i32 @__kmpc_cancel_barrier( // for parallel cancellation only
6177 // exit from construct;
6178 // }
6179 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6180 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6181 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
6182 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6183 CGF.EmitBlock(ExitBB);
6184 if (CancelRegion == OMPD_parallel)
6185 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
6186 // exit from construct;
6187 CodeGenFunction::JumpDest CancelDest =
6188 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6189 CGF.EmitBranchThroughCleanup(CancelDest);
6190 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6191 };
6192 if (IfCond) {
6193 emitIfClause(CGF, IfCond, ThenGen,
6194 [](CodeGenFunction &, PrePostActionTy &) {});
6195 } else {
6196 RegionCodeGenTy ThenRCG(ThenGen);
6197 ThenRCG(CGF);
6198 }
6199 }
6200 }
6201
6202 namespace {
6203 /// Cleanup action for uses_allocators support.
6204 class OMPUsesAllocatorsActionTy final : public PrePostActionTy {
6205 ArrayRef<std::pair<const Expr *, const Expr *>> Allocators;
6206
6207 public:
6208 OMPUsesAllocatorsActionTy(
6209 ArrayRef<std::pair<const Expr *, const Expr *>> Allocators)
6210 : Allocators(Allocators) {}
6211 void Enter(CodeGenFunction &CGF) override {
6212 if (!CGF.HaveInsertPoint())
6213 return;
6214 for (const auto &AllocatorData : Allocators) {
6215 CGF.CGM.getOpenMPRuntime().emitUsesAllocatorsInit(
6216 CGF, AllocatorData.first, AllocatorData.second);
6217 }
6218 }
6219 void Exit(CodeGenFunction &CGF) override {
6220 if (!CGF.HaveInsertPoint())
6221 return;
6222 for (const auto &AllocatorData : Allocators) {
6223 CGF.CGM.getOpenMPRuntime().emitUsesAllocatorsFini(CGF,
6224 AllocatorData.first);
6225 }
6226 }
6227 };
6228 } // namespace
6229
6230 void CGOpenMPRuntime::emitTargetOutlinedFunction(
6231 const OMPExecutableDirective &D, StringRef ParentName,
6232 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6233 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
6234 assert(!ParentName.empty() && "Invalid target entry parent name!");
6235 HasEmittedTargetRegion = true;
6236 SmallVector<std::pair<const Expr *, const Expr *>, 4> Allocators;
6237 for (const auto *C : D.getClausesOfKind<OMPUsesAllocatorsClause>()) {
6238 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6239 const OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
6240 if (!D.AllocatorTraits)
6241 continue;
6242 Allocators.emplace_back(D.Allocator, D.AllocatorTraits);
6243 }
6244 }
6245 OMPUsesAllocatorsActionTy UsesAllocatorAction(Allocators);
6246 CodeGen.setAction(UsesAllocatorAction);
6247 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6248 IsOffloadEntry, CodeGen);
6249 }
6250
6251 void CGOpenMPRuntime::emitUsesAllocatorsInit(CodeGenFunction &CGF,
6252 const Expr *Allocator,
6253 const Expr *AllocatorTraits) {
6254 llvm::Value *ThreadId = getThreadID(CGF, Allocator->getExprLoc());
6255 ThreadId = CGF.Builder.CreateIntCast(ThreadId, CGF.IntTy, /*isSigned=*/true);
6256 // Use default memspace handle.
6257 llvm::Value *MemSpaceHandle = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
6258 llvm::Value *NumTraits = llvm::ConstantInt::get(
6259 CGF.IntTy, cast<ConstantArrayType>(
6260 AllocatorTraits->getType()->getAsArrayTypeUnsafe())
6261 ->getSize()
6262 .getLimitedValue());
6263 LValue AllocatorTraitsLVal = CGF.EmitLValue(AllocatorTraits);
6264 Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6265 AllocatorTraitsLVal.getAddress(), CGF.VoidPtrPtrTy, CGF.VoidPtrTy);
6266 AllocatorTraitsLVal = CGF.MakeAddrLValue(Addr, CGF.getContext().VoidPtrTy,
6267 AllocatorTraitsLVal.getBaseInfo(),
6268 AllocatorTraitsLVal.getTBAAInfo());
6269 llvm::Value *Traits = Addr.emitRawPointer(CGF);
6270
6271 llvm::Value *AllocatorVal =
6272 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
6273 CGM.getModule(), OMPRTL___kmpc_init_allocator),
6274 {ThreadId, MemSpaceHandle, NumTraits, Traits});
6275 // Store to allocator.
6276 CGF.EmitAutoVarAlloca(*cast<VarDecl>(
6277 cast<DeclRefExpr>(Allocator->IgnoreParenImpCasts())->getDecl()));
6278 LValue AllocatorLVal = CGF.EmitLValue(Allocator->IgnoreParenImpCasts());
6279 AllocatorVal =
6280 CGF.EmitScalarConversion(AllocatorVal, CGF.getContext().VoidPtrTy,
6281 Allocator->getType(), Allocator->getExprLoc());
6282 CGF.EmitStoreOfScalar(AllocatorVal, AllocatorLVal);
6283 }
6284
6285 void CGOpenMPRuntime::emitUsesAllocatorsFini(CodeGenFunction &CGF,
6286 const Expr *Allocator) {
6287 llvm::Value *ThreadId = getThreadID(CGF, Allocator->getExprLoc());
6288 ThreadId = CGF.Builder.CreateIntCast(ThreadId, CGF.IntTy, /*isSigned=*/true);
6289 LValue AllocatorLVal = CGF.EmitLValue(Allocator->IgnoreParenImpCasts());
6290 llvm::Value *AllocatorVal =
6291 CGF.EmitLoadOfScalar(AllocatorLVal, Allocator->getExprLoc());
6292 AllocatorVal = CGF.EmitScalarConversion(AllocatorVal, Allocator->getType(),
6293 CGF.getContext().VoidPtrTy,
6294 Allocator->getExprLoc());
6295 (void)CGF.EmitRuntimeCall(
6296 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
6297 OMPRTL___kmpc_destroy_allocator),
6298 {ThreadId, AllocatorVal});
6299 }
6300
6301 void CGOpenMPRuntime::computeMinAndMaxThreadsAndTeams(
6302 const OMPExecutableDirective &D, CodeGenFunction &CGF,
6303 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &Attrs) {
6304 assert(Attrs.MaxTeams.size() == 1 && Attrs.MaxThreads.size() == 1 &&
6305 "invalid default attrs structure");
6306 int32_t &MaxTeamsVal = Attrs.MaxTeams.front();
6307 int32_t &MaxThreadsVal = Attrs.MaxThreads.front();
6308
6309 getNumTeamsExprForTargetDirective(CGF, D, Attrs.MinTeams, MaxTeamsVal);
6310 getNumThreadsExprForTargetDirective(CGF, D, MaxThreadsVal,
6311 /*UpperBoundOnly=*/true);
6312
6313 for (auto *C : D.getClausesOfKind<OMPXAttributeClause>()) {
6314 for (auto *A : C->getAttrs()) {
6315 int32_t AttrMinThreadsVal = 1, AttrMaxThreadsVal = -1;
6316 int32_t AttrMinBlocksVal = 1, AttrMaxBlocksVal = -1;
6317 if (auto *Attr = dyn_cast<CUDALaunchBoundsAttr>(A))
6318 CGM.handleCUDALaunchBoundsAttr(nullptr, Attr, &AttrMaxThreadsVal,
6319 &AttrMinBlocksVal, &AttrMaxBlocksVal);
6320 else if (auto *Attr = dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(A))
6321 CGM.handleAMDGPUFlatWorkGroupSizeAttr(
6322 nullptr, Attr, /*ReqdWGS=*/nullptr, &AttrMinThreadsVal,
6323 &AttrMaxThreadsVal);
6324 else
6325 continue;
6326
6327 Attrs.MinThreads = std::max(Attrs.MinThreads, AttrMinThreadsVal);
6328 if (AttrMaxThreadsVal > 0)
6329 MaxThreadsVal = MaxThreadsVal > 0
6330 ? std::min(MaxThreadsVal, AttrMaxThreadsVal)
6331 : AttrMaxThreadsVal;
6332 Attrs.MinTeams = std::max(Attrs.MinTeams, AttrMinBlocksVal);
6333 if (AttrMaxBlocksVal > 0)
6334 MaxTeamsVal = MaxTeamsVal > 0 ? std::min(MaxTeamsVal, AttrMaxBlocksVal)
6335 : AttrMaxBlocksVal;
6336 }
6337 }
6338 }
6339
6340 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6341 const OMPExecutableDirective &D, StringRef ParentName,
6342 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6343 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
6344
6345 llvm::TargetRegionEntryInfo EntryInfo =
6346 getEntryInfoFromPresumedLoc(CGM, OMPBuilder, D.getBeginLoc(), ParentName);
6347
6348 CodeGenFunction CGF(CGM, true);
6349 llvm::OpenMPIRBuilder::FunctionGenCallback &&GenerateOutlinedFunction =
6350 [&CGF, &D, &CodeGen](StringRef EntryFnName) {
6351 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
6352
6353 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
6354 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6355 return CGF.GenerateOpenMPCapturedStmtFunction(CS, D);
6356 };
6357
6358 cantFail(OMPBuilder.emitTargetRegionFunction(
6359 EntryInfo, GenerateOutlinedFunction, IsOffloadEntry, OutlinedFn,
6360 OutlinedFnID));
6361
6362 if (!OutlinedFn)
6363 return;
6364
6365 CGM.getTargetCodeGenInfo().setTargetAttributes(nullptr, OutlinedFn, CGM);
6366
6367 for (auto *C : D.getClausesOfKind<OMPXAttributeClause>()) {
6368 for (auto *A : C->getAttrs()) {
6369 if (auto *Attr = dyn_cast<AMDGPUWavesPerEUAttr>(A))
6370 CGM.handleAMDGPUWavesPerEUAttr(OutlinedFn, Attr);
6371 }
6372 }
6373 registerVTable(D);
6374 }
6375
6376 /// Checks if the expression is constant or does not have non-trivial function
6377 /// calls.
6378 static bool isTrivial(ASTContext &Ctx, const Expr * E) {
6379 // We can skip constant expressions.
6380 // We can skip expressions with trivial calls or simple expressions.
6381 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
6382 !E->hasNonTrivialCall(Ctx)) &&
6383 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
6384 }
6385
6386 const Stmt *CGOpenMPRuntime::getSingleCompoundChild(ASTContext &Ctx,
6387 const Stmt *Body) {
6388 const Stmt *Child = Body->IgnoreContainers();
6389 while (const auto *C = dyn_cast_or_null<CompoundStmt>(Child)) {
6390 Child = nullptr;
6391 for (const Stmt *S : C->body()) {
6392 if (const auto *E = dyn_cast<Expr>(S)) {
6393 if (isTrivial(Ctx, E))
6394 continue;
6395 }
6396 // Some of the statements can be ignored.
6397 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
6398 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
6399 continue;
6400 // Analyze declarations.
6401 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
6402 if (llvm::all_of(DS->decls(), [](const Decl *D) {
6403 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
6404 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
6405 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
6406 isa<UsingDirectiveDecl>(D) ||
6407 isa<OMPDeclareReductionDecl>(D) ||
6408 isa<OMPThreadPrivateDecl>(D) || isa<OMPAllocateDecl>(D))
6409 return true;
6410 const auto *VD = dyn_cast<VarDecl>(D);
6411 if (!VD)
6412 return false;
6413 return VD->hasGlobalStorage() || !VD->isUsed();
6414 }))
6415 continue;
6416 }
6417 // Found multiple children - cannot get the one child only.
6418 if (Child)
6419 return nullptr;
6420 Child = S;
6421 }
6422 if (Child)
6423 Child = Child->IgnoreContainers();
6424 }
6425 return Child;
6426 }
6427
6428 const Expr *CGOpenMPRuntime::getNumTeamsExprForTargetDirective(
6429 CodeGenFunction &CGF, const OMPExecutableDirective &D, int32_t &MinTeamsVal,
6430 int32_t &MaxTeamsVal) {
6431
6432 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
6433 assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
6434 "Expected target-based executable directive.");
6435 switch (DirectiveKind) {
6436 case OMPD_target: {
6437 const auto *CS = D.getInnermostCapturedStmt();
6438 const auto *Body =
6439 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
6440 const Stmt *ChildStmt =
6441 CGOpenMPRuntime::getSingleCompoundChild(CGF.getContext(), Body);
6442 if (const auto *NestedDir =
6443 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
6444 if (isOpenMPTeamsDirective(NestedDir->getDirectiveKind())) {
6445 if (NestedDir->hasClausesOfKind<OMPNumTeamsClause>()) {
6446 const Expr *NumTeams = NestedDir->getSingleClause<OMPNumTeamsClause>()
6447 ->getNumTeams()
6448 .front();
6449 if (NumTeams->isIntegerConstantExpr(CGF.getContext()))
6450 if (auto Constant =
6451 NumTeams->getIntegerConstantExpr(CGF.getContext()))
6452 MinTeamsVal = MaxTeamsVal = Constant->getExtValue();
6453 return NumTeams;
6454 }
6455 MinTeamsVal = MaxTeamsVal = 0;
6456 return nullptr;
6457 }
6458 MinTeamsVal = MaxTeamsVal = 1;
6459 return nullptr;
6460 }
6461 // A value of -1 is used to check if we need to emit no teams region
6462 MinTeamsVal = MaxTeamsVal = -1;
6463 return nullptr;
6464 }
6465 case OMPD_target_teams_loop:
6466 case OMPD_target_teams:
6467 case OMPD_target_teams_distribute:
6468 case OMPD_target_teams_distribute_simd:
6469 case OMPD_target_teams_distribute_parallel_for:
6470 case OMPD_target_teams_distribute_parallel_for_simd: {
6471 if (D.hasClausesOfKind<OMPNumTeamsClause>()) {
6472 const Expr *NumTeams =
6473 D.getSingleClause<OMPNumTeamsClause>()->getNumTeams().front();
6474 if (NumTeams->isIntegerConstantExpr(CGF.getContext()))
6475 if (auto Constant = NumTeams->getIntegerConstantExpr(CGF.getContext()))
6476 MinTeamsVal = MaxTeamsVal = Constant->getExtValue();
6477 return NumTeams;
6478 }
6479 MinTeamsVal = MaxTeamsVal = 0;
6480 return nullptr;
6481 }
6482 case OMPD_target_parallel:
6483 case OMPD_target_parallel_for:
6484 case OMPD_target_parallel_for_simd:
6485 case OMPD_target_parallel_loop:
6486 case OMPD_target_simd:
6487 MinTeamsVal = MaxTeamsVal = 1;
6488 return nullptr;
6489 case OMPD_parallel:
6490 case OMPD_for:
6491 case OMPD_parallel_for:
6492 case OMPD_parallel_loop:
6493 case OMPD_parallel_master:
6494 case OMPD_parallel_sections:
6495 case OMPD_for_simd:
6496 case OMPD_parallel_for_simd:
6497 case OMPD_cancel:
6498 case OMPD_cancellation_point:
6499 case OMPD_ordered:
6500 case OMPD_threadprivate:
6501 case OMPD_allocate:
6502 case OMPD_task:
6503 case OMPD_simd:
6504 case OMPD_tile:
6505 case OMPD_unroll:
6506 case OMPD_sections:
6507 case OMPD_section:
6508 case OMPD_single:
6509 case OMPD_master:
6510 case OMPD_critical:
6511 case OMPD_taskyield:
6512 case OMPD_barrier:
6513 case OMPD_taskwait:
6514 case OMPD_taskgroup:
6515 case OMPD_atomic:
6516 case OMPD_flush:
6517 case OMPD_depobj:
6518 case OMPD_scan:
6519 case OMPD_teams:
6520 case OMPD_target_data:
6521 case OMPD_target_exit_data:
6522 case OMPD_target_enter_data:
6523 case OMPD_distribute:
6524 case OMPD_distribute_simd:
6525 case OMPD_distribute_parallel_for:
6526 case OMPD_distribute_parallel_for_simd:
6527 case OMPD_teams_distribute:
6528 case OMPD_teams_distribute_simd:
6529 case OMPD_teams_distribute_parallel_for:
6530 case OMPD_teams_distribute_parallel_for_simd:
6531 case OMPD_target_update:
6532 case OMPD_declare_simd:
6533 case OMPD_declare_variant:
6534 case OMPD_begin_declare_variant:
6535 case OMPD_end_declare_variant:
6536 case OMPD_declare_target:
6537 case OMPD_end_declare_target:
6538 case OMPD_declare_reduction:
6539 case OMPD_declare_mapper:
6540 case OMPD_taskloop:
6541 case OMPD_taskloop_simd:
6542 case OMPD_master_taskloop:
6543 case OMPD_master_taskloop_simd:
6544 case OMPD_parallel_master_taskloop:
6545 case OMPD_parallel_master_taskloop_simd:
6546 case OMPD_requires:
6547 case OMPD_metadirective:
6548 case OMPD_unknown:
6549 break;
6550 default:
6551 break;
6552 }
6553 llvm_unreachable("Unexpected directive kind.");
6554 }
6555
6556 llvm::Value *CGOpenMPRuntime::emitNumTeamsForTargetDirective(
6557 CodeGenFunction &CGF, const OMPExecutableDirective &D) {
6558 assert(!CGF.getLangOpts().OpenMPIsTargetDevice &&
6559 "Clauses associated with the teams directive expected to be emitted "
6560 "only for the host!");
6561 CGBuilderTy &Bld = CGF.Builder;
6562 int32_t MinNT = -1, MaxNT = -1;
6563 const Expr *NumTeams =
6564 getNumTeamsExprForTargetDirective(CGF, D, MinNT, MaxNT);
6565 if (NumTeams != nullptr) {
6566 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
6567
6568 switch (DirectiveKind) {
6569 case OMPD_target: {
6570 const auto *CS = D.getInnermostCapturedStmt();
6571 CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
6572 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6573 llvm::Value *NumTeamsVal = CGF.EmitScalarExpr(NumTeams,
6574 /*IgnoreResultAssign*/ true);
6575 return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
6576 /*isSigned=*/true);
6577 }
6578 case OMPD_target_teams:
6579 case OMPD_target_teams_distribute:
6580 case OMPD_target_teams_distribute_simd:
6581 case OMPD_target_teams_distribute_parallel_for:
6582 case OMPD_target_teams_distribute_parallel_for_simd: {
6583 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
6584 llvm::Value *NumTeamsVal = CGF.EmitScalarExpr(NumTeams,
6585 /*IgnoreResultAssign*/ true);
6586 return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
6587 /*isSigned=*/true);
6588 }
6589 default:
6590 break;
6591 }
6592 }
6593
6594 assert(MinNT == MaxNT && "Num threads ranges require handling here.");
6595 return llvm::ConstantInt::getSigned(CGF.Int32Ty, MinNT);
6596 }
6597
6598 /// Check for a num threads constant value (stored in \p DefaultVal), or
6599 /// expression (stored in \p E). If the value is conditional (via an if-clause),
6600 /// store the condition in \p CondVal. If \p E, and \p CondVal respectively, are
6601 /// nullptr, no expression evaluation is perfomed.
6602 static void getNumThreads(CodeGenFunction &CGF, const CapturedStmt *CS,
6603 const Expr **E, int32_t &UpperBound,
6604 bool UpperBoundOnly, llvm::Value **CondVal) {
6605 const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
6606 CGF.getContext(), CS->getCapturedStmt());
6607 const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child);
6608 if (!Dir)
6609 return;
6610
6611 if (isOpenMPParallelDirective(Dir->getDirectiveKind())) {
6612 // Handle if clause. If if clause present, the number of threads is
6613 // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
6614 if (CondVal && Dir->hasClausesOfKind<OMPIfClause>()) {
6615 CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
6616 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6617 const OMPIfClause *IfClause = nullptr;
6618 for (const auto *C : Dir->getClausesOfKind<OMPIfClause>()) {
6619 if (C->getNameModifier() == OMPD_unknown ||
6620 C->getNameModifier() == OMPD_parallel) {
6621 IfClause = C;
6622 break;
6623 }
6624 }
6625 if (IfClause) {
6626 const Expr *CondExpr = IfClause->getCondition();
6627 bool Result;
6628 if (CondExpr->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
6629 if (!Result) {
6630 UpperBound = 1;
6631 return;
6632 }
6633 } else {
6634 CodeGenFunction::LexicalScope Scope(CGF, CondExpr->getSourceRange());
6635 if (const auto *PreInit =
6636 cast_or_null<DeclStmt>(IfClause->getPreInitStmt())) {
6637 for (const auto *I : PreInit->decls()) {
6638 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
6639 CGF.EmitVarDecl(cast<VarDecl>(*I));
6640 } else {
6641 CodeGenFunction::AutoVarEmission Emission =
6642 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
6643 CGF.EmitAutoVarCleanups(Emission);
6644 }
6645 }
6646 *CondVal = CGF.EvaluateExprAsBool(CondExpr);
6647 }
6648 }
6649 }
6650 }
6651 // Check the value of num_threads clause iff if clause was not specified
6652 // or is not evaluated to false.
6653 if (Dir->hasClausesOfKind<OMPNumThreadsClause>()) {
6654 CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
6655 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6656 const auto *NumThreadsClause =
6657 Dir->getSingleClause<OMPNumThreadsClause>();
6658 const Expr *NTExpr = NumThreadsClause->getNumThreads();
6659 if (NTExpr->isIntegerConstantExpr(CGF.getContext()))
6660 if (auto Constant = NTExpr->getIntegerConstantExpr(CGF.getContext()))
6661 UpperBound =
6662 UpperBound
6663 ? Constant->getZExtValue()
6664 : std::min(UpperBound,
6665 static_cast<int32_t>(Constant->getZExtValue()));
6666 // If we haven't found a upper bound, remember we saw a thread limiting
6667 // clause.
6668 if (UpperBound == -1)
6669 UpperBound = 0;
6670 if (!E)
6671 return;
6672 CodeGenFunction::LexicalScope Scope(CGF, NTExpr->getSourceRange());
6673 if (const auto *PreInit =
6674 cast_or_null<DeclStmt>(NumThreadsClause->getPreInitStmt())) {
6675 for (const auto *I : PreInit->decls()) {
6676 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
6677 CGF.EmitVarDecl(cast<VarDecl>(*I));
6678 } else {
6679 CodeGenFunction::AutoVarEmission Emission =
6680 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
6681 CGF.EmitAutoVarCleanups(Emission);
6682 }
6683 }
6684 }
6685 *E = NTExpr;
6686 }
6687 return;
6688 }
6689 if (isOpenMPSimdDirective(Dir->getDirectiveKind()))
6690 UpperBound = 1;
6691 }
6692
6693 const Expr *CGOpenMPRuntime::getNumThreadsExprForTargetDirective(
6694 CodeGenFunction &CGF, const OMPExecutableDirective &D, int32_t &UpperBound,
6695 bool UpperBoundOnly, llvm::Value **CondVal, const Expr **ThreadLimitExpr) {
6696 assert((!CGF.getLangOpts().OpenMPIsTargetDevice || UpperBoundOnly) &&
6697 "Clauses associated with the teams directive expected to be emitted "
6698 "only for the host!");
6699 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
6700 assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
6701 "Expected target-based executable directive.");
6702
6703 const Expr *NT = nullptr;
6704 const Expr **NTPtr = UpperBoundOnly ? nullptr : &NT;
6705
6706 auto CheckForConstExpr = [&](const Expr *E, const Expr **EPtr) {
6707 if (E->isIntegerConstantExpr(CGF.getContext())) {
6708 if (auto Constant = E->getIntegerConstantExpr(CGF.getContext()))
6709 UpperBound = UpperBound ? Constant->getZExtValue()
6710 : std::min(UpperBound,
6711 int32_t(Constant->getZExtValue()));
6712 }
6713 // If we haven't found a upper bound, remember we saw a thread limiting
6714 // clause.
6715 if (UpperBound == -1)
6716 UpperBound = 0;
6717 if (EPtr)
6718 *EPtr = E;
6719 };
6720
6721 auto ReturnSequential = [&]() {
6722 UpperBound = 1;
6723 return NT;
6724 };
6725
6726 switch (DirectiveKind) {
6727 case OMPD_target: {
6728 const CapturedStmt *CS = D.getInnermostCapturedStmt();
6729 getNumThreads(CGF, CS, NTPtr, UpperBound, UpperBoundOnly, CondVal);
6730 const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
6731 CGF.getContext(), CS->getCapturedStmt());
6732 // TODO: The standard is not clear how to resolve two thread limit clauses,
6733 // let's pick the teams one if it's present, otherwise the target one.
6734 const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
6735 if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
6736 if (const auto *TLC = Dir->getSingleClause<OMPThreadLimitClause>()) {
6737 ThreadLimitClause = TLC;
6738 if (ThreadLimitExpr) {
6739 CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
6740 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6741 CodeGenFunction::LexicalScope Scope(
6742 CGF,
6743 ThreadLimitClause->getThreadLimit().front()->getSourceRange());
6744 if (const auto *PreInit =
6745 cast_or_null<DeclStmt>(ThreadLimitClause->getPreInitStmt())) {
6746 for (const auto *I : PreInit->decls()) {
6747 if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
6748 CGF.EmitVarDecl(cast<VarDecl>(*I));
6749 } else {
6750 CodeGenFunction::AutoVarEmission Emission =
6751 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
6752 CGF.EmitAutoVarCleanups(Emission);
6753 }
6754 }
6755 }
6756 }
6757 }
6758 }
6759 if (ThreadLimitClause)
6760 CheckForConstExpr(ThreadLimitClause->getThreadLimit().front(),
6761 ThreadLimitExpr);
6762 if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
6763 if (isOpenMPTeamsDirective(Dir->getDirectiveKind()) &&
6764 !isOpenMPDistributeDirective(Dir->getDirectiveKind())) {
6765 CS = Dir->getInnermostCapturedStmt();
6766 const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
6767 CGF.getContext(), CS->getCapturedStmt());
6768 Dir = dyn_cast_or_null<OMPExecutableDirective>(Child);
6769 }
6770 if (Dir && isOpenMPParallelDirective(Dir->getDirectiveKind())) {
6771 CS = Dir->getInnermostCapturedStmt();
6772 getNumThreads(CGF, CS, NTPtr, UpperBound, UpperBoundOnly, CondVal);
6773 } else if (Dir && isOpenMPSimdDirective(Dir->getDirectiveKind()))
6774 return ReturnSequential();
6775 }
6776 return NT;
6777 }
6778 case OMPD_target_teams: {
6779 if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
6780 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6781 const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
6782 CheckForConstExpr(ThreadLimitClause->getThreadLimit().front(),
6783 ThreadLimitExpr);
6784 }
6785 const CapturedStmt *CS = D.getInnermostCapturedStmt();
6786 getNumThreads(CGF, CS, NTPtr, UpperBound, UpperBoundOnly, CondVal);
6787 const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
6788 CGF.getContext(), CS->getCapturedStmt());
6789 if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
6790 if (Dir->getDirectiveKind() == OMPD_distribute) {
6791 CS = Dir->getInnermostCapturedStmt();
6792 getNumThreads(CGF, CS, NTPtr, UpperBound, UpperBoundOnly, CondVal);
6793 }
6794 }
6795 return NT;
6796 }
6797 case OMPD_target_teams_distribute:
6798 if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
6799 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6800 const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
6801 CheckForConstExpr(ThreadLimitClause->getThreadLimit().front(),
6802 ThreadLimitExpr);
6803 }
6804 getNumThreads(CGF, D.getInnermostCapturedStmt(), NTPtr, UpperBound,
6805 UpperBoundOnly, CondVal);
6806 return NT;
6807 case OMPD_target_teams_loop:
6808 case OMPD_target_parallel_loop:
6809 case OMPD_target_parallel:
6810 case OMPD_target_parallel_for:
6811 case OMPD_target_parallel_for_simd:
6812 case OMPD_target_teams_distribute_parallel_for:
6813 case OMPD_target_teams_distribute_parallel_for_simd: {
6814 if (CondVal && D.hasClausesOfKind<OMPIfClause>()) {
6815 const OMPIfClause *IfClause = nullptr;
6816 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
6817 if (C->getNameModifier() == OMPD_unknown ||
6818 C->getNameModifier() == OMPD_parallel) {
6819 IfClause = C;
6820 break;
6821 }
6822 }
6823 if (IfClause) {
6824 const Expr *Cond = IfClause->getCondition();
6825 bool Result;
6826 if (Cond->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
6827 if (!Result)
6828 return ReturnSequential();
6829 } else {
6830 CodeGenFunction::RunCleanupsScope Scope(CGF);
6831 *CondVal = CGF.EvaluateExprAsBool(Cond);
6832 }
6833 }
6834 }
6835 if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
6836 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6837 const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
6838 CheckForConstExpr(ThreadLimitClause->getThreadLimit().front(),
6839 ThreadLimitExpr);
6840 }
6841 if (D.hasClausesOfKind<OMPNumThreadsClause>()) {
6842 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6843 const auto *NumThreadsClause = D.getSingleClause<OMPNumThreadsClause>();
6844 CheckForConstExpr(NumThreadsClause->getNumThreads(), nullptr);
6845 return NumThreadsClause->getNumThreads();
6846 }
6847 return NT;
6848 }
6849 case OMPD_target_teams_distribute_simd:
6850 case OMPD_target_simd:
6851 return ReturnSequential();
6852 default:
6853 break;
6854 }
6855 llvm_unreachable("Unsupported directive kind.");
6856 }
6857
6858 llvm::Value *CGOpenMPRuntime::emitNumThreadsForTargetDirective(
6859 CodeGenFunction &CGF, const OMPExecutableDirective &D) {
6860 llvm::Value *NumThreadsVal = nullptr;
6861 llvm::Value *CondVal = nullptr;
6862 llvm::Value *ThreadLimitVal = nullptr;
6863 const Expr *ThreadLimitExpr = nullptr;
6864 int32_t UpperBound = -1;
6865
6866 const Expr *NT = getNumThreadsExprForTargetDirective(
6867 CGF, D, UpperBound, /* UpperBoundOnly */ false, &CondVal,
6868 &ThreadLimitExpr);
6869
6870 // Thread limit expressions are used below, emit them.
6871 if (ThreadLimitExpr) {
6872 ThreadLimitVal =
6873 CGF.EmitScalarExpr(ThreadLimitExpr, /*IgnoreResultAssign=*/true);
6874 ThreadLimitVal = CGF.Builder.CreateIntCast(ThreadLimitVal, CGF.Int32Ty,
6875 /*isSigned=*/false);
6876 }
6877
6878 // Generate the num teams expression.
6879 if (UpperBound == 1) {
6880 NumThreadsVal = CGF.Builder.getInt32(UpperBound);
6881 } else if (NT) {
6882 NumThreadsVal = CGF.EmitScalarExpr(NT, /*IgnoreResultAssign=*/true);
6883 NumThreadsVal = CGF.Builder.CreateIntCast(NumThreadsVal, CGF.Int32Ty,
6884 /*isSigned=*/false);
6885 } else if (ThreadLimitVal) {
6886 // If we do not have a num threads value but a thread limit, replace the
6887 // former with the latter. We know handled the thread limit expression.
6888 NumThreadsVal = ThreadLimitVal;
6889 ThreadLimitVal = nullptr;
6890 } else {
6891 // Default to "0" which means runtime choice.
6892 assert(!ThreadLimitVal && "Default not applicable with thread limit value");
6893 NumThreadsVal = CGF.Builder.getInt32(0);
6894 }
6895
6896 // Handle if clause. If if clause present, the number of threads is
6897 // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
6898 if (CondVal) {
6899 CodeGenFunction::RunCleanupsScope Scope(CGF);
6900 NumThreadsVal = CGF.Builder.CreateSelect(CondVal, NumThreadsVal,
6901 CGF.Builder.getInt32(1));
6902 }
6903
6904 // If the thread limit and num teams expression were present, take the
6905 // minimum.
6906 if (ThreadLimitVal) {
6907 NumThreadsVal = CGF.Builder.CreateSelect(
6908 CGF.Builder.CreateICmpULT(ThreadLimitVal, NumThreadsVal),
6909 ThreadLimitVal, NumThreadsVal);
6910 }
6911
6912 return NumThreadsVal;
6913 }
6914
6915 namespace {
6916 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6917
6918 // Utility to handle information from clauses associated with a given
6919 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6920 // It provides a convenient interface to obtain the information and generate
6921 // code for that information.
6922 class MappableExprsHandler {
6923 public:
6924 /// Custom comparator for attach-pointer expressions that compares them by
6925 /// complexity (i.e. their component-depth) first, then by the order in which
6926 /// they were computed by collectAttachPtrExprInfo(), if they are semantically
6927 /// different.
6928 struct AttachPtrExprComparator {
6929 const MappableExprsHandler &Handler;
6930 // Cache of previous equality comparison results.
6931 mutable llvm::DenseMap<std::pair<const Expr *, const Expr *>, bool>
6932 CachedEqualityComparisons;
6933
6934 AttachPtrExprComparator(const MappableExprsHandler &H) : Handler(H) {}
6935 AttachPtrExprComparator() = delete;
6936
6937 // Return true iff LHS is "less than" RHS.
6938 bool operator()(const Expr *LHS, const Expr *RHS) const {
6939 if (LHS == RHS)
6940 return false;
6941
6942 // First, compare by complexity (depth)
6943 const auto ItLHS = Handler.AttachPtrComponentDepthMap.find(LHS);
6944 const auto ItRHS = Handler.AttachPtrComponentDepthMap.find(RHS);
6945
6946 std::optional<size_t> DepthLHS =
6947 (ItLHS != Handler.AttachPtrComponentDepthMap.end()) ? ItLHS->second
6948 : std::nullopt;
6949 std::optional<size_t> DepthRHS =
6950 (ItRHS != Handler.AttachPtrComponentDepthMap.end()) ? ItRHS->second
6951 : std::nullopt;
6952
6953 // std::nullopt (no attach pointer) has lowest complexity
6954 if (!DepthLHS.has_value() && !DepthRHS.has_value()) {
6955 // Both have same complexity, now check semantic equality
6956 if (areEqual(LHS, RHS))
6957 return false;
6958 // Different semantically, compare by computation order
6959 return wasComputedBefore(LHS, RHS);
6960 }
6961 if (!DepthLHS.has_value())
6962 return true; // LHS has lower complexity
6963 if (!DepthRHS.has_value())
6964 return false; // RHS has lower complexity
6965
6966 // Both have values, compare by depth (lower depth = lower complexity)
6967 if (DepthLHS.value() != DepthRHS.value())
6968 return DepthLHS.value() < DepthRHS.value();
6969
6970 // Same complexity, now check semantic equality
6971 if (areEqual(LHS, RHS))
6972 return false;
6973 // Different semantically, compare by computation order
6974 return wasComputedBefore(LHS, RHS);
6975 }
6976
6977 public:
6978 /// Return true if \p LHS and \p RHS are semantically equal. Uses pre-cached
6979 /// results, if available, otherwise does a recursive semantic comparison.
6980 bool areEqual(const Expr *LHS, const Expr *RHS) const {
6981 // Check cache first for faster lookup
6982 const auto CachedResultIt = CachedEqualityComparisons.find({LHS, RHS});
6983 if (CachedResultIt != CachedEqualityComparisons.end())
6984 return CachedResultIt->second;
6985
6986 bool ComparisonResult = areSemanticallyEqual(LHS, RHS);
6987
6988 // Cache the result for future lookups (both orders since semantic
6989 // equality is commutative)
6990 CachedEqualityComparisons[{LHS, RHS}] = ComparisonResult;
6991 CachedEqualityComparisons[{RHS, LHS}] = ComparisonResult;
6992 return ComparisonResult;
6993 }
6994
6995 /// Compare the two attach-ptr expressions by their computation order.
6996 /// Returns true iff LHS was computed before RHS by
6997 /// collectAttachPtrExprInfo().
6998 bool wasComputedBefore(const Expr *LHS, const Expr *RHS) const {
6999 const size_t &OrderLHS = Handler.AttachPtrComputationOrderMap.at(LHS);
7000 const size_t &OrderRHS = Handler.AttachPtrComputationOrderMap.at(RHS);
7001
7002 return OrderLHS < OrderRHS;
7003 }
7004
7005 private:
7006 /// Helper function to compare attach-pointer expressions semantically.
7007 /// This function handles various expression types that can be part of an
7008 /// attach-pointer.
7009 /// TODO: Not urgent, but we should ideally return true when comparing
7010 /// `p[10]`, `*(p + 10)`, `*(p + 5 + 5)`, `p[10:1]` etc.
7011 bool areSemanticallyEqual(const Expr *LHS, const Expr *RHS) const {
7012 if (LHS == RHS)
7013 return true;
7014
7015 // If only one is null, they aren't equal
7016 if (!LHS || !RHS)
7017 return false;
7018
7019 ASTContext &Ctx = Handler.CGF.getContext();
7020 // Strip away parentheses and no-op casts to get to the core expression
7021 LHS = LHS->IgnoreParenNoopCasts(Ctx);
7022 RHS = RHS->IgnoreParenNoopCasts(Ctx);
7023
7024 // Direct pointer comparison of the underlying expressions
7025 if (LHS == RHS)
7026 return true;
7027
7028 // Check if the expression classes match
7029 if (LHS->getStmtClass() != RHS->getStmtClass())
7030 return false;
7031
7032 // Handle DeclRefExpr (variable references)
7033 if (const auto *LD = dyn_cast<DeclRefExpr>(LHS)) {
7034 const auto *RD = dyn_cast<DeclRefExpr>(RHS);
7035 if (!RD)
7036 return false;
7037 return LD->getDecl()->getCanonicalDecl() ==
7038 RD->getDecl()->getCanonicalDecl();
7039 }
7040
7041 // Handle ArraySubscriptExpr (array indexing like a[i])
7042 if (const auto *LA = dyn_cast<ArraySubscriptExpr>(LHS)) {
7043 const auto *RA = dyn_cast<ArraySubscriptExpr>(RHS);
7044 if (!RA)
7045 return false;
7046 return areSemanticallyEqual(LA->getBase(), RA->getBase()) &&
7047 areSemanticallyEqual(LA->getIdx(), RA->getIdx());
7048 }
7049
7050 // Handle MemberExpr (member access like s.m or p->m)
7051 if (const auto *LM = dyn_cast<MemberExpr>(LHS)) {
7052 const auto *RM = dyn_cast<MemberExpr>(RHS);
7053 if (!RM)
7054 return false;
7055 if (LM->getMemberDecl()->getCanonicalDecl() !=
7056 RM->getMemberDecl()->getCanonicalDecl())
7057 return false;
7058 return areSemanticallyEqual(LM->getBase(), RM->getBase());
7059 }
7060
7061 // Handle UnaryOperator (unary operations like *p, &x, etc.)
7062 if (const auto *LU = dyn_cast<UnaryOperator>(LHS)) {
7063 const auto *RU = dyn_cast<UnaryOperator>(RHS);
7064 if (!RU)
7065 return false;
7066 if (LU->getOpcode() != RU->getOpcode())
7067 return false;
7068 return areSemanticallyEqual(LU->getSubExpr(), RU->getSubExpr());
7069 }
7070
7071 // Handle BinaryOperator (binary operations like p + offset)
7072 if (const auto *LB = dyn_cast<BinaryOperator>(LHS)) {
7073 const auto *RB = dyn_cast<BinaryOperator>(RHS);
7074 if (!RB)
7075 return false;
7076 if (LB->getOpcode() != RB->getOpcode())
7077 return false;
7078 return areSemanticallyEqual(LB->getLHS(), RB->getLHS()) &&
7079 areSemanticallyEqual(LB->getRHS(), RB->getRHS());
7080 }
7081
7082 // Handle ArraySectionExpr (array sections like a[0:1])
7083 // Attach pointers should not contain array-sections, but currently we
7084 // don't emit an error.
7085 if (const auto *LAS = dyn_cast<ArraySectionExpr>(LHS)) {
7086 const auto *RAS = dyn_cast<ArraySectionExpr>(RHS);
7087 if (!RAS)
7088 return false;
7089 return areSemanticallyEqual(LAS->getBase(), RAS->getBase()) &&
7090 areSemanticallyEqual(LAS->getLowerBound(),
7091 RAS->getLowerBound()) &&
7092 areSemanticallyEqual(LAS->getLength(), RAS->getLength());
7093 }
7094
7095 // Handle CastExpr (explicit casts)
7096 if (const auto *LC = dyn_cast<CastExpr>(LHS)) {
7097 const auto *RC = dyn_cast<CastExpr>(RHS);
7098 if (!RC)
7099 return false;
7100 if (LC->getCastKind() != RC->getCastKind())
7101 return false;
7102 return areSemanticallyEqual(LC->getSubExpr(), RC->getSubExpr());
7103 }
7104
7105 // Handle CXXThisExpr (this pointer)
7106 if (isa<CXXThisExpr>(LHS) && isa<CXXThisExpr>(RHS))
7107 return true;
7108
7109 // Handle IntegerLiteral (integer constants)
7110 if (const auto *LI = dyn_cast<IntegerLiteral>(LHS)) {
7111 const auto *RI = dyn_cast<IntegerLiteral>(RHS);
7112 if (!RI)
7113 return false;
7114 return LI->getValue() == RI->getValue();
7115 }
7116
7117 // Handle CharacterLiteral (character constants)
7118 if (const auto *LC = dyn_cast<CharacterLiteral>(LHS)) {
7119 const auto *RC = dyn_cast<CharacterLiteral>(RHS);
7120 if (!RC)
7121 return false;
7122 return LC->getValue() == RC->getValue();
7123 }
7124
7125 // Handle FloatingLiteral (floating point constants)
7126 if (const auto *LF = dyn_cast<FloatingLiteral>(LHS)) {
7127 const auto *RF = dyn_cast<FloatingLiteral>(RHS);
7128 if (!RF)
7129 return false;
7130 // Use bitwise comparison for floating point literals
7131 return LF->getValue().bitwiseIsEqual(RF->getValue());
7132 }
7133
7134 // Handle StringLiteral (string constants)
7135 if (const auto *LS = dyn_cast<StringLiteral>(LHS)) {
7136 const auto *RS = dyn_cast<StringLiteral>(RHS);
7137 if (!RS)
7138 return false;
7139 return LS->getString() == RS->getString();
7140 }
7141
7142 // Handle CXXNullPtrLiteralExpr (nullptr)
7143 if (isa<CXXNullPtrLiteralExpr>(LHS) && isa<CXXNullPtrLiteralExpr>(RHS))
7144 return true;
7145
7146 // Handle CXXBoolLiteralExpr (true/false)
7147 if (const auto *LB = dyn_cast<CXXBoolLiteralExpr>(LHS)) {
7148 const auto *RB = dyn_cast<CXXBoolLiteralExpr>(RHS);
7149 if (!RB)
7150 return false;
7151 return LB->getValue() == RB->getValue();
7152 }
7153
7154 // Fallback for other forms - use the existing comparison method
7155 return Expr::isSameComparisonOperand(LHS, RHS);
7156 }
7157 };
7158
7159 /// Get the offset of the OMP_MAP_MEMBER_OF field.
7160 static unsigned getFlagMemberOffset() {
7161 unsigned Offset = 0;
7162 for (uint64_t Remain =
7163 static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
7164 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF);
7165 !(Remain & 1); Remain = Remain >> 1)
7166 Offset++;
7167 return Offset;
7168 }
7169
7170 /// Class that holds debugging information for a data mapping to be passed to
7171 /// the runtime library.
7172 class MappingExprInfo {
7173 /// The variable declaration used for the data mapping.
7174 const ValueDecl *MapDecl = nullptr;
7175 /// The original expression used in the map clause, or null if there is
7176 /// none.
7177 const Expr *MapExpr = nullptr;
7178
7179 public:
7180 MappingExprInfo(const ValueDecl *MapDecl, const Expr *MapExpr = nullptr)
7181 : MapDecl(MapDecl), MapExpr(MapExpr) {}
7182
7183 const ValueDecl *getMapDecl() const { return MapDecl; }
7184 const Expr *getMapExpr() const { return MapExpr; }
7185 };
7186
7187 using DeviceInfoTy = llvm::OpenMPIRBuilder::DeviceInfoTy;
7188 using MapBaseValuesArrayTy = llvm::OpenMPIRBuilder::MapValuesArrayTy;
7189 using MapValuesArrayTy = llvm::OpenMPIRBuilder::MapValuesArrayTy;
7190 using MapFlagsArrayTy = llvm::OpenMPIRBuilder::MapFlagsArrayTy;
7191 using MapDimArrayTy = llvm::OpenMPIRBuilder::MapDimArrayTy;
7192 using MapNonContiguousArrayTy =
7193 llvm::OpenMPIRBuilder::MapNonContiguousArrayTy;
7194 using MapExprsArrayTy = SmallVector<MappingExprInfo, 4>;
7195 using MapValueDeclsArrayTy = SmallVector<const ValueDecl *, 4>;
7196 using MapData =
7197 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7198 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>,
7199 bool /*IsImplicit*/, const ValueDecl *, const Expr *>;
7200 using MapDataArrayTy = SmallVector<MapData, 4>;
7201
7202 /// This structure contains combined information generated for mappable
7203 /// clauses, including base pointers, pointers, sizes, map types, user-defined
7204 /// mappers, and non-contiguous information.
7205 struct MapCombinedInfoTy : llvm::OpenMPIRBuilder::MapInfosTy {
7206 MapExprsArrayTy Exprs;
7207 MapValueDeclsArrayTy Mappers;
7208 MapValueDeclsArrayTy DevicePtrDecls;
7209
7210 /// Append arrays in \a CurInfo.
7211 void append(MapCombinedInfoTy &CurInfo) {
7212 Exprs.append(CurInfo.Exprs.begin(), CurInfo.Exprs.end());
7213 DevicePtrDecls.append(CurInfo.DevicePtrDecls.begin(),
7214 CurInfo.DevicePtrDecls.end());
7215 Mappers.append(CurInfo.Mappers.begin(), CurInfo.Mappers.end());
7216 llvm::OpenMPIRBuilder::MapInfosTy::append(CurInfo);
7217 }
7218 };
7219
7220 /// Map between a struct and the its lowest & highest elements which have been
7221 /// mapped.
7222 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
7223 /// HE(FieldIndex, Pointer)}
7224 struct StructRangeInfoTy {
7225 MapCombinedInfoTy PreliminaryMapData;
7226 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
7227 0, Address::invalid()};
7228 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
7229 0, Address::invalid()};
7230 Address Base = Address::invalid();
7231 Address LB = Address::invalid();
7232 bool IsArraySection = false;
7233 bool HasCompleteRecord = false;
7234 };
7235
7236 /// A struct to store the attach pointer and pointee information, to be used
7237 /// when emitting an attach entry.
7238 struct AttachInfoTy {
7239 Address AttachPtrAddr = Address::invalid();
7240 Address AttachPteeAddr = Address::invalid();
7241 const ValueDecl *AttachPtrDecl = nullptr;
7242 const Expr *AttachMapExpr = nullptr;
7243
7244 bool isValid() const {
7245 return AttachPtrAddr.isValid() && AttachPteeAddr.isValid();
7246 }
7247 };
7248
7249 /// Check if there's any component list where the attach pointer expression
7250 /// matches the given captured variable.
7251 bool hasAttachEntryForCapturedVar(const ValueDecl *VD) const {
7252 for (const auto &AttachEntry : AttachPtrExprMap) {
7253 if (AttachEntry.second) {
7254 // Check if the attach pointer expression is a DeclRefExpr that
7255 // references the captured variable
7256 if (const auto *DRE = dyn_cast<DeclRefExpr>(AttachEntry.second))
7257 if (DRE->getDecl() == VD)
7258 return true;
7259 }
7260 }
7261 return false;
7262 }
7263
7264 /// Get the previously-cached attach pointer for a component list, if-any.
7265 const Expr *getAttachPtrExpr(
7266 OMPClauseMappableExprCommon::MappableExprComponentListRef Components)
7267 const {
7268 const auto It = AttachPtrExprMap.find(Components);
7269 if (It != AttachPtrExprMap.end())
7270 return It->second;
7271
7272 return nullptr;
7273 }
7274
7275 private:
7276 /// Kind that defines how a device pointer has to be returned.
7277 struct MapInfo {
7278 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7279 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7280 ArrayRef<OpenMPMapModifierKind> MapModifiers;
7281 ArrayRef<OpenMPMotionModifierKind> MotionModifiers;
7282 bool ReturnDevicePointer = false;
7283 bool IsImplicit = false;
7284 const ValueDecl *Mapper = nullptr;
7285 const Expr *VarRef = nullptr;
7286 bool ForDeviceAddr = false;
7287
7288 MapInfo() = default;
7289 MapInfo(
7290 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7291 OpenMPMapClauseKind MapType,
7292 ArrayRef<OpenMPMapModifierKind> MapModifiers,
7293 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
7294 bool ReturnDevicePointer, bool IsImplicit,
7295 const ValueDecl *Mapper = nullptr, const Expr *VarRef = nullptr,
7296 bool ForDeviceAddr = false)
7297 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
7298 MotionModifiers(MotionModifiers),
7299 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit),
7300 Mapper(Mapper), VarRef(VarRef), ForDeviceAddr(ForDeviceAddr) {}
7301 };
7302
7303 /// The target directive from where the mappable clauses were extracted. It
7304 /// is either a executable directive or a user-defined mapper directive.
7305 llvm::PointerUnion<const OMPExecutableDirective *,
7306 const OMPDeclareMapperDecl *>
7307 CurDir;
7308
7309 /// Function the directive is being generated for.
7310 CodeGenFunction &CGF;
7311
7312 /// Set of all first private variables in the current directive.
7313 /// bool data is set to true if the variable is implicitly marked as
7314 /// firstprivate, false otherwise.
7315 llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, bool> FirstPrivateDecls;
7316
7317 /// Set of defaultmap clause kinds that use firstprivate behavior.
7318 llvm::SmallSet<OpenMPDefaultmapClauseKind, 4> DefaultmapFirstprivateKinds;
7319
7320 /// Map between device pointer declarations and their expression components.
7321 /// The key value for declarations in 'this' is null.
7322 llvm::DenseMap<
7323 const ValueDecl *,
7324 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
7325 DevPointersMap;
7326
7327 /// Map between device addr declarations and their expression components.
7328 /// The key value for declarations in 'this' is null.
7329 llvm::DenseMap<
7330 const ValueDecl *,
7331 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
7332 HasDevAddrsMap;
7333
7334 /// Map between lambda declarations and their map type.
7335 llvm::DenseMap<const ValueDecl *, const OMPMapClause *> LambdasMap;
7336
7337 /// Map from component lists to their attach pointer expressions.
7338 llvm::DenseMap<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7339 const Expr *>
7340 AttachPtrExprMap;
7341
7342 /// Map from attach pointer expressions to their component depth.
7343 /// nullptr key has std::nullopt depth. This can be used to order attach-ptr
7344 /// expressions with increasing/decreasing depth.
7345 /// The component-depth of `nullptr` (i.e. no attach-ptr) is `std::nullopt`.
7346 /// TODO: Not urgent, but we should ideally use the number of pointer
7347 /// dereferences in an expr as an indicator of its complexity, instead of the
7348 /// component-depth. That would be needed for us to treat `p[1]`, `*(p + 10)`,
7349 /// `*(p + 5 + 5)` together.
7350 llvm::DenseMap<const Expr *, std::optional<size_t>>
7351 AttachPtrComponentDepthMap = {{nullptr, std::nullopt}};
7352
7353 /// Map from attach pointer expressions to the order they were computed in, in
7354 /// collectAttachPtrExprInfo().
7355 llvm::DenseMap<const Expr *, size_t> AttachPtrComputationOrderMap = {
7356 {nullptr, 0}};
7357
7358 /// An instance of attach-ptr-expr comparator that can be used throughout the
7359 /// lifetime of this handler.
7360 AttachPtrExprComparator AttachPtrComparator;
7361
7362 llvm::Value *getExprTypeSize(const Expr *E) const {
7363 QualType ExprTy = E->getType().getCanonicalType();
7364
7365 // Calculate the size for array shaping expression.
7366 if (const auto *OAE = dyn_cast<OMPArrayShapingExpr>(E)) {
7367 llvm::Value *Size =
7368 CGF.getTypeSize(OAE->getBase()->getType()->getPointeeType());
7369 for (const Expr *SE : OAE->getDimensions()) {
7370 llvm::Value *Sz = CGF.EmitScalarExpr(SE);
7371 Sz = CGF.EmitScalarConversion(Sz, SE->getType(),
7372 CGF.getContext().getSizeType(),
7373 SE->getExprLoc());
7374 Size = CGF.Builder.CreateNUWMul(Size, Sz);
7375 }
7376 return Size;
7377 }
7378
7379 // Reference types are ignored for mapping purposes.
7380 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
7381 ExprTy = RefTy->getPointeeType().getCanonicalType();
7382
7383 // Given that an array section is considered a built-in type, we need to
7384 // do the calculation based on the length of the section instead of relying
7385 // on CGF.getTypeSize(E->getType()).
7386 if (const auto *OAE = dyn_cast<ArraySectionExpr>(E)) {
7387 QualType BaseTy = ArraySectionExpr::getBaseOriginalType(
7388 OAE->getBase()->IgnoreParenImpCasts())
7389 .getCanonicalType();
7390
7391 // If there is no length associated with the expression and lower bound is
7392 // not specified too, that means we are using the whole length of the
7393 // base.
7394 if (!OAE->getLength() && OAE->getColonLocFirst().isValid() &&
7395 !OAE->getLowerBound())
7396 return CGF.getTypeSize(BaseTy);
7397
7398 llvm::Value *ElemSize;
7399 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
7400 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
7401 } else {
7402 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
7403 assert(ATy && "Expecting array type if not a pointer type.");
7404 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
7405 }
7406
7407 // If we don't have a length at this point, that is because we have an
7408 // array section with a single element.
7409 if (!OAE->getLength() && OAE->getColonLocFirst().isInvalid())
7410 return ElemSize;
7411
7412 if (const Expr *LenExpr = OAE->getLength()) {
7413 llvm::Value *LengthVal = CGF.EmitScalarExpr(LenExpr);
7414 LengthVal = CGF.EmitScalarConversion(LengthVal, LenExpr->getType(),
7415 CGF.getContext().getSizeType(),
7416 LenExpr->getExprLoc());
7417 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
7418 }
7419 assert(!OAE->getLength() && OAE->getColonLocFirst().isValid() &&
7420 OAE->getLowerBound() && "expected array_section[lb:].");
7421 // Size = sizetype - lb * elemtype;
7422 llvm::Value *LengthVal = CGF.getTypeSize(BaseTy);
7423 llvm::Value *LBVal = CGF.EmitScalarExpr(OAE->getLowerBound());
7424 LBVal = CGF.EmitScalarConversion(LBVal, OAE->getLowerBound()->getType(),
7425 CGF.getContext().getSizeType(),
7426 OAE->getLowerBound()->getExprLoc());
7427 LBVal = CGF.Builder.CreateNUWMul(LBVal, ElemSize);
7428 llvm::Value *Cmp = CGF.Builder.CreateICmpUGT(LengthVal, LBVal);
7429 llvm::Value *TrueVal = CGF.Builder.CreateNUWSub(LengthVal, LBVal);
7430 LengthVal = CGF.Builder.CreateSelect(
7431 Cmp, TrueVal, llvm::ConstantInt::get(CGF.SizeTy, 0));
7432 return LengthVal;
7433 }
7434 return CGF.getTypeSize(ExprTy);
7435 }
7436
7437 /// Return the corresponding bits for a given map clause modifier. Add
7438 /// a flag marking the map as a pointer if requested. Add a flag marking the
7439 /// map as the first one of a series of maps that relate to the same map
7440 /// expression.
7441 OpenMPOffloadMappingFlags getMapTypeBits(
7442 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
7443 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, bool IsImplicit,
7444 bool AddPtrFlag, bool AddIsTargetParamFlag, bool IsNonContiguous) const {
7445 OpenMPOffloadMappingFlags Bits =
7446 IsImplicit ? OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT
7447 : OpenMPOffloadMappingFlags::OMP_MAP_NONE;
7448 switch (MapType) {
7449 case OMPC_MAP_alloc:
7450 case OMPC_MAP_release:
7451 // alloc and release is the default behavior in the runtime library, i.e.
7452 // if we don't pass any bits alloc/release that is what the runtime is
7453 // going to do. Therefore, we don't need to signal anything for these two
7454 // type modifiers.
7455 break;
7456 case OMPC_MAP_to:
7457 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_TO;
7458 break;
7459 case OMPC_MAP_from:
7460 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_FROM;
7461 break;
7462 case OMPC_MAP_tofrom:
7463 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_TO |
7464 OpenMPOffloadMappingFlags::OMP_MAP_FROM;
7465 break;
7466 case OMPC_MAP_delete:
7467 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_DELETE;
7468 break;
7469 case OMPC_MAP_unknown:
7470 llvm_unreachable("Unexpected map type!");
7471 }
7472 if (AddPtrFlag)
7473 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
7474 if (AddIsTargetParamFlag)
7475 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
7476 if (llvm::is_contained(MapModifiers, OMPC_MAP_MODIFIER_always))
7477 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
7478 if (llvm::is_contained(MapModifiers, OMPC_MAP_MODIFIER_close))
7479 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_CLOSE;
7480 if (llvm::is_contained(MapModifiers, OMPC_MAP_MODIFIER_present) ||
7481 llvm::is_contained(MotionModifiers, OMPC_MOTION_MODIFIER_present))
7482 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_PRESENT;
7483 if (llvm::is_contained(MapModifiers, OMPC_MAP_MODIFIER_ompx_hold))
7484 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
7485 if (IsNonContiguous)
7486 Bits |= OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG;
7487 return Bits;
7488 }
7489
7490 /// Return true if the provided expression is a final array section. A
7491 /// final array section, is one whose length can't be proved to be one.
7492 bool isFinalArraySectionExpression(const Expr *E) const {
7493 const auto *OASE = dyn_cast<ArraySectionExpr>(E);
7494
7495 // It is not an array section and therefore not a unity-size one.
7496 if (!OASE)
7497 return false;
7498
7499 // An array section with no colon always refer to a single element.
7500 if (OASE->getColonLocFirst().isInvalid())
7501 return false;
7502
7503 const Expr *Length = OASE->getLength();
7504
7505 // If we don't have a length we have to check if the array has size 1
7506 // for this dimension. Also, we should always expect a length if the
7507 // base type is pointer.
7508 if (!Length) {
7509 QualType BaseQTy = ArraySectionExpr::getBaseOriginalType(
7510 OASE->getBase()->IgnoreParenImpCasts())
7511 .getCanonicalType();
7512 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
7513 return ATy->getSExtSize() != 1;
7514 // If we don't have a constant dimension length, we have to consider
7515 // the current section as having any size, so it is not necessarily
7516 // unitary. If it happen to be unity size, that's user fault.
7517 return true;
7518 }
7519
7520 // Check if the length evaluates to 1.
7521 Expr::EvalResult Result;
7522 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
7523 return true; // Can have more that size 1.
7524
7525 llvm::APSInt ConstLength = Result.Val.getInt();
7526 return ConstLength.getSExtValue() != 1;
7527 }
7528
7529 /// Emit an attach entry into \p CombinedInfo, using the information from \p
7530 /// AttachInfo. For example, for a map of form `int *p; ... map(p[1:10])`,
7531 /// an attach entry has the following form:
7532 /// &p, &p[1], sizeof(void*), ATTACH
7533 void emitAttachEntry(CodeGenFunction &CGF, MapCombinedInfoTy &CombinedInfo,
7534 const AttachInfoTy &AttachInfo) const {
7535 assert(AttachInfo.isValid() &&
7536 "Expected valid attach pointer/pointee information!");
7537
7538 // Size is the size of the pointer itself - use pointer size, not BaseDecl
7539 // size
7540 llvm::Value *PointerSize = CGF.Builder.CreateIntCast(
7541 llvm::ConstantInt::get(
7542 CGF.CGM.SizeTy, CGF.getContext()
7543 .getTypeSizeInChars(CGF.getContext().VoidPtrTy)
7544 .getQuantity()),
7545 CGF.Int64Ty, /*isSigned=*/true);
7546
7547 CombinedInfo.Exprs.emplace_back(AttachInfo.AttachPtrDecl,
7548 AttachInfo.AttachMapExpr);
7549 CombinedInfo.BasePointers.push_back(
7550 AttachInfo.AttachPtrAddr.emitRawPointer(CGF));
7551 CombinedInfo.DevicePtrDecls.push_back(nullptr);
7552 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
7553 CombinedInfo.Pointers.push_back(
7554 AttachInfo.AttachPteeAddr.emitRawPointer(CGF));
7555 CombinedInfo.Sizes.push_back(PointerSize);
7556 CombinedInfo.Types.push_back(OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
7557 CombinedInfo.Mappers.push_back(nullptr);
7558 CombinedInfo.NonContigInfo.Dims.push_back(1);
7559 }
7560
7561 /// A helper class to copy structures with overlapped elements, i.e. those
7562 /// which have mappings of both "s" and "s.mem". Consecutive elements that
7563 /// are not explicitly copied have mapping nodes synthesized for them,
7564 /// taking care to avoid generating zero-sized copies.
7565 class CopyOverlappedEntryGaps {
7566 CodeGenFunction &CGF;
7567 MapCombinedInfoTy &CombinedInfo;
7568 OpenMPOffloadMappingFlags Flags = OpenMPOffloadMappingFlags::OMP_MAP_NONE;
7569 const ValueDecl *MapDecl = nullptr;
7570 const Expr *MapExpr = nullptr;
7571 Address BP = Address::invalid();
7572 bool IsNonContiguous = false;
7573 uint64_t DimSize = 0;
7574 // These elements track the position as the struct is iterated over
7575 // (in order of increasing element address).
7576 const RecordDecl *LastParent = nullptr;
7577 uint64_t Cursor = 0;
7578 unsigned LastIndex = -1u;
7579 Address LB = Address::invalid();
7580
7581 public:
7582 CopyOverlappedEntryGaps(CodeGenFunction &CGF,
7583 MapCombinedInfoTy &CombinedInfo,
7584 OpenMPOffloadMappingFlags Flags,
7585 const ValueDecl *MapDecl, const Expr *MapExpr,
7586 Address BP, Address LB, bool IsNonContiguous,
7587 uint64_t DimSize)
7588 : CGF(CGF), CombinedInfo(CombinedInfo), Flags(Flags), MapDecl(MapDecl),
7589 MapExpr(MapExpr), BP(BP), IsNonContiguous(IsNonContiguous),
7590 DimSize(DimSize), LB(LB) {}
7591
7592 void processField(
7593 const OMPClauseMappableExprCommon::MappableComponent &MC,
7594 const FieldDecl *FD,
7595 llvm::function_ref<LValue(CodeGenFunction &, const MemberExpr *)>
7596 EmitMemberExprBase) {
7597 const RecordDecl *RD = FD->getParent();
7598 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
7599 uint64_t FieldOffset = RL.getFieldOffset(FD->getFieldIndex());
7600 uint64_t FieldSize =
7601 CGF.getContext().getTypeSize(FD->getType().getCanonicalType());
7602 Address ComponentLB = Address::invalid();
7603
7604 if (FD->getType()->isLValueReferenceType()) {
7605 const auto *ME = cast<MemberExpr>(MC.getAssociatedExpression());
7606 LValue BaseLVal = EmitMemberExprBase(CGF, ME);
7607 ComponentLB =
7608 CGF.EmitLValueForFieldInitialization(BaseLVal, FD).getAddress();
7609 } else {
7610 ComponentLB =
7611 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression()).getAddress();
7612 }
7613
7614 if (!LastParent)
7615 LastParent = RD;
7616 if (FD->getParent() == LastParent) {
7617 if (FD->getFieldIndex() != LastIndex + 1)
7618 copyUntilField(FD, ComponentLB);
7619 } else {
7620 LastParent = FD->getParent();
7621 if (((int64_t)FieldOffset - (int64_t)Cursor) > 0)
7622 copyUntilField(FD, ComponentLB);
7623 }
7624 Cursor = FieldOffset + FieldSize;
7625 LastIndex = FD->getFieldIndex();
7626 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
7627 }
7628
7629 void copyUntilField(const FieldDecl *FD, Address ComponentLB) {
7630 llvm::Value *ComponentLBPtr = ComponentLB.emitRawPointer(CGF);
7631 llvm::Value *LBPtr = LB.emitRawPointer(CGF);
7632 llvm::Value *Size =
7633 CGF.Builder.CreatePtrDiff(CGF.Int8Ty, ComponentLBPtr, LBPtr);
7634 copySizedChunk(LBPtr, Size);
7635 }
7636
7637 void copyUntilEnd(Address HB) {
7638 if (LastParent) {
7639 const ASTRecordLayout &RL =
7640 CGF.getContext().getASTRecordLayout(LastParent);
7641 if ((uint64_t)CGF.getContext().toBits(RL.getSize()) <= Cursor)
7642 return;
7643 }
7644 llvm::Value *LBPtr = LB.emitRawPointer(CGF);
7645 llvm::Value *Size = CGF.Builder.CreatePtrDiff(
7646 CGF.Int8Ty, CGF.Builder.CreateConstGEP(HB, 1).emitRawPointer(CGF),
7647 LBPtr);
7648 copySizedChunk(LBPtr, Size);
7649 }
7650
7651 void copySizedChunk(llvm::Value *Base, llvm::Value *Size) {
7652 CombinedInfo.Exprs.emplace_back(MapDecl, MapExpr);
7653 CombinedInfo.BasePointers.push_back(BP.emitRawPointer(CGF));
7654 CombinedInfo.DevicePtrDecls.push_back(nullptr);
7655 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
7656 CombinedInfo.Pointers.push_back(Base);
7657 CombinedInfo.Sizes.push_back(
7658 CGF.Builder.CreateIntCast(Size, CGF.Int64Ty, /*isSigned=*/true));
7659 CombinedInfo.Types.push_back(Flags);
7660 CombinedInfo.Mappers.push_back(nullptr);
7661 CombinedInfo.NonContigInfo.Dims.push_back(IsNonContiguous ? DimSize : 1);
7662 }
7663 };
7664
7665 /// Generate the base pointers, section pointers, sizes, map type bits, and
7666 /// user-defined mappers (all included in \a CombinedInfo) for the provided
7667 /// map type, map or motion modifiers, and expression components.
7668 /// \a IsFirstComponent should be set to true if the provided set of
7669 /// components is the first associated with a capture.
7670 void generateInfoForComponentList(
7671 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
7672 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
7673 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7674 MapCombinedInfoTy &CombinedInfo,
7675 MapCombinedInfoTy &StructBaseCombinedInfo,
7676 StructRangeInfoTy &PartialStruct, AttachInfoTy &AttachInfo,
7677 bool IsFirstComponentList, bool IsImplicit,
7678 bool GenerateAllInfoForClauses, const ValueDecl *Mapper = nullptr,
7679 bool ForDeviceAddr = false, const ValueDecl *BaseDecl = nullptr,
7680 const Expr *MapExpr = nullptr,
7681 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7682 OverlappedElements = {}) const {
7683
7684 // The following summarizes what has to be generated for each map and the
7685 // types below. The generated information is expressed in this order:
7686 // base pointer, section pointer, size, flags
7687 // (to add to the ones that come from the map type and modifier).
7688 // Entries annotated with (+) are only generated for "target" constructs,
7689 // and only if the variable at the beginning of the expression is used in
7690 // the region.
7691 //
7692 // double d;
7693 // int i[100];
7694 // float *p;
7695 // int **a = &i;
7696 //
7697 // struct S1 {
7698 // int i;
7699 // float f[50];
7700 // }
7701 // struct S2 {
7702 // int i;
7703 // float f[50];
7704 // S1 s;
7705 // double *p;
7706 // double *&pref;
7707 // struct S2 *ps;
7708 // int &ref;
7709 // }
7710 // S2 s;
7711 // S2 *ps;
7712 //
7713 // map(d)
7714 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
7715 //
7716 // map(i)
7717 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
7718 //
7719 // map(i[1:23])
7720 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
7721 //
7722 // map(p)
7723 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
7724 //
7725 // map(p[1:24])
7726 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM // map pointee
7727 // &p, &p[1], sizeof(void*), ATTACH // attach pointer/pointee, if both
7728 // // are present, and either is new
7729 //
7730 // map(([22])p)
7731 // p, p, 22*sizeof(float), TARGET_PARAM | TO | FROM
7732 // &p, p, sizeof(void*), ATTACH
7733 //
7734 // map((*a)[0:3])
7735 // a, a, 0, TARGET_PARAM | IMPLICIT // (+)
7736 // (*a)[0], &(*a)[0], 3 * sizeof(int), TO | FROM
7737 // &(*a), &(*a)[0], sizeof(void*), ATTACH
7738 // (+) Only on target, if a is used in the region
7739 // Note: Since the attach base-pointer is `*a`, which is not a scalar
7740 // variable, it doesn't determine the clause on `a`. `a` is mapped using
7741 // a zero-length-array-section map by generateDefaultMapInfo, if it is
7742 // referenced in the target region, because it is a pointer.
7743 //
7744 // map(**a)
7745 // a, a, 0, TARGET_PARAM | IMPLICIT // (+)
7746 // &(*a)[0], &(*a)[0], sizeof(int), TO | FROM
7747 // &(*a), &(*a)[0], sizeof(void*), ATTACH
7748 // (+) Only on target, if a is used in the region
7749 //
7750 // map(s)
7751 // FIXME: This needs to also imply map(ref_ptr_ptee: s.ref), since the
7752 // effect is supposed to be same as if the user had a map for every element
7753 // of the struct. We currently do a shallow-map of s.
7754 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
7755 //
7756 // map(s.i)
7757 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
7758 //
7759 // map(s.s.f)
7760 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
7761 //
7762 // map(s.p)
7763 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
7764 //
7765 // map(to: s.p[:22])
7766 // &s, &(s.p), sizeof(double*), TARGET_PARAM | IMPLICIT // (+)
7767 // &(s.p[0]), &(s.p[0]), 22 * sizeof(double*), TO | FROM
7768 // &(s.p), &(s.p[0]), sizeof(void*), ATTACH
7769 //
7770 // map(to: s.ref)
7771 // &s, &(ptr(s.ref)), sizeof(int*), TARGET_PARAM (*)
7772 // &s, &(ptee(s.ref)), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
7773 // (*) alloc space for struct members, only this is a target parameter.
7774 // (**) map the pointer (nothing to be mapped in this example) (the compiler
7775 // optimizes this entry out, same in the examples below)
7776 // (***) map the pointee (map: to)
7777 // Note: ptr(s.ref) represents the referring pointer of s.ref
7778 // ptee(s.ref) represents the referenced pointee of s.ref
7779 //
7780 // map(to: s.pref)
7781 // &s, &(ptr(s.pref)), sizeof(double**), TARGET_PARAM
7782 // &s, &(ptee(s.pref)), sizeof(double*), MEMBER_OF(1) | PTR_AND_OBJ | TO
7783 //
7784 // map(to: s.pref[:22])
7785 // &s, &(ptr(s.pref)), sizeof(double**), TARGET_PARAM | IMPLICIT // (+)
7786 // &s, &(ptee(s.pref)), sizeof(double*), MEMBER_OF(1) | PTR_AND_OBJ | TO |
7787 // FROM | IMPLICIT // (+)
7788 // &(ptee(s.pref)[0]), &(ptee(s.pref)[0]), 22 * sizeof(double), TO
7789 // &(ptee(s.pref)), &(ptee(s.pref)[0]), sizeof(void*), ATTACH
7790 //
7791 // map(s.ps)
7792 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
7793 //
7794 // map(from: s.ps->s.i)
7795 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM | IMPLICIT // (+)
7796 // &(s.ps[0]), &(s.ps->s.i), sizeof(int), FROM
7797 // &(s.ps), &(s.ps->s.i), sizeof(void*), ATTACH
7798 //
7799 // map(to: s.ps->ps)
7800 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM | IMPLICIT // (+)
7801 // &(s.ps[0]), &(s.ps->ps), sizeof(S2*), TO
7802 // &(s.ps), &(s.ps->ps), sizeof(void*), ATTACH
7803 //
7804 // map(s.ps->ps->ps)
7805 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM | IMPLICIT // (+)
7806 // &(s.ps->ps[0]), &(s.ps->ps->ps), sizeof(S2*), TO
7807 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(void*), ATTACH
7808 //
7809 // map(to: s.ps->ps->s.f[:22])
7810 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM | IMPLICIT // (+)
7811 // &(s.ps->ps[0]), &(s.ps->ps->s.f[0]), 22*sizeof(float), TO
7812 // &(s.ps->ps), &(s.ps->ps->s.f[0]), sizeof(void*), ATTACH
7813 //
7814 // map(ps)
7815 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
7816 //
7817 // map(ps->i)
7818 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
7819 // &ps, &(ps->i), sizeof(void*), ATTACH
7820 //
7821 // map(ps->s.f)
7822 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
7823 // &ps, &(ps->s.f[0]), sizeof(ps), ATTACH
7824 //
7825 // map(from: ps->p)
7826 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
7827 // &ps, &(ps->p), sizeof(ps), ATTACH
7828 //
7829 // map(to: ps->p[:22])
7830 // ps, &(ps[0]), 0, TARGET_PARAM | IMPLICIT // (+)
7831 // &(ps->p[0]), &(ps->p[0]), 22*sizeof(double), TO
7832 // &(ps->p), &(ps->p[0]), sizeof(void*), ATTACH
7833 //
7834 // map(ps->ps)
7835 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
7836 // &ps, &(ps->ps), sizeof(ps), ATTACH
7837 //
7838 // map(from: ps->ps->s.i)
7839 // ps, &(ps[0]), 0, TARGET_PARAM | IMPLICIT // (+)
7840 // &(ps->ps[0]), &(ps->ps->s.i), sizeof(int), FROM
7841 // &(ps->ps), &(ps->ps->s.i), sizeof(void*), ATTACH
7842 //
7843 // map(from: ps->ps->ps)
7844 // ps, &ps[0], 0, TARGET_PARAM | IMPLICIT // (+)
7845 // &(ps->ps[0]), &(ps->ps->ps), sizeof(S2*), FROM
7846 // &(ps->ps), &(ps->ps->ps), sizeof(void*), ATTACH
7847 //
7848 // map(ps->ps->ps->ps)
7849 // ps, &ps[0], 0, TARGET_PARAM | IMPLICIT // (+)
7850 // &(ps->ps->ps[0]), &(ps->ps->ps->ps), sizeof(S2*), FROM
7851 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(void*), ATTACH
7852 //
7853 // map(to: ps->ps->ps->s.f[:22])
7854 // ps, &ps[0], 0, TARGET_PARAM | IMPLICIT // (+)
7855 // &(ps->ps->ps[0]), &(ps->ps->ps->s.f[0]), 22*sizeof(float), TO
7856 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), sizeof(void*), ATTACH
7857 //
7858 // map(to: s.f[:22]) map(from: s.p[:33])
7859 // On target, and if s is used in the region:
7860 //
7861 // &s, &(s.f[0]), 50*sizeof(float) +
7862 // sizeof(struct S1) +
7863 // sizeof(double*) (**), TARGET_PARAM
7864 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
7865 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) | TO |
7866 // FROM | IMPLICIT
7867 // &(s.p[0]), &(s.p[0]), 33*sizeof(double), FROM
7868 // &(s.p), &(s.p[0]), sizeof(void*), ATTACH
7869 // (**) allocate contiguous space needed to fit all mapped members even if
7870 // we allocate space for members not mapped (in this example,
7871 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7872 // them as well because they fall between &s.f[0] and &s.p)
7873 //
7874 // On other constructs, and, if s is not used in the region, on target:
7875 // &s, &(s.f[0]), 22*sizeof(float), TO
7876 // &(s.p[0]), &(s.p[0]), 33*sizeof(double), FROM
7877 // &(s.p), &(s.p[0]), sizeof(void*), ATTACH
7878 //
7879 // map(from: s.f[:22]) map(to: ps->p[:33])
7880 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7881 // &ps[0], &ps[0], 0, TARGET_PARAM | IMPLICIT // (+)
7882 // &(ps->p[0]), &(ps->p[0]), 33*sizeof(double), TO
7883 // &(ps->p), &(ps->p[0]), sizeof(void*), ATTACH
7884 //
7885 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7886 // &s, &(s.f[0]), 50*sizeof(float) +
7887 // sizeof(struct S1), TARGET_PARAM
7888 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7889 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7890 // ps, &ps[0], 0, TARGET_PARAM | IMPLICIT // (+)
7891 // &(ps->p[0]), &(ps->p[0]), 33*sizeof(double), TO
7892 // &(ps->p), &(ps->p[0]), sizeof(void*), ATTACH
7893 //
7894 // map(p[:100], p)
7895 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
7896 // p, &p[0], 100*sizeof(float), TO | FROM
7897 // &p, &p[0], sizeof(float*), ATTACH
7898
7899 // Track if the map information being generated is the first for a capture.
7900 bool IsCaptureFirstInfo = IsFirstComponentList;
7901 // When the variable is on a declare target link or in a to clause with
7902 // unified memory, a reference is needed to hold the host/device address
7903 // of the variable.
7904 bool RequiresReference = false;
7905
7906 // Scan the components from the base to the complete expression.
7907 auto CI = Components.rbegin();
7908 auto CE = Components.rend();
7909 auto I = CI;
7910
7911 // Track if the map information being generated is the first for a list of
7912 // components.
7913 bool IsExpressionFirstInfo = true;
7914 bool FirstPointerInComplexData = false;
7915 Address BP = Address::invalid();
7916 Address FinalLowestElem = Address::invalid();
7917 const Expr *AssocExpr = I->getAssociatedExpression();
7918 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7919 const auto *OASE = dyn_cast<ArraySectionExpr>(AssocExpr);
7920 const auto *OAShE = dyn_cast<OMPArrayShapingExpr>(AssocExpr);
7921
7922 // Get the pointer-attachment base-pointer for the given list, if any.
7923 const Expr *AttachPtrExpr = getAttachPtrExpr(Components);
7924 auto [AttachPtrAddr, AttachPteeBaseAddr] =
7925 getAttachPtrAddrAndPteeBaseAddr(AttachPtrExpr, CGF);
7926
7927 bool HasAttachPtr = AttachPtrExpr != nullptr;
7928 bool FirstComponentIsForAttachPtr = AssocExpr == AttachPtrExpr;
7929 bool SeenAttachPtr = FirstComponentIsForAttachPtr;
7930
7931 if (FirstComponentIsForAttachPtr) {
7932 // No need to process AttachPtr here. It will be processed at the end
7933 // after we have computed the pointee's address.
7934 ++I;
7935 } else if (isa<MemberExpr>(AssocExpr)) {
7936 // The base is the 'this' pointer. The content of the pointer is going
7937 // to be the base of the field being mapped.
7938 BP = CGF.LoadCXXThisAddress();
7939 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7940 (OASE &&
7941 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7942 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
7943 } else if (OAShE &&
7944 isa<CXXThisExpr>(OAShE->getBase()->IgnoreParenCasts())) {
7945 BP = Address(
7946 CGF.EmitScalarExpr(OAShE->getBase()),
7947 CGF.ConvertTypeForMem(OAShE->getBase()->getType()->getPointeeType()),
7948 CGF.getContext().getTypeAlignInChars(OAShE->getBase()->getType()));
7949 } else {
7950 // The base is the reference to the variable.
7951 // BP = &Var.
7952 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
7953 if (const auto *VD =
7954 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7955 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7956 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
7957 if ((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
7958 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
7959 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
7960 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) {
7961 RequiresReference = true;
7962 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
7963 }
7964 }
7965 }
7966
7967 // If the variable is a pointer and is being dereferenced (i.e. is not
7968 // the last component), the base has to be the pointer itself, not its
7969 // reference. References are ignored for mapping purposes.
7970 QualType Ty =
7971 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7972 if (Ty->isAnyPointerType() && std::next(I) != CE) {
7973 // No need to generate individual map information for the pointer, it
7974 // can be associated with the combined storage if shared memory mode is
7975 // active or the base declaration is not global variable.
7976 const auto *VD = dyn_cast<VarDecl>(I->getAssociatedDeclaration());
7977 if (CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory() ||
7978 !VD || VD->hasLocalStorage() || HasAttachPtr)
7979 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
7980 else
7981 FirstPointerInComplexData = true;
7982 ++I;
7983 }
7984 }
7985
7986 // Track whether a component of the list should be marked as MEMBER_OF some
7987 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7988 // in a component list should be marked as MEMBER_OF, all subsequent entries
7989 // do not belong to the base struct. E.g.
7990 // struct S2 s;
7991 // s.ps->ps->ps->f[:]
7992 // (1) (2) (3) (4)
7993 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7994 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7995 // is the pointee of ps(2) which is not member of struct s, so it should not
7996 // be marked as such (it is still PTR_AND_OBJ).
7997 // The variable is initialized to false so that PTR_AND_OBJ entries which
7998 // are not struct members are not considered (e.g. array of pointers to
7999 // data).
8000 bool ShouldBeMemberOf = false;
8001
8002 // Variable keeping track of whether or not we have encountered a component
8003 // in the component list which is a member expression. Useful when we have a
8004 // pointer or a final array section, in which case it is the previous
8005 // component in the list which tells us whether we have a member expression.
8006 // E.g. X.f[:]
8007 // While processing the final array section "[:]" it is "f" which tells us
8008 // whether we are dealing with a member of a declared struct.
8009 const MemberExpr *EncounteredME = nullptr;
8010
8011 // Track for the total number of dimension. Start from one for the dummy
8012 // dimension.
8013 uint64_t DimSize = 1;
8014
8015 // Detects non-contiguous updates due to strided accesses.
8016 // Sets the 'IsNonContiguous' flag so that the 'MapType' bits are set
8017 // correctly when generating information to be passed to the runtime. The
8018 // flag is set to true if any array section has a stride not equal to 1, or
8019 // if the stride is not a constant expression (conservatively assumed
8020 // non-contiguous).
8021 bool IsNonContiguous =
8022 CombinedInfo.NonContigInfo.IsNonContiguous ||
8023 any_of(Components, [&](const auto &Component) {
8024 const auto *OASE =
8025 dyn_cast<ArraySectionExpr>(Component.getAssociatedExpression());
8026 if (!OASE)
8027 return false;
8028
8029 const Expr *StrideExpr = OASE->getStride();
8030 if (!StrideExpr)
8031 return false;
8032
8033 const auto Constant =
8034 StrideExpr->getIntegerConstantExpr(CGF.getContext());
8035 if (!Constant)
8036 return false;
8037
8038 return !Constant->isOne();
8039 });
8040
8041 bool IsPrevMemberReference = false;
8042
8043 bool IsPartialMapped =
8044 !PartialStruct.PreliminaryMapData.BasePointers.empty();
8045
8046 // We need to check if we will be encountering any MEs. If we do not
8047 // encounter any ME expression it means we will be mapping the whole struct.
8048 // In that case we need to skip adding an entry for the struct to the
8049 // CombinedInfo list and instead add an entry to the StructBaseCombinedInfo
8050 // list only when generating all info for clauses.
8051 bool IsMappingWholeStruct = true;
8052 if (!GenerateAllInfoForClauses) {
8053 IsMappingWholeStruct = false;
8054 } else {
8055 for (auto TempI = I; TempI != CE; ++TempI) {
8056 const MemberExpr *PossibleME =
8057 dyn_cast<MemberExpr>(TempI->getAssociatedExpression());
8058 if (PossibleME) {
8059 IsMappingWholeStruct = false;
8060 break;
8061 }
8062 }
8063 }
8064
8065 bool SeenFirstNonBinOpExprAfterAttachPtr = false;
8066 for (; I != CE; ++I) {
8067 // If we have a valid attach-ptr, we skip processing all components until
8068 // after the attach-ptr.
8069 if (HasAttachPtr && !SeenAttachPtr) {
8070 SeenAttachPtr = I->getAssociatedExpression() == AttachPtrExpr;
8071 continue;
8072 }
8073
8074 // After finding the attach pointer, skip binary-ops, to skip past
8075 // expressions like (p + 10), for a map like map(*(p + 10)), where p is
8076 // the attach-ptr.
8077 if (HasAttachPtr && !SeenFirstNonBinOpExprAfterAttachPtr) {
8078 const auto *BO = dyn_cast<BinaryOperator>(I->getAssociatedExpression());
8079 if (BO)
8080 continue;
8081
8082 // Found the first non-binary-operator component after attach
8083 SeenFirstNonBinOpExprAfterAttachPtr = true;
8084 BP = AttachPteeBaseAddr;
8085 }
8086
8087 // If the current component is member of a struct (parent struct) mark it.
8088 if (!EncounteredME) {
8089 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
8090 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
8091 // as MEMBER_OF the parent struct.
8092 if (EncounteredME) {
8093 ShouldBeMemberOf = true;
8094 // Do not emit as complex pointer if this is actually not array-like
8095 // expression.
8096 if (FirstPointerInComplexData) {
8097 QualType Ty = std::prev(I)
8098 ->getAssociatedDeclaration()
8099 ->getType()
8100 .getNonReferenceType();
8101 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
8102 FirstPointerInComplexData = false;
8103 }
8104 }
8105 }
8106
8107 auto Next = std::next(I);
8108
8109 // We need to generate the addresses and sizes if this is the last
8110 // component, if the component is a pointer or if it is an array section
8111 // whose length can't be proved to be one. If this is a pointer, it
8112 // becomes the base address for the following components.
8113
8114 // A final array section, is one whose length can't be proved to be one.
8115 // If the map item is non-contiguous then we don't treat any array section
8116 // as final array section.
8117 bool IsFinalArraySection =
8118 !IsNonContiguous &&
8119 isFinalArraySectionExpression(I->getAssociatedExpression());
8120
8121 // If we have a declaration for the mapping use that, otherwise use
8122 // the base declaration of the map clause.
8123 const ValueDecl *MapDecl = (I->getAssociatedDeclaration())
8124 ? I->getAssociatedDeclaration()
8125 : BaseDecl;
8126 MapExpr = (I->getAssociatedExpression()) ? I->getAssociatedExpression()
8127 : MapExpr;
8128
8129 // Get information on whether the element is a pointer. Have to do a
8130 // special treatment for array sections given that they are built-in
8131 // types.
8132 const auto *OASE =
8133 dyn_cast<ArraySectionExpr>(I->getAssociatedExpression());
8134 const auto *OAShE =
8135 dyn_cast<OMPArrayShapingExpr>(I->getAssociatedExpression());
8136 const auto *UO = dyn_cast<UnaryOperator>(I->getAssociatedExpression());
8137 const auto *BO = dyn_cast<BinaryOperator>(I->getAssociatedExpression());
8138 bool IsPointer =
8139 OAShE ||
8140 (OASE && ArraySectionExpr::getBaseOriginalType(OASE)
8141 .getCanonicalType()
8142 ->isAnyPointerType()) ||
8143 I->getAssociatedExpression()->getType()->isAnyPointerType();
8144 bool IsMemberReference = isa<MemberExpr>(I->getAssociatedExpression()) &&
8145 MapDecl &&
8146 MapDecl->getType()->isLValueReferenceType();
8147 bool IsNonDerefPointer = IsPointer &&
8148 !(UO && UO->getOpcode() != UO_Deref) && !BO &&
8149 !IsNonContiguous;
8150
8151 if (OASE)
8152 ++DimSize;
8153
8154 if (Next == CE || IsMemberReference || IsNonDerefPointer ||
8155 IsFinalArraySection) {
8156 // If this is not the last component, we expect the pointer to be
8157 // associated with an array expression or member expression.
8158 assert((Next == CE ||
8159 isa<MemberExpr>(Next->getAssociatedExpression()) ||
8160 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
8161 isa<ArraySectionExpr>(Next->getAssociatedExpression()) ||
8162 isa<OMPArrayShapingExpr>(Next->getAssociatedExpression()) ||
8163 isa<UnaryOperator>(Next->getAssociatedExpression()) ||
8164 isa<BinaryOperator>(Next->getAssociatedExpression())) &&
8165 "Unexpected expression");
8166
8167 Address LB = Address::invalid();
8168 Address LowestElem = Address::invalid();
8169 auto &&EmitMemberExprBase = [](CodeGenFunction &CGF,
8170 const MemberExpr *E) {
8171 const Expr *BaseExpr = E->getBase();
8172 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a
8173 // scalar.
8174 LValue BaseLV;
8175 if (E->isArrow()) {
8176 LValueBaseInfo BaseInfo;
8177 TBAAAccessInfo TBAAInfo;
8178 Address Addr =
8179 CGF.EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
8180 QualType PtrTy = BaseExpr->getType()->getPointeeType();
8181 BaseLV = CGF.MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
8182 } else {
8183 BaseLV = CGF.EmitOMPSharedLValue(BaseExpr);
8184 }
8185 return BaseLV;
8186 };
8187 if (OAShE) {
8188 LowestElem = LB =
8189 Address(CGF.EmitScalarExpr(OAShE->getBase()),
8190 CGF.ConvertTypeForMem(
8191 OAShE->getBase()->getType()->getPointeeType()),
8192 CGF.getContext().getTypeAlignInChars(
8193 OAShE->getBase()->getType()));
8194 } else if (IsMemberReference) {
8195 const auto *ME = cast<MemberExpr>(I->getAssociatedExpression());
8196 LValue BaseLVal = EmitMemberExprBase(CGF, ME);
8197 LowestElem = CGF.EmitLValueForFieldInitialization(
8198 BaseLVal, cast<FieldDecl>(MapDecl))
8199 .getAddress();
8200 LB = CGF.EmitLoadOfReferenceLValue(LowestElem, MapDecl->getType())
8201 .getAddress();
8202 } else {
8203 LowestElem = LB =
8204 CGF.EmitOMPSharedLValue(I->getAssociatedExpression())
8205 .getAddress();
8206 }
8207
8208 // Save the final LowestElem, to use it as the pointee in attach maps,
8209 // if emitted.
8210 if (Next == CE)
8211 FinalLowestElem = LowestElem;
8212
8213 // If this component is a pointer inside the base struct then we don't
8214 // need to create any entry for it - it will be combined with the object
8215 // it is pointing to into a single PTR_AND_OBJ entry.
8216 bool IsMemberPointerOrAddr =
8217 EncounteredME &&
8218 (((IsPointer || ForDeviceAddr) &&
8219 I->getAssociatedExpression() == EncounteredME) ||
8220 (IsPrevMemberReference && !IsPointer) ||
8221 (IsMemberReference && Next != CE &&
8222 !Next->getAssociatedExpression()->getType()->isPointerType()));
8223 if (!OverlappedElements.empty() && Next == CE) {
8224 // Handle base element with the info for overlapped elements.
8225 assert(!PartialStruct.Base.isValid() && "The base element is set.");
8226 assert(!IsPointer &&
8227 "Unexpected base element with the pointer type.");
8228 // Mark the whole struct as the struct that requires allocation on the
8229 // device.
8230 PartialStruct.LowestElem = {0, LowestElem};
8231 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
8232 I->getAssociatedExpression()->getType());
8233 Address HB = CGF.Builder.CreateConstGEP(
8234 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8235 LowestElem, CGF.VoidPtrTy, CGF.Int8Ty),
8236 TypeSize.getQuantity() - 1);
8237 PartialStruct.HighestElem = {
8238 std::numeric_limits<decltype(
8239 PartialStruct.HighestElem.first)>::max(),
8240 HB};
8241 PartialStruct.Base = BP;
8242 PartialStruct.LB = LB;
8243 assert(
8244 PartialStruct.PreliminaryMapData.BasePointers.empty() &&
8245 "Overlapped elements must be used only once for the variable.");
8246 std::swap(PartialStruct.PreliminaryMapData, CombinedInfo);
8247 // Emit data for non-overlapped data.
8248 OpenMPOffloadMappingFlags Flags =
8249 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF |
8250 getMapTypeBits(MapType, MapModifiers, MotionModifiers, IsImplicit,
8251 /*AddPtrFlag=*/false,
8252 /*AddIsTargetParamFlag=*/false, IsNonContiguous);
8253 CopyOverlappedEntryGaps CopyGaps(CGF, CombinedInfo, Flags, MapDecl,
8254 MapExpr, BP, LB, IsNonContiguous,
8255 DimSize);
8256 // Do bitcopy of all non-overlapped structure elements.
8257 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
8258 Component : OverlappedElements) {
8259 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
8260 Component) {
8261 if (const ValueDecl *VD = MC.getAssociatedDeclaration()) {
8262 if (const auto *FD = dyn_cast<FieldDecl>(VD)) {
8263 CopyGaps.processField(MC, FD, EmitMemberExprBase);
8264 }
8265 }
8266 }
8267 }
8268 CopyGaps.copyUntilEnd(HB);
8269 break;
8270 }
8271 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
8272 // Skip adding an entry in the CurInfo of this combined entry if the
8273 // whole struct is currently being mapped. The struct needs to be added
8274 // in the first position before any data internal to the struct is being
8275 // mapped.
8276 // Skip adding an entry in the CurInfo of this combined entry if the
8277 // PartialStruct.PreliminaryMapData.BasePointers has been mapped.
8278 if ((!IsMemberPointerOrAddr && !IsPartialMapped) ||
8279 (Next == CE && MapType != OMPC_MAP_unknown)) {
8280 if (!IsMappingWholeStruct) {
8281 CombinedInfo.Exprs.emplace_back(MapDecl, MapExpr);
8282 CombinedInfo.BasePointers.push_back(BP.emitRawPointer(CGF));
8283 CombinedInfo.DevicePtrDecls.push_back(nullptr);
8284 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
8285 CombinedInfo.Pointers.push_back(LB.emitRawPointer(CGF));
8286 CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
8287 Size, CGF.Int64Ty, /*isSigned=*/true));
8288 CombinedInfo.NonContigInfo.Dims.push_back(IsNonContiguous ? DimSize
8289 : 1);
8290 } else {
8291 StructBaseCombinedInfo.Exprs.emplace_back(MapDecl, MapExpr);
8292 StructBaseCombinedInfo.BasePointers.push_back(
8293 BP.emitRawPointer(CGF));
8294 StructBaseCombinedInfo.DevicePtrDecls.push_back(nullptr);
8295 StructBaseCombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
8296 StructBaseCombinedInfo.Pointers.push_back(LB.emitRawPointer(CGF));
8297 StructBaseCombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
8298 Size, CGF.Int64Ty, /*isSigned=*/true));
8299 StructBaseCombinedInfo.NonContigInfo.Dims.push_back(
8300 IsNonContiguous ? DimSize : 1);
8301 }
8302
8303 // If Mapper is valid, the last component inherits the mapper.
8304 bool HasMapper = Mapper && Next == CE;
8305 if (!IsMappingWholeStruct)
8306 CombinedInfo.Mappers.push_back(HasMapper ? Mapper : nullptr);
8307 else
8308 StructBaseCombinedInfo.Mappers.push_back(HasMapper ? Mapper
8309 : nullptr);
8310
8311 // We need to add a pointer flag for each map that comes from the
8312 // same expression except for the first one. We also need to signal
8313 // this map is the first one that relates with the current capture
8314 // (there is a set of entries for each capture).
8315 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
8316 MapType, MapModifiers, MotionModifiers, IsImplicit,
8317 !IsExpressionFirstInfo || RequiresReference ||
8318 FirstPointerInComplexData || IsMemberReference,
8319 IsCaptureFirstInfo && !RequiresReference, IsNonContiguous);
8320
8321 if (!IsExpressionFirstInfo || IsMemberReference) {
8322 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
8323 // then we reset the TO/FROM/ALWAYS/DELETE/CLOSE flags.
8324 if (IsPointer || (IsMemberReference && Next != CE))
8325 Flags &= ~(OpenMPOffloadMappingFlags::OMP_MAP_TO |
8326 OpenMPOffloadMappingFlags::OMP_MAP_FROM |
8327 OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS |
8328 OpenMPOffloadMappingFlags::OMP_MAP_DELETE |
8329 OpenMPOffloadMappingFlags::OMP_MAP_CLOSE);
8330
8331 if (ShouldBeMemberOf) {
8332 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
8333 // should be later updated with the correct value of MEMBER_OF.
8334 Flags |= OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
8335 // From now on, all subsequent PTR_AND_OBJ entries should not be
8336 // marked as MEMBER_OF.
8337 ShouldBeMemberOf = false;
8338 }
8339 }
8340
8341 if (!IsMappingWholeStruct)
8342 CombinedInfo.Types.push_back(Flags);
8343 else
8344 StructBaseCombinedInfo.Types.push_back(Flags);
8345 }
8346
8347 // If we have encountered a member expression so far, keep track of the
8348 // mapped member. If the parent is "*this", then the value declaration
8349 // is nullptr.
8350 if (EncounteredME) {
8351 const auto *FD = cast<FieldDecl>(EncounteredME->getMemberDecl());
8352 unsigned FieldIndex = FD->getFieldIndex();
8353
8354 // Update info about the lowest and highest elements for this struct
8355 if (!PartialStruct.Base.isValid()) {
8356 PartialStruct.LowestElem = {FieldIndex, LowestElem};
8357 if (IsFinalArraySection && OASE) {
8358 Address HB =
8359 CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false)
8360 .getAddress();
8361 PartialStruct.HighestElem = {FieldIndex, HB};
8362 } else {
8363 PartialStruct.HighestElem = {FieldIndex, LowestElem};
8364 }
8365 PartialStruct.Base = BP;
8366 PartialStruct.LB = BP;
8367 } else if (FieldIndex < PartialStruct.LowestElem.first) {
8368 PartialStruct.LowestElem = {FieldIndex, LowestElem};
8369 } else if (FieldIndex > PartialStruct.HighestElem.first) {
8370 if (IsFinalArraySection && OASE) {
8371 Address HB =
8372 CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/false)
8373 .getAddress();
8374 PartialStruct.HighestElem = {FieldIndex, HB};
8375 } else {
8376 PartialStruct.HighestElem = {FieldIndex, LowestElem};
8377 }
8378 }
8379 }
8380
8381 // Need to emit combined struct for array sections.
8382 if (IsFinalArraySection || IsNonContiguous)
8383 PartialStruct.IsArraySection = true;
8384
8385 // If we have a final array section, we are done with this expression.
8386 if (IsFinalArraySection)
8387 break;
8388
8389 // The pointer becomes the base for the next element.
8390 if (Next != CE)
8391 BP = IsMemberReference ? LowestElem : LB;
8392 if (!IsPartialMapped)
8393 IsExpressionFirstInfo = false;
8394 IsCaptureFirstInfo = false;
8395 FirstPointerInComplexData = false;
8396 IsPrevMemberReference = IsMemberReference;
8397 } else if (FirstPointerInComplexData) {
8398 QualType Ty = Components.rbegin()
8399 ->getAssociatedDeclaration()
8400 ->getType()
8401 .getNonReferenceType();
8402 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
8403 FirstPointerInComplexData = false;
8404 }
8405 }
8406 // If ran into the whole component - allocate the space for the whole
8407 // record.
8408 if (!EncounteredME)
8409 PartialStruct.HasCompleteRecord = true;
8410
8411 // Populate ATTACH information for later processing by emitAttachEntry.
8412 if (shouldEmitAttachEntry(AttachPtrExpr, BaseDecl, CGF, CurDir)) {
8413 AttachInfo.AttachPtrAddr = AttachPtrAddr;
8414 AttachInfo.AttachPteeAddr = FinalLowestElem;
8415 AttachInfo.AttachPtrDecl = BaseDecl;
8416 AttachInfo.AttachMapExpr = MapExpr;
8417 }
8418
8419 if (!IsNonContiguous)
8420 return;
8421
8422 const ASTContext &Context = CGF.getContext();
8423
8424 // For supporting stride in array section, we need to initialize the first
8425 // dimension size as 1, first offset as 0, and first count as 1
8426 MapValuesArrayTy CurOffsets = {llvm::ConstantInt::get(CGF.CGM.Int64Ty, 0)};
8427 MapValuesArrayTy CurCounts = {llvm::ConstantInt::get(CGF.CGM.Int64Ty, 1)};
8428 MapValuesArrayTy CurStrides;
8429 MapValuesArrayTy DimSizes{llvm::ConstantInt::get(CGF.CGM.Int64Ty, 1)};
8430 uint64_t ElementTypeSize;
8431
8432 // Collect Size information for each dimension and get the element size as
8433 // the first Stride. For example, for `int arr[10][10]`, the DimSizes
8434 // should be [10, 10] and the first stride is 4 btyes.
8435 for (const OMPClauseMappableExprCommon::MappableComponent &Component :
8436 Components) {
8437 const Expr *AssocExpr = Component.getAssociatedExpression();
8438 const auto *OASE = dyn_cast<ArraySectionExpr>(AssocExpr);
8439
8440 if (!OASE)
8441 continue;
8442
8443 QualType Ty = ArraySectionExpr::getBaseOriginalType(OASE->getBase());
8444 auto *CAT = Context.getAsConstantArrayType(Ty);
8445 auto *VAT = Context.getAsVariableArrayType(Ty);
8446
8447 // We need all the dimension size except for the last dimension.
8448 assert((VAT || CAT || &Component == &*Components.begin()) &&
8449 "Should be either ConstantArray or VariableArray if not the "
8450 "first Component");
8451
8452 // Get element size if CurStrides is empty.
8453 if (CurStrides.empty()) {
8454 const Type *ElementType = nullptr;
8455 if (CAT)
8456 ElementType = CAT->getElementType().getTypePtr();
8457 else if (VAT)
8458 ElementType = VAT->getElementType().getTypePtr();
8459 else if (&Component == &*Components.begin()) {
8460 // If the base is a raw pointer (e.g. T *data with data[a:b:c]),
8461 // there was no earlier CAT/VAT/array handling to establish
8462 // ElementType. Capture the pointee type now so that subsequent
8463 // components (offset/length/stride) have a concrete element type to
8464 // work with. This makes pointer-backed sections behave consistently
8465 // with CAT/VAT/array bases.
8466 if (const auto *PtrType = Ty->getAs<PointerType>())
8467 ElementType = PtrType->getPointeeType().getTypePtr();
8468 } else {
8469 // Any component after the first should never have a raw pointer type;
8470 // by this point. ElementType must already be known (set above or in
8471 // prior array / CAT / VAT handling).
8472 assert(!Ty->isPointerType() &&
8473 "Non-first components should not be raw pointers");
8474 }
8475
8476 // At this stage, if ElementType was a base pointer and we are in the
8477 // first iteration, it has been computed.
8478 if (ElementType) {
8479 // For the case that having pointer as base, we need to remove one
8480 // level of indirection.
8481 if (&Component != &*Components.begin())
8482 ElementType = ElementType->getPointeeOrArrayElementType();
8483 ElementTypeSize =
8484 Context.getTypeSizeInChars(ElementType).getQuantity();
8485 CurStrides.push_back(
8486 llvm::ConstantInt::get(CGF.Int64Ty, ElementTypeSize));
8487 }
8488 }
8489 // Get dimension value except for the last dimension since we don't need
8490 // it.
8491 if (DimSizes.size() < Components.size() - 1) {
8492 if (CAT)
8493 DimSizes.push_back(
8494 llvm::ConstantInt::get(CGF.Int64Ty, CAT->getZExtSize()));
8495 else if (VAT)
8496 DimSizes.push_back(CGF.Builder.CreateIntCast(
8497 CGF.EmitScalarExpr(VAT->getSizeExpr()), CGF.Int64Ty,
8498 /*IsSigned=*/false));
8499 }
8500 }
8501
8502 // Skip the dummy dimension since we have already have its information.
8503 auto *DI = DimSizes.begin() + 1;
8504 // Product of dimension.
8505 llvm::Value *DimProd =
8506 llvm::ConstantInt::get(CGF.CGM.Int64Ty, ElementTypeSize);
8507
8508 // Collect info for non-contiguous. Notice that offset, count, and stride
8509 // are only meaningful for array-section, so we insert a null for anything
8510 // other than array-section.
8511 // Also, the size of offset, count, and stride are not the same as
8512 // pointers, base_pointers, sizes, or dims. Instead, the size of offset,
8513 // count, and stride are the same as the number of non-contiguous
8514 // declaration in target update to/from clause.
8515 for (const OMPClauseMappableExprCommon::MappableComponent &Component :
8516 Components) {
8517 const Expr *AssocExpr = Component.getAssociatedExpression();
8518
8519 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr)) {
8520 llvm::Value *Offset = CGF.Builder.CreateIntCast(
8521 CGF.EmitScalarExpr(AE->getIdx()), CGF.Int64Ty,
8522 /*isSigned=*/false);
8523 CurOffsets.push_back(Offset);
8524 CurCounts.push_back(llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/1));
8525 CurStrides.push_back(CurStrides.back());
8526 continue;
8527 }
8528
8529 const auto *OASE = dyn_cast<ArraySectionExpr>(AssocExpr);
8530
8531 if (!OASE)
8532 continue;
8533
8534 // Offset
8535 const Expr *OffsetExpr = OASE->getLowerBound();
8536 llvm::Value *Offset = nullptr;
8537 if (!OffsetExpr) {
8538 // If offset is absent, then we just set it to zero.
8539 Offset = llvm::ConstantInt::get(CGF.Int64Ty, 0);
8540 } else {
8541 Offset = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(OffsetExpr),
8542 CGF.Int64Ty,
8543 /*isSigned=*/false);
8544 }
8545 CurOffsets.push_back(Offset);
8546
8547 // Count
8548 const Expr *CountExpr = OASE->getLength();
8549 llvm::Value *Count = nullptr;
8550 if (!CountExpr) {
8551 // In Clang, once a high dimension is an array section, we construct all
8552 // the lower dimension as array section, however, for case like
8553 // arr[0:2][2], Clang construct the inner dimension as an array section
8554 // but it actually is not in an array section form according to spec.
8555 if (!OASE->getColonLocFirst().isValid() &&
8556 !OASE->getColonLocSecond().isValid()) {
8557 Count = llvm::ConstantInt::get(CGF.Int64Ty, 1);
8558 } else {
8559 // OpenMP 5.0, 2.1.5 Array Sections, Description.
8560 // When the length is absent it defaults to ⌈(size −
8561 // lower-bound)/stride⌉, where size is the size of the array
8562 // dimension.
8563 const Expr *StrideExpr = OASE->getStride();
8564 llvm::Value *Stride =
8565 StrideExpr
8566 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(StrideExpr),
8567 CGF.Int64Ty, /*isSigned=*/false)
8568 : nullptr;
8569 if (Stride)
8570 Count = CGF.Builder.CreateUDiv(
8571 CGF.Builder.CreateNUWSub(*DI, Offset), Stride);
8572 else
8573 Count = CGF.Builder.CreateNUWSub(*DI, Offset);
8574 }
8575 } else {
8576 Count = CGF.EmitScalarExpr(CountExpr);
8577 }
8578 Count = CGF.Builder.CreateIntCast(Count, CGF.Int64Ty, /*isSigned=*/false);
8579 CurCounts.push_back(Count);
8580
8581 // Stride_n' = Stride_n * (D_0 * D_1 ... * D_n-1) * Unit size
8582 // Take `int arr[5][5][5]` and `arr[0:2:2][1:2:1][0:2:2]` as an example:
8583 // Offset Count Stride
8584 // D0 0 1 4 (int) <- dummy dimension
8585 // D1 0 2 8 (2 * (1) * 4)
8586 // D2 1 2 20 (1 * (1 * 5) * 4)
8587 // D3 0 2 200 (2 * (1 * 5 * 4) * 4)
8588 const Expr *StrideExpr = OASE->getStride();
8589 llvm::Value *Stride =
8590 StrideExpr
8591 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(StrideExpr),
8592 CGF.Int64Ty, /*isSigned=*/false)
8593 : nullptr;
8594 DimProd = CGF.Builder.CreateNUWMul(DimProd, *(DI - 1));
8595 if (Stride)
8596 CurStrides.push_back(CGF.Builder.CreateNUWMul(DimProd, Stride));
8597 else
8598 CurStrides.push_back(DimProd);
8599 if (DI != DimSizes.end())
8600 ++DI;
8601 }
8602
8603 CombinedInfo.NonContigInfo.Offsets.push_back(CurOffsets);
8604 CombinedInfo.NonContigInfo.Counts.push_back(CurCounts);
8605 CombinedInfo.NonContigInfo.Strides.push_back(CurStrides);
8606 }
8607
8608 /// Return the adjusted map modifiers if the declaration a capture refers to
8609 /// appears in a first-private clause. This is expected to be used only with
8610 /// directives that start with 'target'.
8611 OpenMPOffloadMappingFlags
8612 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
8613 assert(Cap.capturesVariable() && "Expected capture by reference only!");
8614
8615 // A first private variable captured by reference will use only the
8616 // 'private ptr' and 'map to' flag. Return the right flags if the captured
8617 // declaration is known as first-private in this handler.
8618 if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
8619 if (Cap.getCapturedVar()->getType()->isAnyPointerType())
8620 return OpenMPOffloadMappingFlags::OMP_MAP_TO |
8621 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
8622 return OpenMPOffloadMappingFlags::OMP_MAP_PRIVATE |
8623 OpenMPOffloadMappingFlags::OMP_MAP_TO;
8624 }
8625 auto I = LambdasMap.find(Cap.getCapturedVar()->getCanonicalDecl());
8626 if (I != LambdasMap.end())
8627 // for map(to: lambda): using user specified map type.
8628 return getMapTypeBits(
8629 I->getSecond()->getMapType(), I->getSecond()->getMapTypeModifiers(),
8630 /*MotionModifiers=*/{}, I->getSecond()->isImplicit(),
8631 /*AddPtrFlag=*/false,
8632 /*AddIsTargetParamFlag=*/false,
8633 /*isNonContiguous=*/false);
8634 return OpenMPOffloadMappingFlags::OMP_MAP_TO |
8635 OpenMPOffloadMappingFlags::OMP_MAP_FROM;
8636 }
8637
8638 void getPlainLayout(const CXXRecordDecl *RD,
8639 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
8640 bool AsBase) const {
8641 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
8642
8643 llvm::StructType *St =
8644 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
8645
8646 unsigned NumElements = St->getNumElements();
8647 llvm::SmallVector<
8648 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
8649 RecordLayout(NumElements);
8650
8651 // Fill bases.
8652 for (const auto &I : RD->bases()) {
8653 if (I.isVirtual())
8654 continue;
8655
8656 QualType BaseTy = I.getType();
8657 const auto *Base = BaseTy->getAsCXXRecordDecl();
8658 // Ignore empty bases.
8659 if (isEmptyRecordForLayout(CGF.getContext(), BaseTy) ||
8660 CGF.getContext()
8661 .getASTRecordLayout(Base)
8662 .getNonVirtualSize()
8663 .isZero())
8664 continue;
8665
8666 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
8667 RecordLayout[FieldIndex] = Base;
8668 }
8669 // Fill in virtual bases.
8670 for (const auto &I : RD->vbases()) {
8671 QualType BaseTy = I.getType();
8672 // Ignore empty bases.
8673 if (isEmptyRecordForLayout(CGF.getContext(), BaseTy))
8674 continue;
8675
8676 const auto *Base = BaseTy->getAsCXXRecordDecl();
8677 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
8678 if (RecordLayout[FieldIndex])
8679 continue;
8680 RecordLayout[FieldIndex] = Base;
8681 }
8682 // Fill in all the fields.
8683 assert(!RD->isUnion() && "Unexpected union.");
8684 for (const auto *Field : RD->fields()) {
8685 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
8686 // will fill in later.)
8687 if (!Field->isBitField() &&
8688 !isEmptyFieldForLayout(CGF.getContext(), Field)) {
8689 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
8690 RecordLayout[FieldIndex] = Field;
8691 }
8692 }
8693 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
8694 &Data : RecordLayout) {
8695 if (Data.isNull())
8696 continue;
8697 if (const auto *Base = dyn_cast<const CXXRecordDecl *>(Data))
8698 getPlainLayout(Base, Layout, /*AsBase=*/true);
8699 else
8700 Layout.push_back(cast<const FieldDecl *>(Data));
8701 }
8702 }
8703
8704 /// Returns the address corresponding to \p PointerExpr.
8705 static Address getAttachPtrAddr(const Expr *PointerExpr,
8706 CodeGenFunction &CGF) {
8707 assert(PointerExpr && "Cannot get addr from null attach-ptr expr");
8708 Address AttachPtrAddr = Address::invalid();
8709
8710 if (auto *DRE = dyn_cast<DeclRefExpr>(PointerExpr)) {
8711 // If the pointer is a variable, we can use its address directly.
8712 AttachPtrAddr = CGF.EmitLValue(DRE).getAddress();
8713 } else if (auto *OASE = dyn_cast<ArraySectionExpr>(PointerExpr)) {
8714 AttachPtrAddr =
8715 CGF.EmitArraySectionExpr(OASE, /*IsLowerBound=*/true).getAddress();
8716 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(PointerExpr)) {
8717 AttachPtrAddr = CGF.EmitLValue(ASE).getAddress();
8718 } else if (auto *ME = dyn_cast<MemberExpr>(PointerExpr)) {
8719 AttachPtrAddr = CGF.EmitMemberExpr(ME).getAddress();
8720 } else if (auto *UO = dyn_cast<UnaryOperator>(PointerExpr)) {
8721 assert(UO->getOpcode() == UO_Deref &&
8722 "Unexpected unary-operator on attach-ptr-expr");
8723 AttachPtrAddr = CGF.EmitLValue(UO).getAddress();
8724 }
8725 assert(AttachPtrAddr.isValid() &&
8726 "Failed to get address for attach pointer expression");
8727 return AttachPtrAddr;
8728 }
8729
8730 /// Get the address of the attach pointer, and a load from it, to get the
8731 /// pointee base address.
8732 /// \return A pair containing AttachPtrAddr and AttachPteeBaseAddr. The pair
8733 /// contains invalid addresses if \p AttachPtrExpr is null.
8734 static std::pair<Address, Address>
8735 getAttachPtrAddrAndPteeBaseAddr(const Expr *AttachPtrExpr,
8736 CodeGenFunction &CGF) {
8737
8738 if (!AttachPtrExpr)
8739 return {Address::invalid(), Address::invalid()};
8740
8741 Address AttachPtrAddr = getAttachPtrAddr(AttachPtrExpr, CGF);
8742 assert(AttachPtrAddr.isValid() && "Invalid attach pointer addr");
8743
8744 QualType AttachPtrType =
8745 OMPClauseMappableExprCommon::getComponentExprElementType(AttachPtrExpr)
8746 .getCanonicalType();
8747
8748 Address AttachPteeBaseAddr = CGF.EmitLoadOfPointer(
8749 AttachPtrAddr, AttachPtrType->castAs<PointerType>());
8750 assert(AttachPteeBaseAddr.isValid() && "Invalid attach pointee base addr");
8751
8752 return {AttachPtrAddr, AttachPteeBaseAddr};
8753 }
8754
8755 /// Returns whether an attach entry should be emitted for a map on
8756 /// \p MapBaseDecl on the directive \p CurDir.
8757 static bool
8758 shouldEmitAttachEntry(const Expr *PointerExpr, const ValueDecl *MapBaseDecl,
8759 CodeGenFunction &CGF,
8760 llvm::PointerUnion<const OMPExecutableDirective *,
8761 const OMPDeclareMapperDecl *>
8762 CurDir) {
8763 if (!PointerExpr)
8764 return false;
8765
8766 // Pointer attachment is needed at map-entering time or for declare
8767 // mappers.
8768 return isa<const OMPDeclareMapperDecl *>(CurDir) ||
8769 isOpenMPTargetMapEnteringDirective(
8770 cast<const OMPExecutableDirective *>(CurDir)
8771 ->getDirectiveKind());
8772 }
8773
8774 /// Computes the attach-ptr expr for \p Components, and updates various maps
8775 /// with the information.
8776 /// It internally calls OMPClauseMappableExprCommon::findAttachPtrExpr()
8777 /// with the OpenMPDirectiveKind extracted from \p CurDir.
8778 /// It updates AttachPtrComputationOrderMap, AttachPtrComponentDepthMap, and
8779 /// AttachPtrExprMap.
8780 void collectAttachPtrExprInfo(
8781 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
8782 llvm::PointerUnion<const OMPExecutableDirective *,
8783 const OMPDeclareMapperDecl *>
8784 CurDir) {
8785
8786 OpenMPDirectiveKind CurDirectiveID =
8787 isa<const OMPDeclareMapperDecl *>(CurDir)
8788 ? OMPD_declare_mapper
8789 : cast<const OMPExecutableDirective *>(CurDir)->getDirectiveKind();
8790
8791 const auto &[AttachPtrExpr, Depth] =
8792 OMPClauseMappableExprCommon::findAttachPtrExpr(Components,
8793 CurDirectiveID);
8794
8795 AttachPtrComputationOrderMap.try_emplace(
8796 AttachPtrExpr, AttachPtrComputationOrderMap.size());
8797 AttachPtrComponentDepthMap.try_emplace(AttachPtrExpr, Depth);
8798 AttachPtrExprMap.try_emplace(Components, AttachPtrExpr);
8799 }
8800
8801 /// Generate all the base pointers, section pointers, sizes, map types, and
8802 /// mappers for the extracted mappable expressions (all included in \a
8803 /// CombinedInfo). Also, for each item that relates with a device pointer, a
8804 /// pair of the relevant declaration and index where it occurs is appended to
8805 /// the device pointers info array.
8806 void generateAllInfoForClauses(
8807 ArrayRef<const OMPClause *> Clauses, MapCombinedInfoTy &CombinedInfo,
8808 llvm::OpenMPIRBuilder &OMPBuilder,
8809 const llvm::DenseSet<CanonicalDeclPtr<const Decl>> &SkipVarSet =
8810 llvm::DenseSet<CanonicalDeclPtr<const Decl>>()) const {
8811 // We have to process the component lists that relate with the same
8812 // declaration in a single chunk so that we can generate the map flags
8813 // correctly. Therefore, we organize all lists in a map.
8814 enum MapKind { Present, Allocs, Other, Total };
8815 llvm::MapVector<CanonicalDeclPtr<const Decl>,
8816 SmallVector<SmallVector<MapInfo, 8>, 4>>
8817 Info;
8818
8819 // Helper function to fill the information map for the different supported
8820 // clauses.
8821 auto &&InfoGen =
8822 [&Info, &SkipVarSet](
8823 const ValueDecl *D, MapKind Kind,
8824 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
8825 OpenMPMapClauseKind MapType,
8826 ArrayRef<OpenMPMapModifierKind> MapModifiers,
8827 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
8828 bool ReturnDevicePointer, bool IsImplicit, const ValueDecl *Mapper,
8829 const Expr *VarRef = nullptr, bool ForDeviceAddr = false) {
8830 if (SkipVarSet.contains(D))
8831 return;
8832 auto It = Info.try_emplace(D, Total).first;
8833 It->second[Kind].emplace_back(
8834 L, MapType, MapModifiers, MotionModifiers, ReturnDevicePointer,
8835 IsImplicit, Mapper, VarRef, ForDeviceAddr);
8836 };
8837
8838 for (const auto *Cl : Clauses) {
8839 const auto *C = dyn_cast<OMPMapClause>(Cl);
8840 if (!C)
8841 continue;
8842 MapKind Kind = Other;
8843 if (llvm::is_contained(C->getMapTypeModifiers(),
8844 OMPC_MAP_MODIFIER_present))
8845 Kind = Present;
8846 else if (C->getMapType() == OMPC_MAP_alloc)
8847 Kind = Allocs;
8848 const auto *EI = C->getVarRefs().begin();
8849 for (const auto L : C->component_lists()) {
8850 const Expr *E = (C->getMapLoc().isValid()) ? *EI : nullptr;
8851 InfoGen(std::get<0>(L), Kind, std::get<1>(L), C->getMapType(),
8852 C->getMapTypeModifiers(), {},
8853 /*ReturnDevicePointer=*/false, C->isImplicit(), std::get<2>(L),
8854 E);
8855 ++EI;
8856 }
8857 }
8858 for (const auto *Cl : Clauses) {
8859 const auto *C = dyn_cast<OMPToClause>(Cl);
8860 if (!C)
8861 continue;
8862 MapKind Kind = Other;
8863 if (llvm::is_contained(C->getMotionModifiers(),
8864 OMPC_MOTION_MODIFIER_present))
8865 Kind = Present;
8866 if (llvm::is_contained(C->getMotionModifiers(),
8867 OMPC_MOTION_MODIFIER_iterator)) {
8868 if (auto *IteratorExpr = dyn_cast<OMPIteratorExpr>(
8869 C->getIteratorModifier()->IgnoreParenImpCasts())) {
8870 const auto *VD = cast<VarDecl>(IteratorExpr->getIteratorDecl(0));
8871 CGF.EmitVarDecl(*VD);
8872 }
8873 }
8874
8875 const auto *EI = C->getVarRefs().begin();
8876 for (const auto L : C->component_lists()) {
8877 InfoGen(std::get<0>(L), Kind, std::get<1>(L), OMPC_MAP_to, {},
8878 C->getMotionModifiers(), /*ReturnDevicePointer=*/false,
8879 C->isImplicit(), std::get<2>(L), *EI);
8880 ++EI;
8881 }
8882 }
8883 for (const auto *Cl : Clauses) {
8884 const auto *C = dyn_cast<OMPFromClause>(Cl);
8885 if (!C)
8886 continue;
8887 MapKind Kind = Other;
8888 if (llvm::is_contained(C->getMotionModifiers(),
8889 OMPC_MOTION_MODIFIER_present))
8890 Kind = Present;
8891 if (llvm::is_contained(C->getMotionModifiers(),
8892 OMPC_MOTION_MODIFIER_iterator)) {
8893 if (auto *IteratorExpr = dyn_cast<OMPIteratorExpr>(
8894 C->getIteratorModifier()->IgnoreParenImpCasts())) {
8895 const auto *VD = cast<VarDecl>(IteratorExpr->getIteratorDecl(0));
8896 CGF.EmitVarDecl(*VD);
8897 }
8898 }
8899
8900 const auto *EI = C->getVarRefs().begin();
8901 for (const auto L : C->component_lists()) {
8902 InfoGen(std::get<0>(L), Kind, std::get<1>(L), OMPC_MAP_from, {},
8903 C->getMotionModifiers(),
8904 /*ReturnDevicePointer=*/false, C->isImplicit(), std::get<2>(L),
8905 *EI);
8906 ++EI;
8907 }
8908 }
8909
8910 // Look at the use_device_ptr and use_device_addr clauses information and
8911 // mark the existing map entries as such. If there is no map information for
8912 // an entry in the use_device_ptr and use_device_addr list, we create one
8913 // with map type 'return_param' and zero size section. It is the user's
8914 // fault if that was not mapped before. If there is no map information, then
8915 // we defer the emission of that entry until all the maps for the same VD
8916 // have been handled.
8917 MapCombinedInfoTy UseDeviceDataCombinedInfo;
8918
8919 auto &&UseDeviceDataCombinedInfoGen =
8920 [&UseDeviceDataCombinedInfo](const ValueDecl *VD, llvm::Value *Ptr,
8921 CodeGenFunction &CGF, bool IsDevAddr) {
8922 UseDeviceDataCombinedInfo.Exprs.push_back(VD);
8923 UseDeviceDataCombinedInfo.BasePointers.emplace_back(Ptr);
8924 UseDeviceDataCombinedInfo.DevicePtrDecls.emplace_back(VD);
8925 UseDeviceDataCombinedInfo.DevicePointers.emplace_back(
8926 IsDevAddr ? DeviceInfoTy::Address : DeviceInfoTy::Pointer);
8927 // FIXME: For use_device_addr on array-sections, this should
8928 // be the starting address of the section.
8929 // e.g. int *p;
8930 // ... use_device_addr(p[3])
8931 // &p[0], &p[3], /*size=*/0, RETURN_PARAM
8932 UseDeviceDataCombinedInfo.Pointers.push_back(Ptr);
8933 UseDeviceDataCombinedInfo.Sizes.push_back(
8934 llvm::Constant::getNullValue(CGF.Int64Ty));
8935 UseDeviceDataCombinedInfo.Types.push_back(
8936 OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM);
8937 UseDeviceDataCombinedInfo.Mappers.push_back(nullptr);
8938 };
8939
8940 auto &&MapInfoGen =
8941 [&UseDeviceDataCombinedInfoGen](
8942 CodeGenFunction &CGF, const Expr *IE, const ValueDecl *VD,
8943 OMPClauseMappableExprCommon::MappableExprComponentListRef
8944 Components,
8945 bool IsDevAddr, bool IEIsAttachPtrForDevAddr = false) {
8946 // We didn't find any match in our map information - generate a zero
8947 // size array section.
8948 llvm::Value *Ptr;
8949 if (IsDevAddr && !IEIsAttachPtrForDevAddr) {
8950 if (IE->isGLValue())
8951 Ptr = CGF.EmitLValue(IE).getPointer(CGF);
8952 else
8953 Ptr = CGF.EmitScalarExpr(IE);
8954 } else {
8955 Ptr = CGF.EmitLoadOfScalar(CGF.EmitLValue(IE), IE->getExprLoc());
8956 }
8957 bool TreatDevAddrAsDevPtr = IEIsAttachPtrForDevAddr;
8958 // For the purpose of address-translation, treat something like the
8959 // following:
8960 // int *p;
8961 // ... use_device_addr(p[1])
8962 // equivalent to
8963 // ... use_device_ptr(p)
8964 UseDeviceDataCombinedInfoGen(VD, Ptr, CGF, /*IsDevAddr=*/IsDevAddr &&
8965 !TreatDevAddrAsDevPtr);
8966 };
8967
8968 auto &&IsMapInfoExist = [&Info, this](CodeGenFunction &CGF,
8969 const ValueDecl *VD, const Expr *IE,
8970 const Expr *DesiredAttachPtrExpr,
8971 bool IsDevAddr) -> bool {
8972 // We potentially have map information for this declaration already.
8973 // Look for the first set of components that refer to it. If found,
8974 // return true.
8975 // If the first component is a member expression, we have to look into
8976 // 'this', which maps to null in the map of map information. Otherwise
8977 // look directly for the information.
8978 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
8979 if (It != Info.end()) {
8980 bool Found = false;
8981 for (auto &Data : It->second) {
8982 MapInfo *CI = nullptr;
8983 // We potentially have multiple maps for the same decl. We need to
8984 // only consider those for which the attach-ptr matches the desired
8985 // attach-ptr.
8986 auto *It = llvm::find_if(Data, [&](const MapInfo &MI) {
8987 if (MI.Components.back().getAssociatedDeclaration() != VD)
8988 return false;
8989
8990 const Expr *MapAttachPtr = getAttachPtrExpr(MI.Components);
8991 bool Match = AttachPtrComparator.areEqual(MapAttachPtr,
8992 DesiredAttachPtrExpr);
8993 return Match;
8994 });
8995
8996 if (It != Data.end())
8997 CI = &*It;
8998
8999 if (CI) {
9000 if (IsDevAddr) {
9001 CI->ForDeviceAddr = true;
9002 CI->ReturnDevicePointer = true;
9003 Found = true;
9004 break;
9005 } else {
9006 auto PrevCI = std::next(CI->Components.rbegin());
9007 const auto *VarD = dyn_cast<VarDecl>(VD);
9008 const Expr *AttachPtrExpr = getAttachPtrExpr(CI->Components);
9009 if (CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory() ||
9010 isa<MemberExpr>(IE) ||
9011 !VD->getType().getNonReferenceType()->isPointerType() ||
9012 PrevCI == CI->Components.rend() ||
9013 isa<MemberExpr>(PrevCI->getAssociatedExpression()) || !VarD ||
9014 VarD->hasLocalStorage() ||
9015 (isa_and_nonnull<DeclRefExpr>(AttachPtrExpr) &&
9016 VD == cast<DeclRefExpr>(AttachPtrExpr)->getDecl())) {
9017 CI->ForDeviceAddr = IsDevAddr;
9018 CI->ReturnDevicePointer = true;
9019 Found = true;
9020 break;
9021 }
9022 }
9023 }
9024 }
9025 return Found;
9026 }
9027 return false;
9028 };
9029
9030 // Look at the use_device_ptr clause information and mark the existing map
9031 // entries as such. If there is no map information for an entry in the
9032 // use_device_ptr list, we create one with map type 'alloc' and zero size
9033 // section. It is the user fault if that was not mapped before. If there is
9034 // no map information and the pointer is a struct member, then we defer the
9035 // emission of that entry until the whole struct has been processed.
9036 for (const auto *Cl : Clauses) {
9037 const auto *C = dyn_cast<OMPUseDevicePtrClause>(Cl);
9038 if (!C)
9039 continue;
9040 for (const auto L : C->component_lists()) {
9041 OMPClauseMappableExprCommon::MappableExprComponentListRef Components =
9042 std::get<1>(L);
9043 assert(!Components.empty() &&
9044 "Not expecting empty list of components!");
9045 const ValueDecl *VD = Components.back().getAssociatedDeclaration();
9046 VD = cast<ValueDecl>(VD->getCanonicalDecl());
9047 const Expr *IE = Components.back().getAssociatedExpression();
9048 // For use_device_ptr, we match an existing map clause if its attach-ptr
9049 // is same as the use_device_ptr operand. e.g.
9050 // map expr | use_device_ptr expr | current behavior
9051 // ---------|---------------------|-----------------
9052 // p[1] | p | match
9053 // ps->a | ps | match
9054 // p | p | no match
9055 const Expr *UDPOperandExpr =
9056 Components.front().getAssociatedExpression();
9057 if (IsMapInfoExist(CGF, VD, IE,
9058 /*DesiredAttachPtrExpr=*/UDPOperandExpr,
9059 /*IsDevAddr=*/false))
9060 continue;
9061 MapInfoGen(CGF, IE, VD, Components, /*IsDevAddr=*/false);
9062 }
9063 }
9064
9065 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
9066 for (const auto *Cl : Clauses) {
9067 const auto *C = dyn_cast<OMPUseDeviceAddrClause>(Cl);
9068 if (!C)
9069 continue;
9070 for (const auto L : C->component_lists()) {
9071 OMPClauseMappableExprCommon::MappableExprComponentListRef Components =
9072 std::get<1>(L);
9073 assert(!std::get<1>(L).empty() &&
9074 "Not expecting empty list of components!");
9075 const ValueDecl *VD = std::get<1>(L).back().getAssociatedDeclaration();
9076 if (!Processed.insert(VD).second)
9077 continue;
9078 VD = cast<ValueDecl>(VD->getCanonicalDecl());
9079 // For use_device_addr, we match an existing map clause if the
9080 // use_device_addr operand's attach-ptr matches the map operand's
9081 // attach-ptr.
9082 // We chould also restrict to only match cases when there is a full
9083 // match between the map/use_device_addr clause exprs, but that may be
9084 // unnecessary.
9085 //
9086 // map expr | use_device_addr expr | current | possible restrictive/
9087 // | | behavior | safer behavior
9088 // ---------|----------------------|-----------|-----------------------
9089 // p | p | match | match
9090 // p[0] | p[0] | match | match
9091 // p[0:1] | p[0] | match | no match
9092 // p[0:1] | p[2:1] | match | no match
9093 // p[1] | p[0] | match | no match
9094 // ps->a | ps->b | match | no match
9095 // p | p[0] | no match | no match
9096 // pp | pp[0][0] | no match | no match
9097 const Expr *UDAAttachPtrExpr = getAttachPtrExpr(Components);
9098 const Expr *IE = std::get<1>(L).back().getAssociatedExpression();
9099 assert((!UDAAttachPtrExpr || UDAAttachPtrExpr == IE) &&
9100 "use_device_addr operand has an attach-ptr, but does not match "
9101 "last component's expr.");
9102 if (IsMapInfoExist(CGF, VD, IE,
9103 /*DesiredAttachPtrExpr=*/UDAAttachPtrExpr,
9104 /*IsDevAddr=*/true))
9105 continue;
9106 MapInfoGen(CGF, IE, VD, Components,
9107 /*IsDevAddr=*/true,
9108 /*IEIsAttachPtrForDevAddr=*/UDAAttachPtrExpr != nullptr);
9109 }
9110 }
9111
9112 for (const auto &Data : Info) {
9113 MapCombinedInfoTy CurInfo;
9114 const Decl *D = Data.first;
9115 const ValueDecl *VD = cast_or_null<ValueDecl>(D);
9116 // Group component lists by their AttachPtrExpr and process them in order
9117 // of increasing complexity (nullptr first, then simple expressions like
9118 // p, then more complex ones like p[0], etc.)
9119 //
9120 // This is similar to how generateInfoForCaptureFromClauseInfo handles
9121 // grouping for target constructs.
9122 SmallVector<std::pair<const Expr *, MapInfo>, 16> AttachPtrMapInfoPairs;
9123
9124 // First, collect all MapData entries with their attach-ptr exprs.
9125 for (const auto &M : Data.second) {
9126 for (const MapInfo &L : M) {
9127 assert(!L.Components.empty() &&
9128 "Not expecting declaration with no component lists.");
9129
9130 const Expr *AttachPtrExpr = getAttachPtrExpr(L.Components);
9131 AttachPtrMapInfoPairs.emplace_back(AttachPtrExpr, L);
9132 }
9133 }
9134
9135 // Next, sort by increasing order of their complexity.
9136 llvm::stable_sort(AttachPtrMapInfoPairs,
9137 [this](const auto &LHS, const auto &RHS) {
9138 return AttachPtrComparator(LHS.first, RHS.first);
9139 });
9140
9141 // And finally, process them all in order, grouping those with
9142 // equivalent attach-ptr exprs together.
9143 auto *It = AttachPtrMapInfoPairs.begin();
9144 while (It != AttachPtrMapInfoPairs.end()) {
9145 const Expr *AttachPtrExpr = It->first;
9146
9147 SmallVector<MapInfo, 8> GroupLists;
9148 while (It != AttachPtrMapInfoPairs.end() &&
9149 (It->first == AttachPtrExpr ||
9150 AttachPtrComparator.areEqual(It->first, AttachPtrExpr))) {
9151 GroupLists.push_back(It->second);
9152 ++It;
9153 }
9154 assert(!GroupLists.empty() && "GroupLists should not be empty");
9155
9156 StructRangeInfoTy PartialStruct;
9157 AttachInfoTy AttachInfo;
9158 MapCombinedInfoTy GroupCurInfo;
9159 // Current group's struct base information:
9160 MapCombinedInfoTy GroupStructBaseCurInfo;
9161 for (const MapInfo &L : GroupLists) {
9162 // Remember the current base pointer index.
9163 unsigned CurrentBasePointersIdx = GroupCurInfo.BasePointers.size();
9164 unsigned StructBasePointersIdx =
9165 GroupStructBaseCurInfo.BasePointers.size();
9166
9167 GroupCurInfo.NonContigInfo.IsNonContiguous =
9168 L.Components.back().isNonContiguous();
9169 generateInfoForComponentList(
9170 L.MapType, L.MapModifiers, L.MotionModifiers, L.Components,
9171 GroupCurInfo, GroupStructBaseCurInfo, PartialStruct, AttachInfo,
9172 /*IsFirstComponentList=*/false, L.IsImplicit,
9173 /*GenerateAllInfoForClauses*/ true, L.Mapper, L.ForDeviceAddr, VD,
9174 L.VarRef, /*OverlappedElements*/ {});
9175
9176 // If this entry relates to a device pointer, set the relevant
9177 // declaration and add the 'return pointer' flag.
9178 if (L.ReturnDevicePointer) {
9179 // Check whether a value was added to either GroupCurInfo or
9180 // GroupStructBaseCurInfo and error if no value was added to either
9181 // of them:
9182 assert((CurrentBasePointersIdx < GroupCurInfo.BasePointers.size() ||
9183 StructBasePointersIdx <
9184 GroupStructBaseCurInfo.BasePointers.size()) &&
9185 "Unexpected number of mapped base pointers.");
9186
9187 // Choose a base pointer index which is always valid:
9188 const ValueDecl *RelevantVD =
9189 L.Components.back().getAssociatedDeclaration();
9190 assert(RelevantVD &&
9191 "No relevant declaration related with device pointer??");
9192
9193 // If GroupStructBaseCurInfo has been updated this iteration then
9194 // work on the first new entry added to it i.e. make sure that when
9195 // multiple values are added to any of the lists, the first value
9196 // added is being modified by the assignments below (not the last
9197 // value added).
9198 if (StructBasePointersIdx <
9199 GroupStructBaseCurInfo.BasePointers.size()) {
9200 GroupStructBaseCurInfo.DevicePtrDecls[StructBasePointersIdx] =
9201 RelevantVD;
9202 GroupStructBaseCurInfo.DevicePointers[StructBasePointersIdx] =
9203 L.ForDeviceAddr ? DeviceInfoTy::Address
9204 : DeviceInfoTy::Pointer;
9205 GroupStructBaseCurInfo.Types[StructBasePointersIdx] |=
9206 OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
9207 } else {
9208 GroupCurInfo.DevicePtrDecls[CurrentBasePointersIdx] = RelevantVD;
9209 GroupCurInfo.DevicePointers[CurrentBasePointersIdx] =
9210 L.ForDeviceAddr ? DeviceInfoTy::Address
9211 : DeviceInfoTy::Pointer;
9212 GroupCurInfo.Types[CurrentBasePointersIdx] |=
9213 OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
9214 }
9215 }
9216 }
9217
9218 // Unify entries in one list making sure the struct mapping precedes the
9219 // individual fields:
9220 MapCombinedInfoTy GroupUnionCurInfo;
9221 GroupUnionCurInfo.append(GroupStructBaseCurInfo);
9222 GroupUnionCurInfo.append(GroupCurInfo);
9223
9224 // If there is an entry in PartialStruct it means we have a struct with
9225 // individual members mapped. Emit an extra combined entry.
9226 if (PartialStruct.Base.isValid()) {
9227 // Prepend a synthetic dimension of length 1 to represent the
9228 // aggregated struct object. Using 1 (not 0, as 0 produced an
9229 // incorrect non-contiguous descriptor (DimSize==1), causing the
9230 // non-contiguous motion clause path to be skipped.) is important:
9231 // * It preserves the correct rank so targetDataUpdate() computes
9232 // DimSize == 2 for cases like strided array sections originating
9233 // from user-defined mappers (e.g. test with s.data[0:8:2]).
9234 GroupUnionCurInfo.NonContigInfo.Dims.insert(
9235 GroupUnionCurInfo.NonContigInfo.Dims.begin(), 1);
9236 emitCombinedEntry(
9237 CurInfo, GroupUnionCurInfo.Types, PartialStruct, AttachInfo,
9238 /*IsMapThis=*/!VD, OMPBuilder, VD,
9239 /*OffsetForMemberOfFlag=*/CombinedInfo.BasePointers.size(),
9240 /*NotTargetParams=*/true);
9241 }
9242
9243 // Append this group's results to the overall CurInfo in the correct
9244 // order: combined-entry -> original-field-entries -> attach-entry
9245 CurInfo.append(GroupUnionCurInfo);
9246 if (AttachInfo.isValid())
9247 emitAttachEntry(CGF, CurInfo, AttachInfo);
9248 }
9249
9250 // We need to append the results of this capture to what we already have.
9251 CombinedInfo.append(CurInfo);
9252 }
9253 // Append data for use_device_ptr/addr clauses.
9254 CombinedInfo.append(UseDeviceDataCombinedInfo);
9255 }
9256
9257 public:
9258 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
9259 : CurDir(&Dir), CGF(CGF), AttachPtrComparator(*this) {
9260 // Extract firstprivate clause information.
9261 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
9262 for (const auto *D : C->varlist())
9263 FirstPrivateDecls.try_emplace(
9264 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl()), C->isImplicit());
9265 // Extract implicit firstprivates from uses_allocators clauses.
9266 for (const auto *C : Dir.getClausesOfKind<OMPUsesAllocatorsClause>()) {
9267 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
9268 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
9269 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(D.AllocatorTraits))
9270 FirstPrivateDecls.try_emplace(cast<VarDecl>(DRE->getDecl()),
9271 /*Implicit=*/true);
9272 else if (const auto *VD = dyn_cast<VarDecl>(
9273 cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts())
9274 ->getDecl()))
9275 FirstPrivateDecls.try_emplace(VD, /*Implicit=*/true);
9276 }
9277 }
9278 // Extract defaultmap clause information.
9279 for (const auto *C : Dir.getClausesOfKind<OMPDefaultmapClause>())
9280 if (C->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_firstprivate)
9281 DefaultmapFirstprivateKinds.insert(C->getDefaultmapKind());
9282 // Extract device pointer clause information.
9283 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
9284 for (auto L : C->component_lists())
9285 DevPointersMap[std::get<0>(L)].push_back(std::get<1>(L));
9286 // Extract device addr clause information.
9287 for (const auto *C : Dir.getClausesOfKind<OMPHasDeviceAddrClause>())
9288 for (auto L : C->component_lists())
9289 HasDevAddrsMap[std::get<0>(L)].push_back(std::get<1>(L));
9290 // Extract map information.
9291 for (const auto *C : Dir.getClausesOfKind<OMPMapClause>()) {
9292 if (C->getMapType() != OMPC_MAP_to)
9293 continue;
9294 for (auto L : C->component_lists()) {
9295 const ValueDecl *VD = std::get<0>(L);
9296 const auto *RD = VD ? VD->getType()
9297 .getCanonicalType()
9298 .getNonReferenceType()
9299 ->getAsCXXRecordDecl()
9300 : nullptr;
9301 if (RD && RD->isLambda())
9302 LambdasMap.try_emplace(std::get<0>(L), C);
9303 }
9304 }
9305
9306 auto CollectAttachPtrExprsForClauseComponents = [this](const auto *C) {
9307 for (auto L : C->component_lists()) {
9308 OMPClauseMappableExprCommon::MappableExprComponentListRef Components =
9309 std::get<1>(L);
9310 if (!Components.empty())
9311 collectAttachPtrExprInfo(Components, CurDir);
9312 }
9313 };
9314
9315 // Populate the AttachPtrExprMap for all component lists from map-related
9316 // clauses.
9317 for (const auto *C : Dir.getClausesOfKind<OMPMapClause>())
9318 CollectAttachPtrExprsForClauseComponents(C);
9319 for (const auto *C : Dir.getClausesOfKind<OMPToClause>())
9320 CollectAttachPtrExprsForClauseComponents(C);
9321 for (const auto *C : Dir.getClausesOfKind<OMPFromClause>())
9322 CollectAttachPtrExprsForClauseComponents(C);
9323 for (const auto *C : Dir.getClausesOfKind<OMPUseDevicePtrClause>())
9324 CollectAttachPtrExprsForClauseComponents(C);
9325 for (const auto *C : Dir.getClausesOfKind<OMPUseDeviceAddrClause>())
9326 CollectAttachPtrExprsForClauseComponents(C);
9327 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
9328 CollectAttachPtrExprsForClauseComponents(C);
9329 for (const auto *C : Dir.getClausesOfKind<OMPHasDeviceAddrClause>())
9330 CollectAttachPtrExprsForClauseComponents(C);
9331 }
9332
9333 /// Constructor for the declare mapper directive.
9334 MappableExprsHandler(const OMPDeclareMapperDecl &Dir, CodeGenFunction &CGF)
9335 : CurDir(&Dir), CGF(CGF), AttachPtrComparator(*this) {}
9336
9337 /// Generate code for the combined entry if we have a partially mapped struct
9338 /// and take care of the mapping flags of the arguments corresponding to
9339 /// individual struct members.
9340 /// If a valid \p AttachInfo exists, its pointee addr will be updated to point
9341 /// to the combined-entry's begin address, if emitted.
9342 /// \p PartialStruct contains attach base-pointer information.
9343 /// \returns The index of the combined entry if one was added, std::nullopt
9344 /// otherwise.
9345 void emitCombinedEntry(MapCombinedInfoTy &CombinedInfo,
9346 MapFlagsArrayTy &CurTypes,
9347 const StructRangeInfoTy &PartialStruct,
9348 AttachInfoTy &AttachInfo, bool IsMapThis,
9349 llvm::OpenMPIRBuilder &OMPBuilder, const ValueDecl *VD,
9350 unsigned OffsetForMemberOfFlag,
9351 bool NotTargetParams) const {
9352 if (CurTypes.size() == 1 &&
9353 ((CurTypes.back() & OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) !=
9354 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) &&
9355 !PartialStruct.IsArraySection)
9356 return;
9357 Address LBAddr = PartialStruct.LowestElem.second;
9358 Address HBAddr = PartialStruct.HighestElem.second;
9359 if (PartialStruct.HasCompleteRecord) {
9360 LBAddr = PartialStruct.LB;
9361 HBAddr = PartialStruct.LB;
9362 }
9363 CombinedInfo.Exprs.push_back(VD);
9364 // Base is the base of the struct
9365 CombinedInfo.BasePointers.push_back(PartialStruct.Base.emitRawPointer(CGF));
9366 CombinedInfo.DevicePtrDecls.push_back(nullptr);
9367 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
9368 // Pointer is the address of the lowest element
9369 llvm::Value *LB = LBAddr.emitRawPointer(CGF);
9370 const CXXMethodDecl *MD =
9371 CGF.CurFuncDecl ? dyn_cast<CXXMethodDecl>(CGF.CurFuncDecl) : nullptr;
9372 const CXXRecordDecl *RD = MD ? MD->getParent() : nullptr;
9373 bool HasBaseClass = RD && IsMapThis ? RD->getNumBases() > 0 : false;
9374 // There should not be a mapper for a combined entry.
9375 if (HasBaseClass) {
9376 // OpenMP 5.2 148:21:
9377 // If the target construct is within a class non-static member function,
9378 // and a variable is an accessible data member of the object for which the
9379 // non-static data member function is invoked, the variable is treated as
9380 // if the this[:1] expression had appeared in a map clause with a map-type
9381 // of tofrom.
9382 // Emit this[:1]
9383 CombinedInfo.Pointers.push_back(PartialStruct.Base.emitRawPointer(CGF));
9384 QualType Ty = MD->getFunctionObjectParameterType();
9385 llvm::Value *Size =
9386 CGF.Builder.CreateIntCast(CGF.getTypeSize(Ty), CGF.Int64Ty,
9387 /*isSigned=*/true);
9388 CombinedInfo.Sizes.push_back(Size);
9389 } else {
9390 CombinedInfo.Pointers.push_back(LB);
9391 // Size is (addr of {highest+1} element) - (addr of lowest element)
9392 llvm::Value *HB = HBAddr.emitRawPointer(CGF);
9393 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(
9394 HBAddr.getElementType(), HB, /*Idx0=*/1);
9395 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
9396 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
9397 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CGF.Int8Ty, CHAddr, CLAddr);
9398 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.Int64Ty,
9399 /*isSigned=*/false);
9400 CombinedInfo.Sizes.push_back(Size);
9401 }
9402 CombinedInfo.Mappers.push_back(nullptr);
9403 // Map type is always TARGET_PARAM, if generate info for captures.
9404 CombinedInfo.Types.push_back(
9405 NotTargetParams ? OpenMPOffloadMappingFlags::OMP_MAP_NONE
9406 : !PartialStruct.PreliminaryMapData.BasePointers.empty()
9407 ? OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ
9408 : OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM);
9409 // If any element has the present modifier, then make sure the runtime
9410 // doesn't attempt to allocate the struct.
9411 if (CurTypes.end() !=
9412 llvm::find_if(CurTypes, [](OpenMPOffloadMappingFlags Type) {
9413 return static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
9414 Type & OpenMPOffloadMappingFlags::OMP_MAP_PRESENT);
9415 }))
9416 CombinedInfo.Types.back() |= OpenMPOffloadMappingFlags::OMP_MAP_PRESENT;
9417 // Remove TARGET_PARAM flag from the first element
9418 (*CurTypes.begin()) &= ~OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
9419 // If any element has the ompx_hold modifier, then make sure the runtime
9420 // uses the hold reference count for the struct as a whole so that it won't
9421 // be unmapped by an extra dynamic reference count decrement. Add it to all
9422 // elements as well so the runtime knows which reference count to check
9423 // when determining whether it's time for device-to-host transfers of
9424 // individual elements.
9425 if (CurTypes.end() !=
9426 llvm::find_if(CurTypes, [](OpenMPOffloadMappingFlags Type) {
9427 return static_cast<std::underlying_type_t<OpenMPOffloadMappingFlags>>(
9428 Type & OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD);
9429 })) {
9430 CombinedInfo.Types.back() |= OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
9431 for (auto &M : CurTypes)
9432 M |= OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
9433 }
9434
9435 // All other current entries will be MEMBER_OF the combined entry
9436 // (except for PTR_AND_OBJ entries which do not have a placeholder value
9437 // 0xFFFF in the MEMBER_OF field, or ATTACH entries since they are expected
9438 // to be handled by themselves, after all other maps).
9439 OpenMPOffloadMappingFlags MemberOfFlag = OMPBuilder.getMemberOfFlag(
9440 OffsetForMemberOfFlag + CombinedInfo.BasePointers.size() - 1);
9441 for (auto &M : CurTypes)
9442 OMPBuilder.setCorrectMemberOfFlag(M, MemberOfFlag);
9443
9444 // When we are emitting a combined entry. If there were any pending
9445 // attachments to be done, we do them to the begin address of the combined
9446 // entry. Note that this means only one attachment per combined-entry will
9447 // be done. So, for instance, if we have:
9448 // S *ps;
9449 // ... map(ps->a, ps->b)
9450 // When we are emitting a combined entry. If AttachInfo is valid,
9451 // update the pointee address to point to the begin address of the combined
9452 // entry. This ensures that if we have multiple maps like:
9453 // `map(ps->a, ps->b)`, we still get a single ATTACH entry, like:
9454 //
9455 // &ps[0], &ps->a, sizeof(ps->a to ps->b), ALLOC // combined-entry
9456 // &ps[0], &ps->a, sizeof(ps->a), TO | FROM
9457 // &ps[0], &ps->b, sizeof(ps->b), TO | FROM
9458 // &ps, &ps->a, sizeof(void*), ATTACH // Use combined-entry's LB
9459 if (AttachInfo.isValid())
9460 AttachInfo.AttachPteeAddr = LBAddr;
9461 }
9462
9463 /// Generate all the base pointers, section pointers, sizes, map types, and
9464 /// mappers for the extracted mappable expressions (all included in \a
9465 /// CombinedInfo). Also, for each item that relates with a device pointer, a
9466 /// pair of the relevant declaration and index where it occurs is appended to
9467 /// the device pointers info array.
9468 void generateAllInfo(
9469 MapCombinedInfoTy &CombinedInfo, llvm::OpenMPIRBuilder &OMPBuilder,
9470 const llvm::DenseSet<CanonicalDeclPtr<const Decl>> &SkipVarSet =
9471 llvm::DenseSet<CanonicalDeclPtr<const Decl>>()) const {
9472 assert(isa<const OMPExecutableDirective *>(CurDir) &&
9473 "Expect a executable directive");
9474 const auto *CurExecDir = cast<const OMPExecutableDirective *>(CurDir);
9475 generateAllInfoForClauses(CurExecDir->clauses(), CombinedInfo, OMPBuilder,
9476 SkipVarSet);
9477 }
9478
9479 /// Generate all the base pointers, section pointers, sizes, map types, and
9480 /// mappers for the extracted map clauses of user-defined mapper (all included
9481 /// in \a CombinedInfo).
9482 void generateAllInfoForMapper(MapCombinedInfoTy &CombinedInfo,
9483 llvm::OpenMPIRBuilder &OMPBuilder) const {
9484 assert(isa<const OMPDeclareMapperDecl *>(CurDir) &&
9485 "Expect a declare mapper directive");
9486 const auto *CurMapperDir = cast<const OMPDeclareMapperDecl *>(CurDir);
9487 generateAllInfoForClauses(CurMapperDir->clauses(), CombinedInfo,
9488 OMPBuilder);
9489 }
9490
9491 /// Emit capture info for lambdas for variables captured by reference.
9492 void generateInfoForLambdaCaptures(
9493 const ValueDecl *VD, llvm::Value *Arg, MapCombinedInfoTy &CombinedInfo,
9494 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
9495 QualType VDType = VD->getType().getCanonicalType().getNonReferenceType();
9496 const auto *RD = VDType->getAsCXXRecordDecl();
9497 if (!RD || !RD->isLambda())
9498 return;
9499 Address VDAddr(Arg, CGF.ConvertTypeForMem(VDType),
9500 CGF.getContext().getDeclAlign(VD));
9501 LValue VDLVal = CGF.MakeAddrLValue(VDAddr, VDType);
9502 llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
9503 FieldDecl *ThisCapture = nullptr;
9504 RD->getCaptureFields(Captures, ThisCapture);
9505 if (ThisCapture) {
9506 LValue ThisLVal =
9507 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
9508 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
9509 LambdaPointers.try_emplace(ThisLVal.getPointer(CGF),
9510 VDLVal.getPointer(CGF));
9511 CombinedInfo.Exprs.push_back(VD);
9512 CombinedInfo.BasePointers.push_back(ThisLVal.getPointer(CGF));
9513 CombinedInfo.DevicePtrDecls.push_back(nullptr);
9514 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
9515 CombinedInfo.Pointers.push_back(ThisLValVal.getPointer(CGF));
9516 CombinedInfo.Sizes.push_back(
9517 CGF.Builder.CreateIntCast(CGF.getTypeSize(CGF.getContext().VoidPtrTy),
9518 CGF.Int64Ty, /*isSigned=*/true));
9519 CombinedInfo.Types.push_back(
9520 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ |
9521 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
9522 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF |
9523 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT);
9524 CombinedInfo.Mappers.push_back(nullptr);
9525 }
9526 for (const LambdaCapture &LC : RD->captures()) {
9527 if (!LC.capturesVariable())
9528 continue;
9529 const VarDecl *VD = cast<VarDecl>(LC.getCapturedVar());
9530 if (LC.getCaptureKind() != LCK_ByRef && !VD->getType()->isPointerType())
9531 continue;
9532 auto It = Captures.find(VD);
9533 assert(It != Captures.end() && "Found lambda capture without field.");
9534 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
9535 if (LC.getCaptureKind() == LCK_ByRef) {
9536 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
9537 LambdaPointers.try_emplace(VarLVal.getPointer(CGF),
9538 VDLVal.getPointer(CGF));
9539 CombinedInfo.Exprs.push_back(VD);
9540 CombinedInfo.BasePointers.push_back(VarLVal.getPointer(CGF));
9541 CombinedInfo.DevicePtrDecls.push_back(nullptr);
9542 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
9543 CombinedInfo.Pointers.push_back(VarLValVal.getPointer(CGF));
9544 CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
9545 CGF.getTypeSize(
9546 VD->getType().getCanonicalType().getNonReferenceType()),
9547 CGF.Int64Ty, /*isSigned=*/true));
9548 } else {
9549 RValue VarRVal = CGF.EmitLoadOfLValue(VarLVal, RD->getLocation());
9550 LambdaPointers.try_emplace(VarLVal.getPointer(CGF),
9551 VDLVal.getPointer(CGF));
9552 CombinedInfo.Exprs.push_back(VD);
9553 CombinedInfo.BasePointers.push_back(VarLVal.getPointer(CGF));
9554 CombinedInfo.DevicePtrDecls.push_back(nullptr);
9555 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
9556 CombinedInfo.Pointers.push_back(VarRVal.getScalarVal());
9557 CombinedInfo.Sizes.push_back(llvm::ConstantInt::get(CGF.Int64Ty, 0));
9558 }
9559 CombinedInfo.Types.push_back(
9560 OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ |
9561 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
9562 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF |
9563 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT);
9564 CombinedInfo.Mappers.push_back(nullptr);
9565 }
9566 }
9567
9568 /// Set correct indices for lambdas captures.
9569 void adjustMemberOfForLambdaCaptures(
9570 llvm::OpenMPIRBuilder &OMPBuilder,
9571 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
9572 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
9573 MapFlagsArrayTy &Types) const {
9574 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
9575 // Set correct member_of idx for all implicit lambda captures.
9576 if (Types[I] != (OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ |
9577 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
9578 OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF |
9579 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT))
9580 continue;
9581 llvm::Value *BasePtr = LambdaPointers.lookup(BasePointers[I]);
9582 assert(BasePtr && "Unable to find base lambda address.");
9583 int TgtIdx = -1;
9584 for (unsigned J = I; J > 0; --J) {
9585 unsigned Idx = J - 1;
9586 if (Pointers[Idx] != BasePtr)
9587 continue;
9588 TgtIdx = Idx;
9589 break;
9590 }
9591 assert(TgtIdx != -1 && "Unable to find parent lambda.");
9592 // All other current entries will be MEMBER_OF the combined entry
9593 // (except for PTR_AND_OBJ entries which do not have a placeholder value
9594 // 0xFFFF in the MEMBER_OF field).
9595 OpenMPOffloadMappingFlags MemberOfFlag =
9596 OMPBuilder.getMemberOfFlag(TgtIdx);
9597 OMPBuilder.setCorrectMemberOfFlag(Types[I], MemberOfFlag);
9598 }
9599 }
9600
9601 /// Populate component lists for non-lambda captured variables from map,
9602 /// is_device_ptr and has_device_addr clause info.
9603 void populateComponentListsForNonLambdaCaptureFromClauses(
9604 const ValueDecl *VD, MapDataArrayTy &DeclComponentLists,
9605 SmallVectorImpl<
9606 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 8>>
9607 &StorageForImplicitlyAddedComponentLists) const {
9608 if (VD && LambdasMap.count(VD))
9609 return;
9610
9611 // For member fields list in is_device_ptr, store it in
9612 // DeclComponentLists for generating components info.
9613 static const OpenMPMapModifierKind Unknown = OMPC_MAP_MODIFIER_unknown;
9614 auto It = DevPointersMap.find(VD);
9615 if (It != DevPointersMap.end())
9616 for (const auto &MCL : It->second)
9617 DeclComponentLists.emplace_back(MCL, OMPC_MAP_to, Unknown,
9618 /*IsImpicit = */ true, nullptr,
9619 nullptr);
9620 auto I = HasDevAddrsMap.find(VD);
9621 if (I != HasDevAddrsMap.end())
9622 for (const auto &MCL : I->second)
9623 DeclComponentLists.emplace_back(MCL, OMPC_MAP_tofrom, Unknown,
9624 /*IsImpicit = */ true, nullptr,
9625 nullptr);
9626 assert(isa<const OMPExecutableDirective *>(CurDir) &&
9627 "Expect a executable directive");
9628 const auto *CurExecDir = cast<const OMPExecutableDirective *>(CurDir);
9629 for (const auto *C : CurExecDir->getClausesOfKind<OMPMapClause>()) {
9630 const auto *EI = C->getVarRefs().begin();
9631 for (const auto L : C->decl_component_lists(VD)) {
9632 const ValueDecl *VDecl, *Mapper;
9633 // The Expression is not correct if the mapping is implicit
9634 const Expr *E = (C->getMapLoc().isValid()) ? *EI : nullptr;
9635 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
9636 std::tie(VDecl, Components, Mapper) = L;
9637 assert(VDecl == VD && "We got information for the wrong declaration??");
9638 assert(!Components.empty() &&
9639 "Not expecting declaration with no component lists.");
9640 DeclComponentLists.emplace_back(Components, C->getMapType(),
9641 C->getMapTypeModifiers(),
9642 C->isImplicit(), Mapper, E);
9643 ++EI;
9644 }
9645 }
9646
9647 // For the target construct, if there's a map with a base-pointer that's
9648 // a member of an implicitly captured struct, of the current class,
9649 // we need to emit an implicit map on the pointer.
9650 if (isOpenMPTargetExecutionDirective(CurExecDir->getDirectiveKind()))
9651 addImplicitMapForAttachPtrBaseIfMemberOfCapturedVD(
9652 VD, DeclComponentLists, StorageForImplicitlyAddedComponentLists);
9653
9654 llvm::stable_sort(DeclComponentLists, [](const MapData &LHS,
9655 const MapData &RHS) {
9656 ArrayRef<OpenMPMapModifierKind> MapModifiers = std::get<2>(LHS);
9657 OpenMPMapClauseKind MapType = std::get<1>(RHS);
9658 bool HasPresent =
9659 llvm::is_contained(MapModifiers, clang::OMPC_MAP_MODIFIER_present);
9660 bool HasAllocs = MapType == OMPC_MAP_alloc;
9661 MapModifiers = std::get<2>(RHS);
9662 MapType = std::get<1>(LHS);
9663 bool HasPresentR =
9664 llvm::is_contained(MapModifiers, clang::OMPC_MAP_MODIFIER_present);
9665 bool HasAllocsR = MapType == OMPC_MAP_alloc;
9666 return (HasPresent && !HasPresentR) || (HasAllocs && !HasAllocsR);
9667 });
9668 }
9669
9670 /// On a target construct, if there's an implicit map on a struct, or that of
9671 /// this[:], and an explicit map with a member of that struct/class as the
9672 /// base-pointer, we need to make sure that base-pointer is implicitly mapped,
9673 /// to make sure we don't map the full struct/class. For example:
9674 ///
9675 /// \code
9676 /// struct S {
9677 /// int dummy[10000];
9678 /// int *p;
9679 /// void f1() {
9680 /// #pragma omp target map(p[0:1])
9681 /// (void)this;
9682 /// }
9683 /// }; S s;
9684 ///
9685 /// void f2() {
9686 /// #pragma omp target map(s.p[0:10])
9687 /// (void)s;
9688 /// }
9689 /// \endcode
9690 ///
9691 /// Only `this-p` and `s.p` should be mapped in the two cases above.
9692 //
9693 // OpenMP 6.0: 7.9.6 map clause, pg 285
9694 // If a list item with an implicitly determined data-mapping attribute does
9695 // not have any corresponding storage in the device data environment prior to
9696 // a task encountering the construct associated with the map clause, and one
9697 // or more contiguous parts of the original storage are either list items or
9698 // base pointers to list items that are explicitly mapped on the construct,
9699 // only those parts of the original storage will have corresponding storage in
9700 // the device data environment as a result of the map clauses on the
9701 // construct.
9702 void addImplicitMapForAttachPtrBaseIfMemberOfCapturedVD(
9703 const ValueDecl *CapturedVD, MapDataArrayTy &DeclComponentLists,
9704 SmallVectorImpl<
9705 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 8>>
9706 &ComponentVectorStorage) const {
9707 bool IsThisCapture = CapturedVD == nullptr;
9708
9709 for (const auto &ComponentsAndAttachPtr : AttachPtrExprMap) {
9710 OMPClauseMappableExprCommon::MappableExprComponentListRef
9711 ComponentsWithAttachPtr = ComponentsAndAttachPtr.first;
9712 const Expr *AttachPtrExpr = ComponentsAndAttachPtr.second;
9713 if (!AttachPtrExpr)
9714 continue;
9715
9716 const auto *ME = dyn_cast<MemberExpr>(AttachPtrExpr);
9717 if (!ME)
9718 continue;
9719
9720 const Expr *Base = ME->getBase()->IgnoreParenImpCasts();
9721
9722 // If we are handling a "this" capture, then we are looking for
9723 // attach-ptrs of form `this->p`, either explicitly or implicitly.
9724 if (IsThisCapture && !ME->isImplicitCXXThis() && !isa<CXXThisExpr>(Base))
9725 continue;
9726
9727 if (!IsThisCapture && (!isa<DeclRefExpr>(Base) ||
9728 cast<DeclRefExpr>(Base)->getDecl() != CapturedVD))
9729 continue;
9730
9731 // For non-this captures, we are looking for attach-ptrs of form
9732 // `s.p`.
9733 // For non-this captures, we are looking for attach-ptrs like `s.p`.
9734 if (!IsThisCapture && (ME->isArrow() || !isa<DeclRefExpr>(Base) ||
9735 cast<DeclRefExpr>(Base)->getDecl() != CapturedVD))
9736 continue;
9737
9738 // Check if we have an existing map on either:
9739 // this[:], s, this->p, or s.p, in which case, we don't need to add
9740 // an implicit one for the attach-ptr s.p/this->p.
9741 bool FoundExistingMap = false;
9742 for (const MapData &ExistingL : DeclComponentLists) {
9743 OMPClauseMappableExprCommon::MappableExprComponentListRef
9744 ExistingComponents = std::get<0>(ExistingL);
9745
9746 if (ExistingComponents.empty())
9747 continue;
9748
9749 // First check if we have a map like map(this->p) or map(s.p).
9750 const auto &FirstComponent = ExistingComponents.front();
9751 const Expr *FirstExpr = FirstComponent.getAssociatedExpression();
9752
9753 if (!FirstExpr)
9754 continue;
9755
9756 // First check if we have a map like map(this->p) or map(s.p).
9757 if (AttachPtrComparator.areEqual(FirstExpr, AttachPtrExpr)) {
9758 FoundExistingMap = true;
9759 break;
9760 }
9761
9762 // Check if we have a map like this[0:1]
9763 if (IsThisCapture) {
9764 if (const auto *OASE = dyn_cast<ArraySectionExpr>(FirstExpr)) {
9765 if (isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts())) {
9766 FoundExistingMap = true;
9767 break;
9768 }
9769 }
9770 continue;
9771 }
9772
9773 // When the attach-ptr is something like `s.p`, check if
9774 // `s` itself is mapped explicitly.
9775 if (const auto *DRE = dyn_cast<DeclRefExpr>(FirstExpr)) {
9776 if (DRE->getDecl() == CapturedVD) {
9777 FoundExistingMap = true;
9778 break;
9779 }
9780 }
9781 }
9782
9783 if (FoundExistingMap)
9784 continue;
9785
9786 // If no base map is found, we need to create an implicit map for the
9787 // attach-pointer expr.
9788
9789 ComponentVectorStorage.emplace_back();
9790 auto &AttachPtrComponents = ComponentVectorStorage.back();
9791
9792 static const OpenMPMapModifierKind Unknown = OMPC_MAP_MODIFIER_unknown;
9793 bool SeenAttachPtrComponent = false;
9794 // For creating a map on the attach-ptr `s.p/this->p`, we copy all
9795 // components from the component-list which has `s.p/this->p`
9796 // as the attach-ptr, starting from the component which matches
9797 // `s.p/this->p`. This way, we'll have component-lists of
9798 // `s.p` -> `s`, and `this->p` -> `this`.
9799 for (size_t i = 0; i < ComponentsWithAttachPtr.size(); ++i) {
9800 const auto &Component = ComponentsWithAttachPtr[i];
9801 const Expr *ComponentExpr = Component.getAssociatedExpression();
9802
9803 if (!SeenAttachPtrComponent && ComponentExpr != AttachPtrExpr)
9804 continue;
9805 SeenAttachPtrComponent = true;
9806
9807 AttachPtrComponents.emplace_back(Component.getAssociatedExpression(),
9808 Component.getAssociatedDeclaration(),
9809 Component.isNonContiguous());
9810 }
9811 assert(!AttachPtrComponents.empty() &&
9812 "Could not populate component-lists for mapping attach-ptr");
9813
9814 DeclComponentLists.emplace_back(
9815 AttachPtrComponents, OMPC_MAP_tofrom, Unknown,
9816 /*IsImplicit=*/true, /*mapper=*/nullptr, AttachPtrExpr);
9817 }
9818 }
9819
9820 /// For a capture that has an associated clause, generate the base pointers,
9821 /// section pointers, sizes, map types, and mappers (all included in
9822 /// \a CurCaptureVarInfo).
9823 void generateInfoForCaptureFromClauseInfo(
9824 const MapDataArrayTy &DeclComponentListsFromClauses,
9825 const CapturedStmt::Capture *Cap, llvm::Value *Arg,
9826 MapCombinedInfoTy &CurCaptureVarInfo, llvm::OpenMPIRBuilder &OMPBuilder,
9827 unsigned OffsetForMemberOfFlag) const {
9828 assert(!Cap->capturesVariableArrayType() &&
9829 "Not expecting to generate map info for a variable array type!");
9830
9831 // We need to know when we generating information for the first component
9832 const ValueDecl *VD = Cap->capturesThis()
9833 ? nullptr
9834 : Cap->getCapturedVar()->getCanonicalDecl();
9835
9836 // for map(to: lambda): skip here, processing it in
9837 // generateDefaultMapInfo
9838 if (LambdasMap.count(VD))
9839 return;
9840
9841 // If this declaration appears in a is_device_ptr clause we just have to
9842 // pass the pointer by value. If it is a reference to a declaration, we just
9843 // pass its value.
9844 if (VD && (DevPointersMap.count(VD) || HasDevAddrsMap.count(VD))) {
9845 CurCaptureVarInfo.Exprs.push_back(VD);
9846 CurCaptureVarInfo.BasePointers.emplace_back(Arg);
9847 CurCaptureVarInfo.DevicePtrDecls.emplace_back(VD);
9848 CurCaptureVarInfo.DevicePointers.emplace_back(DeviceInfoTy::Pointer);
9849 CurCaptureVarInfo.Pointers.push_back(Arg);
9850 CurCaptureVarInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
9851 CGF.getTypeSize(CGF.getContext().VoidPtrTy), CGF.Int64Ty,
9852 /*isSigned=*/true));
9853 CurCaptureVarInfo.Types.push_back(
9854 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
9855 OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM);
9856 CurCaptureVarInfo.Mappers.push_back(nullptr);
9857 return;
9858 }
9859
9860 auto GenerateInfoForComponentLists =
9861 [&](ArrayRef<MapData> DeclComponentListsFromClauses,
9862 bool IsEligibleForTargetParamFlag) {
9863 MapCombinedInfoTy CurInfoForComponentLists;
9864 StructRangeInfoTy PartialStruct;
9865 AttachInfoTy AttachInfo;
9866
9867 if (DeclComponentListsFromClauses.empty())
9868 return;
9869
9870 generateInfoForCaptureFromComponentLists(
9871 VD, DeclComponentListsFromClauses, CurInfoForComponentLists,
9872 PartialStruct, AttachInfo, IsEligibleForTargetParamFlag);
9873
9874 // If there is an entry in PartialStruct it means we have a
9875 // struct with individual members mapped. Emit an extra combined
9876 // entry.
9877 if (PartialStruct.Base.isValid()) {
9878 CurCaptureVarInfo.append(PartialStruct.PreliminaryMapData);
9879 emitCombinedEntry(
9880 CurCaptureVarInfo, CurInfoForComponentLists.Types,
9881 PartialStruct, AttachInfo, Cap->capturesThis(), OMPBuilder,
9882 /*VD=*/nullptr, OffsetForMemberOfFlag,
9883 /*NotTargetParams*/ !IsEligibleForTargetParamFlag);
9884 }
9885
9886 // We do the appends to get the entries in the following order:
9887 // combined-entry -> individual-field-entries -> attach-entry,
9888 CurCaptureVarInfo.append(CurInfoForComponentLists);
9889 if (AttachInfo.isValid())
9890 emitAttachEntry(CGF, CurCaptureVarInfo, AttachInfo);
9891 };
9892
9893 // Group component lists by their AttachPtrExpr and process them in order
9894 // of increasing complexity (nullptr first, then simple expressions like p,
9895 // then more complex ones like p[0], etc.)
9896 //
9897 // This ensure that we:
9898 // * handle maps that can contribute towards setting the kernel argument,
9899 // (e.g. map(ps), or map(ps[0])), before any that cannot (e.g. ps->pt->d).
9900 // * allocate a single contiguous storage for all exprs with the same
9901 // captured var and having the same attach-ptr.
9902 //
9903 // Example: The map clauses below should be handled grouped together based
9904 // on their attachable-base-pointers:
9905 // map-clause | attachable-base-pointer
9906 // --------------------------+------------------------
9907 // map(p, ps) | nullptr
9908 // map(p[0]) | p
9909 // map(p[0]->b, p[0]->c) | p[0]
9910 // map(ps->d, ps->e, ps->pt) | ps
9911 // map(ps->pt->d, ps->pt->e) | ps->pt
9912
9913 // First, collect all MapData entries with their attach-ptr exprs.
9914 SmallVector<std::pair<const Expr *, MapData>, 16> AttachPtrMapDataPairs;
9915
9916 for (const MapData &L : DeclComponentListsFromClauses) {
9917 OMPClauseMappableExprCommon::MappableExprComponentListRef Components =
9918 std::get<0>(L);
9919 const Expr *AttachPtrExpr = getAttachPtrExpr(Components);
9920 AttachPtrMapDataPairs.emplace_back(AttachPtrExpr, L);
9921 }
9922
9923 // Next, sort by increasing order of their complexity.
9924 llvm::stable_sort(AttachPtrMapDataPairs,
9925 [this](const auto &LHS, const auto &RHS) {
9926 return AttachPtrComparator(LHS.first, RHS.first);
9927 });
9928
9929 bool NoDefaultMappingDoneForVD = CurCaptureVarInfo.BasePointers.empty();
9930 bool IsFirstGroup = true;
9931
9932 // And finally, process them all in order, grouping those with
9933 // equivalent attach-ptr exprs together.
9934 auto *It = AttachPtrMapDataPairs.begin();
9935 while (It != AttachPtrMapDataPairs.end()) {
9936 const Expr *AttachPtrExpr = It->first;
9937
9938 MapDataArrayTy GroupLists;
9939 while (It != AttachPtrMapDataPairs.end() &&
9940 (It->first == AttachPtrExpr ||
9941 AttachPtrComparator.areEqual(It->first, AttachPtrExpr))) {
9942 GroupLists.push_back(It->second);
9943 ++It;
9944 }
9945 assert(!GroupLists.empty() && "GroupLists should not be empty");
9946
9947 // Determine if this group of component-lists is eligible for TARGET_PARAM
9948 // flag. Only the first group processed should be eligible, and only if no
9949 // default mapping was done.
9950 bool IsEligibleForTargetParamFlag =
9951 IsFirstGroup && NoDefaultMappingDoneForVD;
9952
9953 GenerateInfoForComponentLists(GroupLists, IsEligibleForTargetParamFlag);
9954 IsFirstGroup = false;
9955 }
9956 }
9957
9958 /// Generate the base pointers, section pointers, sizes, map types, and
9959 /// mappers associated to \a DeclComponentLists for a given capture
9960 /// \a VD (all included in \a CurComponentListInfo).
9961 void generateInfoForCaptureFromComponentLists(
9962 const ValueDecl *VD, ArrayRef<MapData> DeclComponentLists,
9963 MapCombinedInfoTy &CurComponentListInfo, StructRangeInfoTy &PartialStruct,
9964 AttachInfoTy &AttachInfo, bool IsListEligibleForTargetParamFlag) const {
9965 // Find overlapping elements (including the offset from the base element).
9966 llvm::SmallDenseMap<
9967 const MapData *,
9968 llvm::SmallVector<
9969 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
9970 4>
9971 OverlappedData;
9972 size_t Count = 0;
9973 for (const MapData &L : DeclComponentLists) {
9974 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
9975 OpenMPMapClauseKind MapType;
9976 ArrayRef<OpenMPMapModifierKind> MapModifiers;
9977 bool IsImplicit;
9978 const ValueDecl *Mapper;
9979 const Expr *VarRef;
9980 std::tie(Components, MapType, MapModifiers, IsImplicit, Mapper, VarRef) =
9981 L;
9982 ++Count;
9983 for (const MapData &L1 : ArrayRef(DeclComponentLists).slice(Count)) {
9984 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
9985 std::tie(Components1, MapType, MapModifiers, IsImplicit, Mapper,
9986 VarRef) = L1;
9987 auto CI = Components.rbegin();
9988 auto CE = Components.rend();
9989 auto SI = Components1.rbegin();
9990 auto SE = Components1.rend();
9991 for (; CI != CE && SI != SE; ++CI, ++SI) {
9992 if (CI->getAssociatedExpression()->getStmtClass() !=
9993 SI->getAssociatedExpression()->getStmtClass())
9994 break;
9995 // Are we dealing with different variables/fields?
9996 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
9997 break;
9998 }
9999 // Found overlapping if, at least for one component, reached the head
10000 // of the components list.
10001 if (CI == CE || SI == SE) {
10002 // Ignore it if it is the same component.
10003 if (CI == CE && SI == SE)
10004 continue;
10005 const auto It = (SI == SE) ? CI : SI;
10006 // If one component is a pointer and another one is a kind of
10007 // dereference of this pointer (array subscript, section, dereference,
10008 // etc.), it is not an overlapping.
10009 // Same, if one component is a base and another component is a
10010 // dereferenced pointer memberexpr with the same base.
10011 if (!isa<MemberExpr>(It->getAssociatedExpression()) ||
10012 (std::prev(It)->getAssociatedDeclaration() &&
10013 std::prev(It)
10014 ->getAssociatedDeclaration()
10015 ->getType()
10016 ->isPointerType()) ||
10017 (It->getAssociatedDeclaration() &&
10018 It->getAssociatedDeclaration()->getType()->isPointerType() &&
10019 std::next(It) != CE && std::next(It) != SE))
10020 continue;
10021 const MapData &BaseData = CI == CE ? L : L1;
10022 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
10023 SI == SE ? Components : Components1;
10024 OverlappedData[&BaseData].push_back(SubData);
10025 }
10026 }
10027 }
10028 // Sort the overlapped elements for each item.
10029 llvm::SmallVector<const FieldDecl *, 4> Layout;
10030 if (!OverlappedData.empty()) {
10031 const Type *BaseType = VD->getType().getCanonicalType().getTypePtr();
10032 const Type *OrigType = BaseType->getPointeeOrArrayElementType();
10033 while (BaseType != OrigType) {
10034 BaseType = OrigType->getCanonicalTypeInternal().getTypePtr();
10035 OrigType = BaseType->getPointeeOrArrayElementType();
10036 }
10037
10038 if (const auto *CRD = BaseType->getAsCXXRecordDecl())
10039 getPlainLayout(CRD, Layout, /*AsBase=*/false);
10040 else {
10041 const auto *RD = BaseType->getAsRecordDecl();
10042 Layout.append(RD->field_begin(), RD->field_end());
10043 }
10044 }
10045 for (auto &Pair : OverlappedData) {
10046 llvm::stable_sort(
10047 Pair.getSecond(),
10048 [&Layout](
10049 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
10050 OMPClauseMappableExprCommon::MappableExprComponentListRef
10051 Second) {
10052 auto CI = First.rbegin();
10053 auto CE = First.rend();
10054 auto SI = Second.rbegin();
10055 auto SE = Second.rend();
10056 for (; CI != CE && SI != SE; ++CI, ++SI) {
10057 if (CI->getAssociatedExpression()->getStmtClass() !=
10058 SI->getAssociatedExpression()->getStmtClass())
10059 break;
10060 // Are we dealing with different variables/fields?
10061 if (CI->getAssociatedDeclaration() !=
10062 SI->getAssociatedDeclaration())
10063 break;
10064 }
10065
10066 // Lists contain the same elements.
10067 if (CI == CE && SI == SE)
10068 return false;
10069
10070 // List with less elements is less than list with more elements.
10071 if (CI == CE || SI == SE)
10072 return CI == CE;
10073
10074 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
10075 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
10076 if (FD1->getParent() == FD2->getParent())
10077 return FD1->getFieldIndex() < FD2->getFieldIndex();
10078 const auto *It =
10079 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
10080 return FD == FD1 || FD == FD2;
10081 });
10082 return *It == FD1;
10083 });
10084 }
10085
10086 // Associated with a capture, because the mapping flags depend on it.
10087 // Go through all of the elements with the overlapped elements.
10088 bool AddTargetParamFlag = IsListEligibleForTargetParamFlag;
10089 MapCombinedInfoTy StructBaseCombinedInfo;
10090 for (const auto &Pair : OverlappedData) {
10091 const MapData &L = *Pair.getFirst();
10092 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
10093 OpenMPMapClauseKind MapType;
10094 ArrayRef<OpenMPMapModifierKind> MapModifiers;
10095 bool IsImplicit;
10096 const ValueDecl *Mapper;
10097 const Expr *VarRef;
10098 std::tie(Components, MapType, MapModifiers, IsImplicit, Mapper, VarRef) =
10099 L;
10100 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
10101 OverlappedComponents = Pair.getSecond();
10102 generateInfoForComponentList(
10103 MapType, MapModifiers, {}, Components, CurComponentListInfo,
10104 StructBaseCombinedInfo, PartialStruct, AttachInfo, AddTargetParamFlag,
10105 IsImplicit, /*GenerateAllInfoForClauses*/ false, Mapper,
10106 /*ForDeviceAddr=*/false, VD, VarRef, OverlappedComponents);
10107 AddTargetParamFlag = false;
10108 }
10109 // Go through other elements without overlapped elements.
10110 for (const MapData &L : DeclComponentLists) {
10111 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
10112 OpenMPMapClauseKind MapType;
10113 ArrayRef<OpenMPMapModifierKind> MapModifiers;
10114 bool IsImplicit;
10115 const ValueDecl *Mapper;
10116 const Expr *VarRef;
10117 std::tie(Components, MapType, MapModifiers, IsImplicit, Mapper, VarRef) =
10118 L;
10119 auto It = OverlappedData.find(&L);
10120 if (It == OverlappedData.end())
10121 generateInfoForComponentList(
10122 MapType, MapModifiers, {}, Components, CurComponentListInfo,
10123 StructBaseCombinedInfo, PartialStruct, AttachInfo,
10124 AddTargetParamFlag, IsImplicit, /*GenerateAllInfoForClauses*/ false,
10125 Mapper, /*ForDeviceAddr=*/false, VD, VarRef,
10126 /*OverlappedElements*/ {});
10127 AddTargetParamFlag = false;
10128 }
10129 }
10130
10131 /// Check if a variable should be treated as firstprivate due to explicit
10132 /// firstprivate clause or defaultmap(firstprivate:...).
10133 bool isEffectivelyFirstprivate(const VarDecl *VD, QualType Type) const {
10134 // Check explicit firstprivate clauses (not implicit from defaultmap)
10135 auto I = FirstPrivateDecls.find(VD);
10136 if (I != FirstPrivateDecls.end() && !I->getSecond())
10137 return true; // Explicit firstprivate only
10138
10139 // Check defaultmap(firstprivate:scalar) for scalar types
10140 if (DefaultmapFirstprivateKinds.count(OMPC_DEFAULTMAP_scalar)) {
10141 if (Type->isScalarType())
10142 return true;
10143 }
10144
10145 // Check defaultmap(firstprivate:pointer) for pointer types
10146 if (DefaultmapFirstprivateKinds.count(OMPC_DEFAULTMAP_pointer)) {
10147 if (Type->isAnyPointerType())
10148 return true;
10149 }
10150
10151 // Check defaultmap(firstprivate:aggregate) for aggregate types
10152 if (DefaultmapFirstprivateKinds.count(OMPC_DEFAULTMAP_aggregate)) {
10153 if (Type->isAggregateType())
10154 return true;
10155 }
10156
10157 // Check defaultmap(firstprivate:all) for all types
10158 return DefaultmapFirstprivateKinds.count(OMPC_DEFAULTMAP_all);
10159 }
10160
10161 /// Generate the default map information for a given capture \a CI,
10162 /// record field declaration \a RI and captured value \a CV.
10163 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
10164 const FieldDecl &RI, llvm::Value *CV,
10165 MapCombinedInfoTy &CombinedInfo) const {
10166 bool IsImplicit = true;
10167 // Do the default mapping.
10168 if (CI.capturesThis()) {
10169 CombinedInfo.Exprs.push_back(nullptr);
10170 CombinedInfo.BasePointers.push_back(CV);
10171 CombinedInfo.DevicePtrDecls.push_back(nullptr);
10172 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
10173 CombinedInfo.Pointers.push_back(CV);
10174 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
10175 CombinedInfo.Sizes.push_back(
10176 CGF.Builder.CreateIntCast(CGF.getTypeSize(PtrTy->getPointeeType()),
10177 CGF.Int64Ty, /*isSigned=*/true));
10178 // Default map type.
10179 CombinedInfo.Types.push_back(OpenMPOffloadMappingFlags::OMP_MAP_TO |
10180 OpenMPOffloadMappingFlags::OMP_MAP_FROM);
10181 } else if (CI.capturesVariableByCopy()) {
10182 const VarDecl *VD = CI.getCapturedVar();
10183 CombinedInfo.Exprs.push_back(VD->getCanonicalDecl());
10184 CombinedInfo.BasePointers.push_back(CV);
10185 CombinedInfo.DevicePtrDecls.push_back(nullptr);
10186 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
10187 CombinedInfo.Pointers.push_back(CV);
10188 bool IsFirstprivate =
10189 isEffectivelyFirstprivate(VD, RI.getType().getNonReferenceType());
10190
10191 if (!RI.getType()->isAnyPointerType()) {
10192 // We have to signal to the runtime captures passed by value that are
10193 // not pointers.
10194 CombinedInfo.Types.push_back(
10195 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
10196 CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
10197 CGF.getTypeSize(RI.getType()), CGF.Int64Ty, /*isSigned=*/true));
10198 } else if (IsFirstprivate) {
10199 // Firstprivate pointers should be passed by value (as literals)
10200 // without performing a present table lookup at runtime.
10201 CombinedInfo.Types.push_back(
10202 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
10203 // Use zero size for pointer literals (just passing the pointer value)
10204 CombinedInfo.Sizes.push_back(llvm::Constant::getNullValue(CGF.Int64Ty));
10205 } else {
10206 // Pointers are implicitly mapped with a zero size and no flags
10207 // (other than first map that is added for all implicit maps).
10208 CombinedInfo.Types.push_back(OpenMPOffloadMappingFlags::OMP_MAP_NONE);
10209 CombinedInfo.Sizes.push_back(llvm::Constant::getNullValue(CGF.Int64Ty));
10210 }
10211 auto I = FirstPrivateDecls.find(VD);
10212 if (I != FirstPrivateDecls.end())
10213 IsImplicit = I->getSecond();
10214 } else {
10215 assert(CI.capturesVariable() && "Expected captured reference.");
10216 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
10217 QualType ElementType = PtrTy->getPointeeType();
10218 const VarDecl *VD = CI.getCapturedVar();
10219 bool IsFirstprivate = isEffectivelyFirstprivate(VD, ElementType);
10220 CombinedInfo.Exprs.push_back(VD->getCanonicalDecl());
10221 CombinedInfo.BasePointers.push_back(CV);
10222 CombinedInfo.DevicePtrDecls.push_back(nullptr);
10223 CombinedInfo.DevicePointers.push_back(DeviceInfoTy::None);
10224
10225 // For firstprivate pointers, pass by value instead of dereferencing
10226 if (IsFirstprivate && ElementType->isAnyPointerType()) {
10227 // Treat as a literal value (pass the pointer value itself)
10228 CombinedInfo.Pointers.push_back(CV);
10229 // Use zero size for pointer literals
10230 CombinedInfo.Sizes.push_back(llvm::Constant::getNullValue(CGF.Int64Ty));
10231 CombinedInfo.Types.push_back(
10232 OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
10233 } else {
10234 CombinedInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
10235 CGF.getTypeSize(ElementType), CGF.Int64Ty, /*isSigned=*/true));
10236 // The default map type for a scalar/complex type is 'to' because by
10237 // default the value doesn't have to be retrieved. For an aggregate
10238 // type, the default is 'tofrom'.
10239 CombinedInfo.Types.push_back(getMapModifiersForPrivateClauses(CI));
10240 CombinedInfo.Pointers.push_back(CV);
10241 }
10242 auto I = FirstPrivateDecls.find(VD);
10243 if (I != FirstPrivateDecls.end())
10244 IsImplicit = I->getSecond();
10245 }
10246 // Every default map produces a single argument which is a target parameter.
10247 CombinedInfo.Types.back() |=
10248 OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
10249
10250 // Add flag stating this is an implicit map.
10251 if (IsImplicit)
10252 CombinedInfo.Types.back() |= OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT;
10253
10254 // No user-defined mapper for default mapping.
10255 CombinedInfo.Mappers.push_back(nullptr);
10256 }
10257 };
10258 } // anonymous namespace
10259
10260 // Try to extract the base declaration from a `this->x` expression if possible.
10261 static ValueDecl *getDeclFromThisExpr(const Expr *E) {
10262 if (!E)
10263 return nullptr;
10264
10265 if (const auto *OASE = dyn_cast<ArraySectionExpr>(E->IgnoreParenCasts()))
10266 if (const MemberExpr *ME =
10267 dyn_cast<MemberExpr>(OASE->getBase()->IgnoreParenImpCasts()))
10268 return ME->getMemberDecl();
10269 return nullptr;
10270 }
10271
10272 /// Emit a string constant containing the names of the values mapped to the
10273 /// offloading runtime library.
10274 static llvm::Constant *
10275 emitMappingInformation(CodeGenFunction &CGF, llvm::OpenMPIRBuilder &OMPBuilder,
10276 MappableExprsHandler::MappingExprInfo &MapExprs) {
10277
10278 uint32_t SrcLocStrSize;
10279 if (!MapExprs.getMapDecl() && !MapExprs.getMapExpr())
10280 return OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
10281
10282 SourceLocation Loc;
10283 if (!MapExprs.getMapDecl() && MapExprs.getMapExpr()) {
10284 if (const ValueDecl *VD = getDeclFromThisExpr(MapExprs.getMapExpr()))
10285 Loc = VD->getLocation();
10286 else
10287 Loc = MapExprs.getMapExpr()->getExprLoc();
10288 } else {
10289 Loc = MapExprs.getMapDecl()->getLocation();
10290 }
10291
10292 std::string ExprName;
10293 if (MapExprs.getMapExpr()) {
10294 PrintingPolicy P(CGF.getContext().getLangOpts());
10295 llvm::raw_string_ostream OS(ExprName);
10296 MapExprs.getMapExpr()->printPretty(OS, nullptr, P);
10297 } else {
10298 ExprName = MapExprs.getMapDecl()->getNameAsString();
10299 }
10300
10301 std::string FileName;
10302 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
10303 if (auto *DbgInfo = CGF.getDebugInfo())
10304 FileName = DbgInfo->remapDIPath(PLoc.getFilename());
10305 else
10306 FileName = PLoc.getFilename();
10307 return OMPBuilder.getOrCreateSrcLocStr(FileName, ExprName, PLoc.getLine(),
10308 PLoc.getColumn(), SrcLocStrSize);
10309 }
10310 /// Emit the arrays used to pass the captures and map information to the
10311 /// offloading runtime library. If there is no map or capture information,
10312 /// return nullptr by reference.
10313 static void emitOffloadingArraysAndArgs(
10314 CodeGenFunction &CGF, MappableExprsHandler::MapCombinedInfoTy &CombinedInfo,
10315 CGOpenMPRuntime::TargetDataInfo &Info, llvm::OpenMPIRBuilder &OMPBuilder,
10316 bool IsNonContiguous = false, bool ForEndCall = false) {
10317 CodeGenModule &CGM = CGF.CGM;
10318
10319 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
10320 InsertPointTy AllocaIP(CGF.AllocaInsertPt->getParent(),
10321 CGF.AllocaInsertPt->getIterator());
10322 InsertPointTy CodeGenIP(CGF.Builder.GetInsertBlock(),
10323 CGF.Builder.GetInsertPoint());
10324
10325 auto DeviceAddrCB = [&](unsigned int I, llvm::Value *NewDecl) {
10326 if (const ValueDecl *DevVD = CombinedInfo.DevicePtrDecls[I]) {
10327 Info.CaptureDeviceAddrMap.try_emplace(DevVD, NewDecl);
10328 }
10329 };
10330
10331 auto CustomMapperCB = [&](unsigned int I) {
10332 llvm::Function *MFunc = nullptr;
10333 if (CombinedInfo.Mappers[I]) {
10334 Info.HasMapper = true;
10335 MFunc = CGM.getOpenMPRuntime().getOrCreateUserDefinedMapperFunc(
10336 cast<OMPDeclareMapperDecl>(CombinedInfo.Mappers[I]));
10337 }
10338 return MFunc;
10339 };
10340 cantFail(OMPBuilder.emitOffloadingArraysAndArgs(
10341 AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
10342 IsNonContiguous, ForEndCall, DeviceAddrCB));
10343 }
10344
10345 /// Check for inner distribute directive.
10346 static const OMPExecutableDirective *
10347 getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
10348 const auto *CS = D.getInnermostCapturedStmt();
10349 const auto *Body =
10350 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
10351 const Stmt *ChildStmt =
10352 CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
10353
10354 if (const auto *NestedDir =
10355 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
10356 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
10357 switch (D.getDirectiveKind()) {
10358 case OMPD_target:
10359 // For now, treat 'target' with nested 'teams loop' as if it's
10360 // distributed (target teams distribute).
10361 if (isOpenMPDistributeDirective(DKind) || DKind == OMPD_teams_loop)
10362 return NestedDir;
10363 if (DKind == OMPD_teams) {
10364 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
10365 /*IgnoreCaptured=*/true);
10366 if (!Body)
10367 return nullptr;
10368 ChildStmt = CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
10369 if (const auto *NND =
10370 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
10371 DKind = NND->getDirectiveKind();
10372 if (isOpenMPDistributeDirective(DKind))
10373 return NND;
10374 }
10375 }
10376 return nullptr;
10377 case OMPD_target_teams:
10378 if (isOpenMPDistributeDirective(DKind))
10379 return NestedDir;
10380 return nullptr;
10381 case OMPD_target_parallel:
10382 case OMPD_target_simd:
10383 case OMPD_target_parallel_for:
10384 case OMPD_target_parallel_for_simd:
10385 return nullptr;
10386 case OMPD_target_teams_distribute:
10387 case OMPD_target_teams_distribute_simd:
10388 case OMPD_target_teams_distribute_parallel_for:
10389 case OMPD_target_teams_distribute_parallel_for_simd:
10390 case OMPD_parallel:
10391 case OMPD_for:
10392 case OMPD_parallel_for:
10393 case OMPD_parallel_master:
10394 case OMPD_parallel_sections:
10395 case OMPD_for_simd:
10396 case OMPD_parallel_for_simd:
10397 case OMPD_cancel:
10398 case OMPD_cancellation_point:
10399 case OMPD_ordered:
10400 case OMPD_threadprivate:
10401 case OMPD_allocate:
10402 case OMPD_task:
10403 case OMPD_simd:
10404 case OMPD_tile:
10405 case OMPD_unroll:
10406 case OMPD_sections:
10407 case OMPD_section:
10408 case OMPD_single:
10409 case OMPD_master:
10410 case OMPD_critical:
10411 case OMPD_taskyield:
10412 case OMPD_barrier:
10413 case OMPD_taskwait:
10414 case OMPD_taskgroup:
10415 case OMPD_atomic:
10416 case OMPD_flush:
10417 case OMPD_depobj:
10418 case OMPD_scan:
10419 case OMPD_teams:
10420 case OMPD_target_data:
10421 case OMPD_target_exit_data:
10422 case OMPD_target_enter_data:
10423 case OMPD_distribute:
10424 case OMPD_distribute_simd:
10425 case OMPD_distribute_parallel_for:
10426 case OMPD_distribute_parallel_for_simd:
10427 case OMPD_teams_distribute:
10428 case OMPD_teams_distribute_simd:
10429 case OMPD_teams_distribute_parallel_for:
10430 case OMPD_teams_distribute_parallel_for_simd:
10431 case OMPD_target_update:
10432 case OMPD_declare_simd:
10433 case OMPD_declare_variant:
10434 case OMPD_begin_declare_variant:
10435 case OMPD_end_declare_variant:
10436 case OMPD_declare_target:
10437 case OMPD_end_declare_target:
10438 case OMPD_declare_reduction:
10439 case OMPD_declare_mapper:
10440 case OMPD_taskloop:
10441 case OMPD_taskloop_simd:
10442 case OMPD_master_taskloop:
10443 case OMPD_master_taskloop_simd:
10444 case OMPD_parallel_master_taskloop:
10445 case OMPD_parallel_master_taskloop_simd:
10446 case OMPD_requires:
10447 case OMPD_metadirective:
10448 case OMPD_unknown:
10449 default:
10450 llvm_unreachable("Unexpected directive.");
10451 }
10452 }
10453
10454 return nullptr;
10455 }
10456
10457 /// Emit the user-defined mapper function. The code generation follows the
10458 /// pattern in the example below.
10459 /// \code
10460 /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
10461 /// void *base, void *begin,
10462 /// int64_t size, int64_t type,
10463 /// void *name = nullptr) {
10464 /// // Allocate space for an array section first or add a base/begin for
10465 /// // pointer dereference.
10466 /// if ((size > 1 || (base != begin && maptype.IsPtrAndObj)) &&
10467 /// !maptype.IsDelete)
10468 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
10469 /// size*sizeof(Ty), clearToFromMember(type));
10470 /// // Map members.
10471 /// for (unsigned i = 0; i < size; i++) {
10472 /// // For each component specified by this mapper:
10473 /// for (auto c : begin[i]->all_components) {
10474 /// if (c.hasMapper())
10475 /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin, c.arg_size,
10476 /// c.arg_type, c.arg_name);
10477 /// else
10478 /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
10479 /// c.arg_begin, c.arg_size, c.arg_type,
10480 /// c.arg_name);
10481 /// }
10482 /// }
10483 /// // Delete the array section.
10484 /// if (size > 1 && maptype.IsDelete)
10485 /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
10486 /// size*sizeof(Ty), clearToFromMember(type));
10487 /// }
10488 /// \endcode
10489 void CGOpenMPRuntime::emitUserDefinedMapper(const OMPDeclareMapperDecl *D,
10490 CodeGenFunction *CGF) {
10491 if (UDMMap.count(D) > 0)
10492 return;
10493 ASTContext &C = CGM.getContext();
10494 QualType Ty = D->getType();
10495 auto *MapperVarDecl =
10496 cast<VarDecl>(cast<DeclRefExpr>(D->getMapperVarRef())->getDecl());
10497 CharUnits ElementSize = C.getTypeSizeInChars(Ty);
10498 llvm::Type *ElemTy = CGM.getTypes().ConvertTypeForMem(Ty);
10499
10500 CodeGenFunction MapperCGF(CGM);
10501 MappableExprsHandler::MapCombinedInfoTy CombinedInfo;
10502 auto PrivatizeAndGenMapInfoCB =
10503 [&](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP, llvm::Value *PtrPHI,
10504 llvm::Value *BeginArg) -> llvm::OpenMPIRBuilder::MapInfosTy & {
10505 MapperCGF.Builder.restoreIP(CodeGenIP);
10506
10507 // Privatize the declared variable of mapper to be the current array
10508 // element.
10509 Address PtrCurrent(
10510 PtrPHI, ElemTy,
10511 Address(BeginArg, MapperCGF.VoidPtrTy, CGM.getPointerAlign())
10512 .getAlignment()
10513 .alignmentOfArrayElement(ElementSize));
10514 CodeGenFunction::OMPPrivateScope Scope(MapperCGF);
10515 Scope.addPrivate(MapperVarDecl, PtrCurrent);
10516 (void)Scope.Privatize();
10517
10518 // Get map clause information.
10519 MappableExprsHandler MEHandler(*D, MapperCGF);
10520 MEHandler.generateAllInfoForMapper(CombinedInfo, OMPBuilder);
10521
10522 auto FillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
10523 return emitMappingInformation(MapperCGF, OMPBuilder, MapExpr);
10524 };
10525 if (CGM.getCodeGenOpts().getDebugInfo() !=
10526 llvm::codegenoptions::NoDebugInfo) {
10527 CombinedInfo.Names.resize(CombinedInfo.Exprs.size());
10528 llvm::transform(CombinedInfo.Exprs, CombinedInfo.Names.begin(),
10529 FillInfoMap);
10530 }
10531
10532 return CombinedInfo;
10533 };
10534
10535 auto CustomMapperCB = [&](unsigned I) {
10536 llvm::Function *MapperFunc = nullptr;
10537 if (CombinedInfo.Mappers[I]) {
10538 // Call the corresponding mapper function.
10539 MapperFunc = getOrCreateUserDefinedMapperFunc(
10540 cast<OMPDeclareMapperDecl>(CombinedInfo.Mappers[I]));
10541 assert(MapperFunc && "Expect a valid mapper function is available.");
10542 }
10543 return MapperFunc;
10544 };
10545
10546 SmallString<64> TyStr;
10547 llvm::raw_svector_ostream Out(TyStr);
10548 CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
10549 std::string Name = getName({"omp_mapper", TyStr, D->getName()});
10550
10551 llvm::Function *NewFn = cantFail(OMPBuilder.emitUserDefinedMapper(
10552 PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB));
10553 UDMMap.try_emplace(D, NewFn);
10554 if (CGF)
10555 FunctionUDMMap[CGF->CurFn].push_back(D);
10556 }
10557
10558 llvm::Function *CGOpenMPRuntime::getOrCreateUserDefinedMapperFunc(
10559 const OMPDeclareMapperDecl *D) {
10560 auto I = UDMMap.find(D);
10561 if (I != UDMMap.end())
10562 return I->second;
10563 emitUserDefinedMapper(D);
10564 return UDMMap.lookup(D);
10565 }
10566
10567 llvm::Value *CGOpenMPRuntime::emitTargetNumIterationsCall(
10568 CodeGenFunction &CGF, const OMPExecutableDirective &D,
10569 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
10570 const OMPLoopDirective &D)>
10571 SizeEmitter) {
10572 OpenMPDirectiveKind Kind = D.getDirectiveKind();
10573 const OMPExecutableDirective *TD = &D;
10574 // Get nested teams distribute kind directive, if any. For now, treat
10575 // 'target_teams_loop' as if it's really a target_teams_distribute.
10576 if ((!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind)) &&
10577 Kind != OMPD_target_teams_loop)
10578 TD = getNestedDistributeDirective(CGM.getContext(), D);
10579 if (!TD)
10580 return llvm::ConstantInt::get(CGF.Int64Ty, 0);
10581
10582 const auto *LD = cast<OMPLoopDirective>(TD);
10583 if (llvm::Value *NumIterations = SizeEmitter(CGF, *LD))
10584 return NumIterations;
10585 return llvm::ConstantInt::get(CGF.Int64Ty, 0);
10586 }
10587
10588 static void
10589 emitTargetCallFallback(CGOpenMPRuntime *OMPRuntime, llvm::Function *OutlinedFn,
10590 const OMPExecutableDirective &D,
10591 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars,
10592 bool RequiresOuterTask, const CapturedStmt &CS,
10593 bool OffloadingMandatory, CodeGenFunction &CGF) {
10594 if (OffloadingMandatory) {
10595 CGF.Builder.CreateUnreachable();
10596 } else {
10597 if (RequiresOuterTask) {
10598 CapturedVars.clear();
10599 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
10600 }
10601 OMPRuntime->emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn,
10602 CapturedVars);
10603 }
10604 }
10605
10606 static llvm::Value *emitDeviceID(
10607 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
10608 CodeGenFunction &CGF) {
10609 // Emit device ID if any.
10610 llvm::Value *DeviceID;
10611 if (Device.getPointer()) {
10612 assert((Device.getInt() == OMPC_DEVICE_unknown ||
10613 Device.getInt() == OMPC_DEVICE_device_num) &&
10614 "Expected device_num modifier.");
10615 llvm::Value *DevVal = CGF.EmitScalarExpr(Device.getPointer());
10616 DeviceID =
10617 CGF.Builder.CreateIntCast(DevVal, CGF.Int64Ty, /*isSigned=*/true);
10618 } else {
10619 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
10620 }
10621 return DeviceID;
10622 }
10623
10624 static std::pair<llvm::Value *, OMPDynGroupprivateFallbackType>
10625 emitDynCGroupMem(const OMPExecutableDirective &D, CodeGenFunction &CGF) {
10626 llvm::Value *DynGP = CGF.Builder.getInt32(0);
10627 auto DynGPFallback = OMPDynGroupprivateFallbackType::Abort;
10628
10629 if (auto *DynGPClause = D.getSingleClause<OMPDynGroupprivateClause>()) {
10630 CodeGenFunction::RunCleanupsScope DynGPScope(CGF);
10631 llvm::Value *DynGPVal =
10632 CGF.EmitScalarExpr(DynGPClause->getSize(), /*IgnoreResultAssign=*/true);
10633 DynGP = CGF.Builder.CreateIntCast(DynGPVal, CGF.Int32Ty,
10634 /*isSigned=*/false);
10635 auto FallbackModifier = DynGPClause->getDynGroupprivateFallbackModifier();
10636 switch (FallbackModifier) {
10637 case OMPC_DYN_GROUPPRIVATE_FALLBACK_abort:
10638 DynGPFallback = OMPDynGroupprivateFallbackType::Abort;
10639 break;
10640 case OMPC_DYN_GROUPPRIVATE_FALLBACK_null:
10641 DynGPFallback = OMPDynGroupprivateFallbackType::Null;
10642 break;
10643 case OMPC_DYN_GROUPPRIVATE_FALLBACK_default_mem:
10644 case OMPC_DYN_GROUPPRIVATE_FALLBACK_unknown:
10645 // This is the default for dyn_groupprivate.
10646 DynGPFallback = OMPDynGroupprivateFallbackType::DefaultMem;
10647 break;
10648 default:
10649 llvm_unreachable("Unknown fallback modifier for OpenMP dyn_groupprivate");
10650 }
10651 } else if (auto *OMPXDynCGClause =
10652 D.getSingleClause<OMPXDynCGroupMemClause>()) {
10653 CodeGenFunction::RunCleanupsScope DynCGMemScope(CGF);
10654 llvm::Value *DynCGMemVal = CGF.EmitScalarExpr(OMPXDynCGClause->getSize(),
10655 /*IgnoreResultAssign=*/true);
10656 DynGP = CGF.Builder.CreateIntCast(DynCGMemVal, CGF.Int32Ty,
10657 /*isSigned=*/false);
10658 }
10659 return {DynGP, DynGPFallback};
10660 }
10661
10662 static void genMapInfoForCaptures(
10663 MappableExprsHandler &MEHandler, CodeGenFunction &CGF,
10664 const CapturedStmt &CS, llvm::SmallVectorImpl<llvm::Value *> &CapturedVars,
10665 llvm::OpenMPIRBuilder &OMPBuilder,
10666 llvm::DenseSet<CanonicalDeclPtr<const Decl>> &MappedVarSet,
10667 MappableExprsHandler::MapCombinedInfoTy &CombinedInfo) {
10668
10669 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
10670 auto RI = CS.getCapturedRecordDecl()->field_begin();
10671 auto *CV = CapturedVars.begin();
10672 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
10673 CE = CS.capture_end();
10674 CI != CE; ++CI, ++RI, ++CV) {
10675 MappableExprsHandler::MapCombinedInfoTy CurInfo;
10676
10677 // VLA sizes are passed to the outlined region by copy and do not have map
10678 // information associated.
10679 if (CI->capturesVariableArrayType()) {
10680 CurInfo.Exprs.push_back(nullptr);
10681 CurInfo.BasePointers.push_back(*CV);
10682 CurInfo.DevicePtrDecls.push_back(nullptr);
10683 CurInfo.DevicePointers.push_back(
10684 MappableExprsHandler::DeviceInfoTy::None);
10685 CurInfo.Pointers.push_back(*CV);
10686 CurInfo.Sizes.push_back(CGF.Builder.CreateIntCast(
10687 CGF.getTypeSize(RI->getType()), CGF.Int64Ty, /*isSigned=*/true));
10688 // Copy to the device as an argument. No need to retrieve it.
10689 CurInfo.Types.push_back(OpenMPOffloadMappingFlags::OMP_MAP_LITERAL |
10690 OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM |
10691 OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT);
10692 CurInfo.Mappers.push_back(nullptr);
10693 } else {
10694 const ValueDecl *CapturedVD =
10695 CI->capturesThis() ? nullptr
10696 : CI->getCapturedVar()->getCanonicalDecl();
10697 bool HasEntryWithCVAsAttachPtr = false;
10698 if (CapturedVD)
10699 HasEntryWithCVAsAttachPtr =
10700 MEHandler.hasAttachEntryForCapturedVar(CapturedVD);
10701
10702 // Populate component lists for the captured variable from clauses.
10703 MappableExprsHandler::MapDataArrayTy DeclComponentLists;
10704 SmallVector<
10705 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 8>, 4>
10706 StorageForImplicitlyAddedComponentLists;
10707 MEHandler.populateComponentListsForNonLambdaCaptureFromClauses(
10708 CapturedVD, DeclComponentLists,
10709 StorageForImplicitlyAddedComponentLists);
10710
10711 // OpenMP 6.0, 15.8, target construct, restrictions:
10712 // * A list item in a map clause that is specified on a target construct
10713 // must have a base variable or base pointer.
10714 //
10715 // Map clauses on a target construct must either have a base pointer, or a
10716 // base-variable. So, if we don't have a base-pointer, that means that it
10717 // must have a base-variable, i.e. we have a map like `map(s)`, `map(s.x)`
10718 // etc. In such cases, we do not need to handle default map generation
10719 // for `s`.
10720 bool HasEntryWithoutAttachPtr =
10721 llvm::any_of(DeclComponentLists, [&](const auto &MapData) {
10722 OMPClauseMappableExprCommon::MappableExprComponentListRef
10723 Components = std::get<0>(MapData);
10724 return !MEHandler.getAttachPtrExpr(Components);
10725 });
10726
10727 // Generate default map info first if there's no direct map with CV as
10728 // the base-variable, or attach pointer.
10729 if (DeclComponentLists.empty() ||
10730 (!HasEntryWithCVAsAttachPtr && !HasEntryWithoutAttachPtr))
10731 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurInfo);
10732
10733 // If we have any information in the map clause, we use it, otherwise we
10734 // just do a default mapping.
10735 MEHandler.generateInfoForCaptureFromClauseInfo(
10736 DeclComponentLists, CI, *CV, CurInfo, OMPBuilder,
10737 /*OffsetForMemberOfFlag=*/CombinedInfo.BasePointers.size());
10738
10739 if (!CI->capturesThis())
10740 MappedVarSet.insert(CI->getCapturedVar());
10741 else
10742 MappedVarSet.insert(nullptr);
10743
10744 // Generate correct mapping for variables captured by reference in
10745 // lambdas.
10746 if (CI->capturesVariable())
10747 MEHandler.generateInfoForLambdaCaptures(CI->getCapturedVar(), *CV,
10748 CurInfo, LambdaPointers);
10749 }
10750 // We expect to have at least an element of information for this capture.
10751 assert(!CurInfo.BasePointers.empty() &&
10752 "Non-existing map pointer for capture!");
10753 assert(CurInfo.BasePointers.size() == CurInfo.Pointers.size() &&
10754 CurInfo.BasePointers.size() == CurInfo.Sizes.size() &&
10755 CurInfo.BasePointers.size() == CurInfo.Types.size() &&
10756 CurInfo.BasePointers.size() == CurInfo.Mappers.size() &&
10757 "Inconsistent map information sizes!");
10758
10759 // We need to append the results of this capture to what we already have.
10760 CombinedInfo.append(CurInfo);
10761 }
10762 // Adjust MEMBER_OF flags for the lambdas captures.
10763 MEHandler.adjustMemberOfForLambdaCaptures(
10764 OMPBuilder, LambdaPointers, CombinedInfo.BasePointers,
10765 CombinedInfo.Pointers, CombinedInfo.Types);
10766 }
10767 static void
10768 genMapInfo(MappableExprsHandler &MEHandler, CodeGenFunction &CGF,
10769 MappableExprsHandler::MapCombinedInfoTy &CombinedInfo,
10770 llvm::OpenMPIRBuilder &OMPBuilder,
10771 const llvm::DenseSet<CanonicalDeclPtr<const Decl>> &SkippedVarSet =
10772 llvm::DenseSet<CanonicalDeclPtr<const Decl>>()) {
10773
10774 CodeGenModule &CGM = CGF.CGM;
10775 // Map any list items in a map clause that were not captures because they
10776 // weren't referenced within the construct.
10777 MEHandler.generateAllInfo(CombinedInfo, OMPBuilder, SkippedVarSet);
10778
10779 auto FillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
10780 return emitMappingInformation(CGF, OMPBuilder, MapExpr);
10781 };
10782 if (CGM.getCodeGenOpts().getDebugInfo() !=
10783 llvm::codegenoptions::NoDebugInfo) {
10784 CombinedInfo.Names.resize(CombinedInfo.Exprs.size());
10785 llvm::transform(CombinedInfo.Exprs, CombinedInfo.Names.begin(),
10786 FillInfoMap);
10787 }
10788 }
10789
10790 static void genMapInfo(const OMPExecutableDirective &D, CodeGenFunction &CGF,
10791 const CapturedStmt &CS,
10792 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars,
10793 llvm::OpenMPIRBuilder &OMPBuilder,
10794 MappableExprsHandler::MapCombinedInfoTy &CombinedInfo) {
10795 // Get mappable expression information.
10796 MappableExprsHandler MEHandler(D, CGF);
10797 llvm::DenseSet<CanonicalDeclPtr<const Decl>> MappedVarSet;
10798
10799 genMapInfoForCaptures(MEHandler, CGF, CS, CapturedVars, OMPBuilder,
10800 MappedVarSet, CombinedInfo);
10801 genMapInfo(MEHandler, CGF, CombinedInfo, OMPBuilder, MappedVarSet);
10802 }
10803
10804 template <typename ClauseTy>
10805 static void
10806 emitClauseForBareTargetDirective(CodeGenFunction &CGF,
10807 const OMPExecutableDirective &D,
10808 llvm::SmallVectorImpl<llvm::Value *> &Values) {
10809 const auto *C = D.getSingleClause<ClauseTy>();
10810 assert(!C->varlist_empty() &&
10811 "ompx_bare requires explicit num_teams and thread_limit");
10812 CodeGenFunction::RunCleanupsScope Scope(CGF);
10813 for (auto *E : C->varlist()) {
10814 llvm::Value *V = CGF.EmitScalarExpr(E);
10815 Values.push_back(
10816 CGF.Builder.CreateIntCast(V, CGF.Int32Ty, /*isSigned=*/true));
10817 }
10818 }
10819
10820 static void emitTargetCallKernelLaunch(
10821 CGOpenMPRuntime *OMPRuntime, llvm::Function *OutlinedFn,
10822 const OMPExecutableDirective &D,
10823 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars, bool RequiresOuterTask,
10824 const CapturedStmt &CS, bool OffloadingMandatory,
10825 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
10826 llvm::Value *OutlinedFnID, CodeGenFunction::OMPTargetDataInfo &InputInfo,
10827 llvm::Value *&MapTypesArray, llvm::Value *&MapNamesArray,
10828 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
10829 const OMPLoopDirective &D)>
10830 SizeEmitter,
10831 CodeGenFunction &CGF, CodeGenModule &CGM) {
10832 llvm::OpenMPIRBuilder &OMPBuilder = OMPRuntime->getOMPBuilder();
10833
10834 // Fill up the arrays with all the captured variables.
10835 MappableExprsHandler::MapCombinedInfoTy CombinedInfo;
10836 CGOpenMPRuntime::TargetDataInfo Info;
10837 genMapInfo(D, CGF, CS, CapturedVars, OMPBuilder, CombinedInfo);
10838
10839 emitOffloadingArraysAndArgs(CGF, CombinedInfo, Info, OMPBuilder,
10840 /*IsNonContiguous=*/true, /*ForEndCall=*/false);
10841
10842 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
10843 InputInfo.BasePointersArray = Address(Info.RTArgs.BasePointersArray,
10844 CGF.VoidPtrTy, CGM.getPointerAlign());
10845 InputInfo.PointersArray =
10846 Address(Info.RTArgs.PointersArray, CGF.VoidPtrTy, CGM.getPointerAlign());
10847 InputInfo.SizesArray =
10848 Address(Info.RTArgs.SizesArray, CGF.Int64Ty, CGM.getPointerAlign());
10849 InputInfo.MappersArray =
10850 Address(Info.RTArgs.MappersArray, CGF.VoidPtrTy, CGM.getPointerAlign());
10851 MapTypesArray = Info.RTArgs.MapTypesArray;
10852 MapNamesArray = Info.RTArgs.MapNamesArray;
10853
10854 auto &&ThenGen = [&OMPRuntime, OutlinedFn, &D, &CapturedVars,
10855 RequiresOuterTask, &CS, OffloadingMandatory, Device,
10856 OutlinedFnID, &InputInfo, &MapTypesArray, &MapNamesArray,
10857 SizeEmitter](CodeGenFunction &CGF, PrePostActionTy &) {
10858 bool IsReverseOffloading = Device.getInt() == OMPC_DEVICE_ancestor;
10859
10860 if (IsReverseOffloading) {
10861 // Reverse offloading is not supported, so just execute on the host.
10862 // FIXME: This fallback solution is incorrect since it ignores the
10863 // OMP_TARGET_OFFLOAD environment variable. Instead it would be better to
10864 // assert here and ensure SEMA emits an error.
10865 emitTargetCallFallback(OMPRuntime, OutlinedFn, D, CapturedVars,
10866 RequiresOuterTask, CS, OffloadingMandatory, CGF);
10867 return;
10868 }
10869
10870 bool HasNoWait = D.hasClausesOfKind<OMPNowaitClause>();
10871 unsigned NumTargetItems = InputInfo.NumberOfTargetItems;
10872
10873 llvm::Value *BasePointersArray =
10874 InputInfo.BasePointersArray.emitRawPointer(CGF);
10875 llvm::Value *PointersArray = InputInfo.PointersArray.emitRawPointer(CGF);
10876 llvm::Value *SizesArray = InputInfo.SizesArray.emitRawPointer(CGF);
10877 llvm::Value *MappersArray = InputInfo.MappersArray.emitRawPointer(CGF);
10878
10879 auto &&EmitTargetCallFallbackCB =
10880 [&OMPRuntime, OutlinedFn, &D, &CapturedVars, RequiresOuterTask, &CS,
10881 OffloadingMandatory, &CGF](llvm::OpenMPIRBuilder::InsertPointTy IP)
10882 -> llvm::OpenMPIRBuilder::InsertPointTy {
10883 CGF.Builder.restoreIP(IP);
10884 emitTargetCallFallback(OMPRuntime, OutlinedFn, D, CapturedVars,
10885 RequiresOuterTask, CS, OffloadingMandatory, CGF);
10886 return CGF.Builder.saveIP();
10887 };
10888
10889 bool IsBare = D.hasClausesOfKind<OMPXBareClause>();
10890 SmallVector<llvm::Value *, 3> NumTeams;
10891 SmallVector<llvm::Value *, 3> NumThreads;
10892 if (IsBare) {
10893 emitClauseForBareTargetDirective<OMPNumTeamsClause>(CGF, D, NumTeams);
10894 emitClauseForBareTargetDirective<OMPThreadLimitClause>(CGF, D,
10895 NumThreads);
10896 } else {
10897 NumTeams.push_back(OMPRuntime->emitNumTeamsForTargetDirective(CGF, D));
10898 NumThreads.push_back(
10899 OMPRuntime->emitNumThreadsForTargetDirective(CGF, D));
10900 }
10901
10902 llvm::Value *DeviceID = emitDeviceID(Device, CGF);
10903 llvm::Value *RTLoc = OMPRuntime->emitUpdateLocation(CGF, D.getBeginLoc());
10904 llvm::Value *NumIterations =
10905 OMPRuntime->emitTargetNumIterationsCall(CGF, D, SizeEmitter);
10906 auto [DynCGroupMem, DynCGroupMemFallback] = emitDynCGroupMem(D, CGF);
10907 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
10908 CGF.AllocaInsertPt->getParent(), CGF.AllocaInsertPt->getIterator());
10909
10910 llvm::OpenMPIRBuilder::TargetDataRTArgs RTArgs(
10911 BasePointersArray, PointersArray, SizesArray, MapTypesArray,
10912 nullptr /* MapTypesArrayEnd */, MappersArray, MapNamesArray);
10913
10914 llvm::OpenMPIRBuilder::TargetKernelArgs Args(
10915 NumTargetItems, RTArgs, NumIterations, NumTeams, NumThreads,
10916 DynCGroupMem, HasNoWait, DynCGroupMemFallback);
10917
10918 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
10919 cantFail(OMPRuntime->getOMPBuilder().emitKernelLaunch(
10920 CGF.Builder, OutlinedFnID, EmitTargetCallFallbackCB, Args, DeviceID,
10921 RTLoc, AllocaIP));
10922 CGF.Builder.restoreIP(AfterIP);
10923 };
10924
10925 if (RequiresOuterTask)
10926 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
10927 else
10928 OMPRuntime->emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
10929 }
10930
10931 static void
10932 emitTargetCallElse(CGOpenMPRuntime *OMPRuntime, llvm::Function *OutlinedFn,
10933 const OMPExecutableDirective &D,
10934 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars,
10935 bool RequiresOuterTask, const CapturedStmt &CS,
10936 bool OffloadingMandatory, CodeGenFunction &CGF) {
10937
10938 // Notify that the host version must be executed.
10939 auto &&ElseGen =
10940 [&OMPRuntime, OutlinedFn, &D, &CapturedVars, RequiresOuterTask, &CS,
10941 OffloadingMandatory](CodeGenFunction &CGF, PrePostActionTy &) {
10942 emitTargetCallFallback(OMPRuntime, OutlinedFn, D, CapturedVars,
10943 RequiresOuterTask, CS, OffloadingMandatory, CGF);
10944 };
10945
10946 if (RequiresOuterTask) {
10947 CodeGenFunction::OMPTargetDataInfo InputInfo;
10948 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
10949 } else {
10950 OMPRuntime->emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
10951 }
10952 }
10953
10954 void CGOpenMPRuntime::emitTargetCall(
10955 CodeGenFunction &CGF, const OMPExecutableDirective &D,
10956 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
10957 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
10958 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
10959 const OMPLoopDirective &D)>
10960 SizeEmitter) {
10961 if (!CGF.HaveInsertPoint())
10962 return;
10963
10964 const bool OffloadingMandatory = !CGM.getLangOpts().OpenMPIsTargetDevice &&
10965 CGM.getLangOpts().OpenMPOffloadMandatory;
10966
10967 assert((OffloadingMandatory || OutlinedFn) && "Invalid outlined function!");
10968
10969 const bool RequiresOuterTask =
10970 D.hasClausesOfKind<OMPDependClause>() ||
10971 D.hasClausesOfKind<OMPNowaitClause>() ||
10972 D.hasClausesOfKind<OMPInReductionClause>() ||
10973 (CGM.getLangOpts().OpenMP >= 51 &&
10974 needsTaskBasedThreadLimit(D.getDirectiveKind()) &&
10975 D.hasClausesOfKind<OMPThreadLimitClause>());
10976 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
10977 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
10978 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
10979 PrePostActionTy &) {
10980 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
10981 };
10982 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
10983
10984 CodeGenFunction::OMPTargetDataInfo InputInfo;
10985 llvm::Value *MapTypesArray = nullptr;
10986 llvm::Value *MapNamesArray = nullptr;
10987
10988 auto &&TargetThenGen = [this, OutlinedFn, &D, &CapturedVars,
10989 RequiresOuterTask, &CS, OffloadingMandatory, Device,
10990 OutlinedFnID, &InputInfo, &MapTypesArray,
10991 &MapNamesArray, SizeEmitter](CodeGenFunction &CGF,
10992 PrePostActionTy &) {
10993 emitTargetCallKernelLaunch(this, OutlinedFn, D, CapturedVars,
10994 RequiresOuterTask, CS, OffloadingMandatory,
10995 Device, OutlinedFnID, InputInfo, MapTypesArray,
10996 MapNamesArray, SizeEmitter, CGF, CGM);
10997 };
10998
10999 auto &&TargetElseGen =
11000 [this, OutlinedFn, &D, &CapturedVars, RequiresOuterTask, &CS,
11001 OffloadingMandatory](CodeGenFunction &CGF, PrePostActionTy &) {
11002 emitTargetCallElse(this, OutlinedFn, D, CapturedVars, RequiresOuterTask,
11003 CS, OffloadingMandatory, CGF);
11004 };
11005
11006 // If we have a target function ID it means that we need to support
11007 // offloading, otherwise, just execute on the host. We need to execute on host
11008 // regardless of the conditional in the if clause if, e.g., the user do not
11009 // specify target triples.
11010 if (OutlinedFnID) {
11011 if (IfCond) {
11012 emitIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
11013 } else {
11014 RegionCodeGenTy ThenRCG(TargetThenGen);
11015 ThenRCG(CGF);
11016 }
11017 } else {
11018 RegionCodeGenTy ElseRCG(TargetElseGen);
11019 ElseRCG(CGF);
11020 }
11021 }
11022
11023 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
11024 StringRef ParentName) {
11025 if (!S)
11026 return;
11027
11028 // Register vtable from device for target data and target directives.
11029 // Add this block here since scanForTargetRegionsFunctions ignores
11030 // target data by checking if S is a executable directive (target).
11031 if (auto *E = dyn_cast<OMPExecutableDirective>(S);
11032 E && isOpenMPTargetDataManagementDirective(E->getDirectiveKind())) {
11033 // Don't need to check if it's device compile
11034 // since scanForTargetRegionsFunctions currently only called
11035 // in device compilation.
11036 registerVTable(*E);
11037 }
11038
11039 // Codegen OMP target directives that offload compute to the device.
11040 bool RequiresDeviceCodegen =
11041 isa<OMPExecutableDirective>(S) &&
11042 isOpenMPTargetExecutionDirective(
11043 cast<OMPExecutableDirective>(S)->getDirectiveKind());
11044
11045 if (RequiresDeviceCodegen) {
11046 const auto &E = *cast<OMPExecutableDirective>(S);
11047
11048 llvm::TargetRegionEntryInfo EntryInfo = getEntryInfoFromPresumedLoc(
11049 CGM, OMPBuilder, E.getBeginLoc(), ParentName);
11050
11051 // Is this a target region that should not be emitted as an entry point? If
11052 // so just signal we are done with this target region.
11053 if (!OMPBuilder.OffloadInfoManager.hasTargetRegionEntryInfo(EntryInfo))
11054 return;
11055
11056 switch (E.getDirectiveKind()) {
11057 case OMPD_target:
11058 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
11059 cast<OMPTargetDirective>(E));
11060 break;
11061 case OMPD_target_parallel:
11062 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
11063 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
11064 break;
11065 case OMPD_target_teams:
11066 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
11067 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
11068 break;
11069 case OMPD_target_teams_distribute:
11070 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
11071 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
11072 break;
11073 case OMPD_target_teams_distribute_simd:
11074 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
11075 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
11076 break;
11077 case OMPD_target_parallel_for:
11078 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
11079 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
11080 break;
11081 case OMPD_target_parallel_for_simd:
11082 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
11083 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
11084 break;
11085 case OMPD_target_simd:
11086 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
11087 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
11088 break;
11089 case OMPD_target_teams_distribute_parallel_for:
11090 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
11091 CGM, ParentName,
11092 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
11093 break;
11094 case OMPD_target_teams_distribute_parallel_for_simd:
11095 CodeGenFunction::
11096 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
11097 CGM, ParentName,
11098 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
11099 break;
11100 case OMPD_target_teams_loop:
11101 CodeGenFunction::EmitOMPTargetTeamsGenericLoopDeviceFunction(
11102 CGM, ParentName, cast<OMPTargetTeamsGenericLoopDirective>(E));
11103 break;
11104 case OMPD_target_parallel_loop:
11105 CodeGenFunction::EmitOMPTargetParallelGenericLoopDeviceFunction(
11106 CGM, ParentName, cast<OMPTargetParallelGenericLoopDirective>(E));
11107 break;
11108 case OMPD_parallel:
11109 case OMPD_for:
11110 case OMPD_parallel_for:
11111 case OMPD_parallel_master:
11112 case OMPD_parallel_sections:
11113 case OMPD_for_simd:
11114 case OMPD_parallel_for_simd:
11115 case OMPD_cancel:
11116 case OMPD_cancellation_point:
11117 case OMPD_ordered:
11118 case OMPD_threadprivate:
11119 case OMPD_allocate:
11120 case OMPD_task:
11121 case OMPD_simd:
11122 case OMPD_tile:
11123 case OMPD_unroll:
11124 case OMPD_sections:
11125 case OMPD_section:
11126 case OMPD_single:
11127 case OMPD_master:
11128 case OMPD_critical:
11129 case OMPD_taskyield:
11130 case OMPD_barrier:
11131 case OMPD_taskwait:
11132 case OMPD_taskgroup:
11133 case OMPD_atomic:
11134 case OMPD_flush:
11135 case OMPD_depobj:
11136 case OMPD_scan:
11137 case OMPD_teams:
11138 case OMPD_target_data:
11139 case OMPD_target_exit_data:
11140 case OMPD_target_enter_data:
11141 case OMPD_distribute:
11142 case OMPD_distribute_simd:
11143 case OMPD_distribute_parallel_for:
11144 case OMPD_distribute_parallel_for_simd:
11145 case OMPD_teams_distribute:
11146 case OMPD_teams_distribute_simd:
11147 case OMPD_teams_distribute_parallel_for:
11148 case OMPD_teams_distribute_parallel_for_simd:
11149 case OMPD_target_update:
11150 case OMPD_declare_simd:
11151 case OMPD_declare_variant:
11152 case OMPD_begin_declare_variant:
11153 case OMPD_end_declare_variant:
11154 case OMPD_declare_target:
11155 case OMPD_end_declare_target:
11156 case OMPD_declare_reduction:
11157 case OMPD_declare_mapper:
11158 case OMPD_taskloop:
11159 case OMPD_taskloop_simd:
11160 case OMPD_master_taskloop:
11161 case OMPD_master_taskloop_simd:
11162 case OMPD_parallel_master_taskloop:
11163 case OMPD_parallel_master_taskloop_simd:
11164 case OMPD_requires:
11165 case OMPD_metadirective:
11166 case OMPD_unknown:
11167 default:
11168 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
11169 }
11170 return;
11171 }
11172
11173 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
11174 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
11175 return;
11176
11177 scanForTargetRegionsFunctions(E->getRawStmt(), ParentName);
11178 return;
11179 }
11180
11181 // If this is a lambda function, look into its body.
11182 if (const auto *L = dyn_cast<LambdaExpr>(S))
11183 S = L->getBody();
11184
11185 // Keep looking for target regions recursively.
11186 for (const Stmt *II : S->children())
11187 scanForTargetRegionsFunctions(II, ParentName);
11188 }
11189
11190 static bool isAssumedToBeNotEmitted(const ValueDecl *VD, bool IsDevice) {
11191 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
11192 OMPDeclareTargetDeclAttr::getDeviceType(VD);
11193 if (!DevTy)
11194 return false;
11195 // Do not emit device_type(nohost) functions for the host.
11196 if (!IsDevice && DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
11197 return true;
11198 // Do not emit device_type(host) functions for the device.
11199 if (IsDevice && DevTy == OMPDeclareTargetDeclAttr::DT_Host)
11200 return true;
11201 return false;
11202 }
11203
11204 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
11205 // If emitting code for the host, we do not process FD here. Instead we do
11206 // the normal code generation.
11207 if (!CGM.getLangOpts().OpenMPIsTargetDevice) {
11208 if (const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
11209 if (isAssumedToBeNotEmitted(cast<ValueDecl>(FD),
11210 CGM.getLangOpts().OpenMPIsTargetDevice))
11211 return true;
11212 return false;
11213 }
11214
11215 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
11216 // Try to detect target regions in the function.
11217 if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
11218 StringRef Name = CGM.getMangledName(GD);
11219 scanForTargetRegionsFunctions(FD->getBody(), Name);
11220 if (isAssumedToBeNotEmitted(cast<ValueDecl>(FD),
11221 CGM.getLangOpts().OpenMPIsTargetDevice))
11222 return true;
11223 }
11224
11225 // Do not to emit function if it is not marked as declare target.
11226 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
11227 AlreadyEmittedTargetDecls.count(VD) == 0;
11228 }
11229
11230 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
11231 if (isAssumedToBeNotEmitted(cast<ValueDecl>(GD.getDecl()),
11232 CGM.getLangOpts().OpenMPIsTargetDevice))
11233 return true;
11234
11235 if (!CGM.getLangOpts().OpenMPIsTargetDevice)
11236 return false;
11237
11238 // Check if there are Ctors/Dtors in this declaration and look for target
11239 // regions in it. We use the complete variant to produce the kernel name
11240 // mangling.
11241 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
11242 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
11243 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
11244 StringRef ParentName =
11245 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
11246 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
11247 }
11248 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
11249 StringRef ParentName =
11250 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
11251 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
11252 }
11253 }
11254
11255 // Do not to emit variable if it is not marked as declare target.
11256 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
11257 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
11258 cast<VarDecl>(GD.getDecl()));
11259 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
11260 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
11261 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
11262 HasRequiresUnifiedSharedMemory)) {
11263 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
11264 return true;
11265 }
11266 return false;
11267 }
11268
11269 void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
11270 llvm::Constant *Addr) {
11271 if (CGM.getLangOpts().OMPTargetTriples.empty() &&
11272 !CGM.getLangOpts().OpenMPIsTargetDevice)
11273 return;
11274
11275 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
11276 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
11277
11278 // If this is an 'extern' declaration we defer to the canonical definition and
11279 // do not emit an offloading entry.
11280 if (Res && *Res != OMPDeclareTargetDeclAttr::MT_Link &&
11281 VD->hasExternalStorage())
11282 return;
11283
11284 if (!Res) {
11285 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
11286 // Register non-target variables being emitted in device code (debug info
11287 // may cause this).
11288 StringRef VarName = CGM.getMangledName(VD);
11289 EmittedNonTargetVariables.try_emplace(VarName, Addr);
11290 }
11291 return;
11292 }
11293
11294 auto AddrOfGlobal = [&VD, this]() { return CGM.GetAddrOfGlobal(VD); };
11295 auto LinkageForVariable = [&VD, this]() {
11296 return CGM.getLLVMLinkageVarDefinition(VD);
11297 };
11298
11299 std::vector<llvm::GlobalVariable *> GeneratedRefs;
11300 OMPBuilder.registerTargetGlobalVariable(
11301 convertCaptureClause(VD), convertDeviceClause(VD),
11302 VD->hasDefinition(CGM.getContext()) == VarDecl::DeclarationOnly,
11303 VD->isExternallyVisible(),
11304 getEntryInfoFromPresumedLoc(CGM, OMPBuilder,
11305 VD->getCanonicalDecl()->getBeginLoc()),
11306 CGM.getMangledName(VD), GeneratedRefs, CGM.getLangOpts().OpenMPSimd,
11307 CGM.getLangOpts().OMPTargetTriples, AddrOfGlobal, LinkageForVariable,
11308 CGM.getTypes().ConvertTypeForMem(
11309 CGM.getContext().getPointerType(VD->getType())),
11310 Addr);
11311
11312 for (auto *ref : GeneratedRefs)
11313 CGM.addCompilerUsedGlobal(ref);
11314 }
11315
11316 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
11317 if (isa<FunctionDecl>(GD.getDecl()) ||
11318 isa<OMPDeclareReductionDecl>(GD.getDecl()))
11319 return emitTargetFunctions(GD);
11320
11321 return emitTargetGlobalVariable(GD);
11322 }
11323
11324 void CGOpenMPRuntime::emitDeferredTargetDecls() const {
11325 for (const VarDecl *VD : DeferredGlobalVariables) {
11326 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
11327 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
11328 if (!Res)
11329 continue;
11330 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
11331 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
11332 !HasRequiresUnifiedSharedMemory) {
11333 CGM.EmitGlobal(VD);
11334 } else {
11335 assert((*Res == OMPDeclareTargetDeclAttr::MT_Link ||
11336 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
11337 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
11338 HasRequiresUnifiedSharedMemory)) &&
11339 "Expected link clause or to clause with unified memory.");
11340 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
11341 }
11342 }
11343 }
11344
11345 void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
11346 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
11347 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
11348 " Expected target-based directive.");
11349 }
11350
11351 void CGOpenMPRuntime::processRequiresDirective(const OMPRequiresDecl *D) {
11352 for (const OMPClause *Clause : D->clauselists()) {
11353 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
11354 HasRequiresUnifiedSharedMemory = true;
11355 OMPBuilder.Config.setHasRequiresUnifiedSharedMemory(true);
11356 } else if (const auto *AC =
11357 dyn_cast<OMPAtomicDefaultMemOrderClause>(Clause)) {
11358 switch (AC->getAtomicDefaultMemOrderKind()) {
11359 case OMPC_ATOMIC_DEFAULT_MEM_ORDER_acq_rel:
11360 RequiresAtomicOrdering = llvm::AtomicOrdering::AcquireRelease;
11361 break;
11362 case OMPC_ATOMIC_DEFAULT_MEM_ORDER_seq_cst:
11363 RequiresAtomicOrdering = llvm::AtomicOrdering::SequentiallyConsistent;
11364 break;
11365 case OMPC_ATOMIC_DEFAULT_MEM_ORDER_relaxed:
11366 RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic;
11367 break;
11368 case OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown:
11369 break;
11370 }
11371 }
11372 }
11373 }
11374
11375 llvm::AtomicOrdering CGOpenMPRuntime::getDefaultMemoryOrdering() const {
11376 return RequiresAtomicOrdering;
11377 }
11378
11379 bool CGOpenMPRuntime::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
11380 LangAS &AS) {
11381 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
11382 return false;
11383 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
11384 switch(A->getAllocatorType()) {
11385 case OMPAllocateDeclAttr::OMPNullMemAlloc:
11386 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
11387 // Not supported, fallback to the default mem space.
11388 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
11389 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
11390 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
11391 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
11392 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
11393 case OMPAllocateDeclAttr::OMPConstMemAlloc:
11394 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
11395 AS = LangAS::Default;
11396 return true;
11397 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
11398 llvm_unreachable("Expected predefined allocator for the variables with the "
11399 "static storage.");
11400 }
11401 return false;
11402 }
11403
11404 bool CGOpenMPRuntime::hasRequiresUnifiedSharedMemory() const {
11405 return HasRequiresUnifiedSharedMemory;
11406 }
11407
11408 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
11409 CodeGenModule &CGM)
11410 : CGM(CGM) {
11411 if (CGM.getLangOpts().OpenMPIsTargetDevice) {
11412 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
11413 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
11414 }
11415 }
11416
11417 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
11418 if (CGM.getLangOpts().OpenMPIsTargetDevice)
11419 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
11420 }
11421
11422 bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
11423 if (!CGM.getLangOpts().OpenMPIsTargetDevice || !ShouldMarkAsGlobal)
11424 return true;
11425
11426 const auto *D = cast<FunctionDecl>(GD.getDecl());
11427 // Do not to emit function if it is marked as declare target as it was already
11428 // emitted.
11429 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
11430 if (D->hasBody() && AlreadyEmittedTargetDecls.count(D) == 0) {
11431 if (auto *F = dyn_cast_or_null<llvm::Function>(
11432 CGM.GetGlobalValue(CGM.getMangledName(GD))))
11433 return !F->isDeclaration();
11434 return false;
11435 }
11436 return true;
11437 }
11438
11439 return !AlreadyEmittedTargetDecls.insert(D).second;
11440 }
11441
11442 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
11443 const OMPExecutableDirective &D,
11444 SourceLocation Loc,
11445 llvm::Function *OutlinedFn,
11446 ArrayRef<llvm::Value *> CapturedVars) {
11447 if (!CGF.HaveInsertPoint())
11448 return;
11449
11450 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
11451 CodeGenFunction::RunCleanupsScope Scope(CGF);
11452
11453 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
11454 llvm::Value *Args[] = {
11455 RTLoc,
11456 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
11457 OutlinedFn};
11458 llvm::SmallVector<llvm::Value *, 16> RealArgs;
11459 RealArgs.append(std::begin(Args), std::end(Args));
11460 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
11461
11462 llvm::FunctionCallee RTLFn = OMPBuilder.getOrCreateRuntimeFunction(
11463 CGM.getModule(), OMPRTL___kmpc_fork_teams);
11464 CGF.EmitRuntimeCall(RTLFn, RealArgs);
11465 }
11466
11467 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
11468 const Expr *NumTeams,
11469 const Expr *ThreadLimit,
11470 SourceLocation Loc) {
11471 if (!CGF.HaveInsertPoint())
11472 return;
11473
11474 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
11475
11476 llvm::Value *NumTeamsVal =
11477 NumTeams
11478 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
11479 CGF.CGM.Int32Ty, /* isSigned = */ true)
11480 : CGF.Builder.getInt32(0);
11481
11482 llvm::Value *ThreadLimitVal =
11483 ThreadLimit
11484 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
11485 CGF.CGM.Int32Ty, /* isSigned = */ true)
11486 : CGF.Builder.getInt32(0);
11487
11488 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
11489 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
11490 ThreadLimitVal};
11491 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
11492 CGM.getModule(), OMPRTL___kmpc_push_num_teams),
11493 PushNumTeamsArgs);
11494 }
11495
11496 void CGOpenMPRuntime::emitThreadLimitClause(CodeGenFunction &CGF,
11497 const Expr *ThreadLimit,
11498 SourceLocation Loc) {
11499 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
11500 llvm::Value *ThreadLimitVal =
11501 ThreadLimit
11502 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
11503 CGF.CGM.Int32Ty, /* isSigned = */ true)
11504 : CGF.Builder.getInt32(0);
11505
11506 // Build call __kmpc_set_thread_limit(&loc, global_tid, thread_limit)
11507 llvm::Value *ThreadLimitArgs[] = {RTLoc, getThreadID(CGF, Loc),
11508 ThreadLimitVal};
11509 CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
11510 CGM.getModule(), OMPRTL___kmpc_set_thread_limit),
11511 ThreadLimitArgs);
11512 }
11513
11514 void CGOpenMPRuntime::emitTargetDataCalls(
11515 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
11516 const Expr *Device, const RegionCodeGenTy &CodeGen,
11517 CGOpenMPRuntime::TargetDataInfo &Info) {
11518 if (!CGF.HaveInsertPoint())
11519 return;
11520
11521 // Action used to replace the default codegen action and turn privatization
11522 // off.
11523 PrePostActionTy NoPrivAction;
11524
11525 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
11526
11527 llvm::Value *IfCondVal = nullptr;
11528 if (IfCond)
11529 IfCondVal = CGF.EvaluateExprAsBool(IfCond);
11530
11531 // Emit device ID if any.
11532 llvm::Value *DeviceID = nullptr;
11533 if (Device) {
11534 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
11535 CGF.Int64Ty, /*isSigned=*/true);
11536 } else {
11537 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
11538 }
11539
11540 // Fill up the arrays with all the mapped variables.
11541 MappableExprsHandler::MapCombinedInfoTy CombinedInfo;
11542 auto GenMapInfoCB =
11543 [&](InsertPointTy CodeGenIP) -> llvm::OpenMPIRBuilder::MapInfosTy & {
11544 CGF.Builder.restoreIP(CodeGenIP);
11545 // Get map clause information.
11546 MappableExprsHandler MEHandler(D, CGF);
11547 MEHandler.generateAllInfo(CombinedInfo, OMPBuilder);
11548
11549 auto FillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
11550 return emitMappingInformation(CGF, OMPBuilder, MapExpr);
11551 };
11552 if (CGM.getCodeGenOpts().getDebugInfo() !=
11553 llvm::codegenoptions::NoDebugInfo) {
11554 CombinedInfo.Names.resize(CombinedInfo.Exprs.size());
11555 llvm::transform(CombinedInfo.Exprs, CombinedInfo.Names.begin(),
11556 FillInfoMap);
11557 }
11558
11559 return CombinedInfo;
11560 };
11561 using BodyGenTy = llvm::OpenMPIRBuilder::BodyGenTy;
11562 auto BodyCB = [&](InsertPointTy CodeGenIP, BodyGenTy BodyGenType) {
11563 CGF.Builder.restoreIP(CodeGenIP);
11564 switch (BodyGenType) {
11565 case BodyGenTy::Priv:
11566 if (!Info.CaptureDeviceAddrMap.empty())
11567 CodeGen(CGF);
11568 break;
11569 case BodyGenTy::DupNoPriv:
11570 if (!Info.CaptureDeviceAddrMap.empty()) {
11571 CodeGen.setAction(NoPrivAction);
11572 CodeGen(CGF);
11573 }
11574 break;
11575 case BodyGenTy::NoPriv:
11576 if (Info.CaptureDeviceAddrMap.empty()) {
11577 CodeGen.setAction(NoPrivAction);
11578 CodeGen(CGF);
11579 }
11580 break;
11581 }
11582 return InsertPointTy(CGF.Builder.GetInsertBlock(),
11583 CGF.Builder.GetInsertPoint());
11584 };
11585
11586 auto DeviceAddrCB = [&](unsigned int I, llvm::Value *NewDecl) {
11587 if (const ValueDecl *DevVD = CombinedInfo.DevicePtrDecls[I]) {
11588 Info.CaptureDeviceAddrMap.try_emplace(DevVD, NewDecl);
11589 }
11590 };
11591
11592 auto CustomMapperCB = [&](unsigned int I) {
11593 llvm::Function *MFunc = nullptr;
11594 if (CombinedInfo.Mappers[I]) {
11595 Info.HasMapper = true;
11596 MFunc = CGF.CGM.getOpenMPRuntime().getOrCreateUserDefinedMapperFunc(
11597 cast<OMPDeclareMapperDecl>(CombinedInfo.Mappers[I]));
11598 }
11599 return MFunc;
11600 };
11601
11602 // Source location for the ident struct
11603 llvm::Value *RTLoc = emitUpdateLocation(CGF, D.getBeginLoc());
11604
11605 InsertPointTy AllocaIP(CGF.AllocaInsertPt->getParent(),
11606 CGF.AllocaInsertPt->getIterator());
11607 InsertPointTy CodeGenIP(CGF.Builder.GetInsertBlock(),
11608 CGF.Builder.GetInsertPoint());
11609 llvm::OpenMPIRBuilder::LocationDescription OmpLoc(CodeGenIP);
11610 llvm::OpenMPIRBuilder::InsertPointTy AfterIP =
11611 cantFail(OMPBuilder.createTargetData(
11612 OmpLoc, AllocaIP, CodeGenIP, DeviceID, IfCondVal, Info, GenMapInfoCB,
11613 CustomMapperCB,
11614 /*MapperFunc=*/nullptr, BodyCB, DeviceAddrCB, RTLoc));
11615 CGF.Builder.restoreIP(AfterIP);
11616 }
11617
11618 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
11619 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
11620 const Expr *Device) {
11621 if (!CGF.HaveInsertPoint())
11622 return;
11623
11624 assert((isa<OMPTargetEnterDataDirective>(D) ||
11625 isa<OMPTargetExitDataDirective>(D) ||
11626 isa<OMPTargetUpdateDirective>(D)) &&
11627 "Expecting either target enter, exit data, or update directives.");
11628
11629 CodeGenFunction::OMPTargetDataInfo InputInfo;
11630 llvm::Value *MapTypesArray = nullptr;
11631 llvm::Value *MapNamesArray = nullptr;
11632 // Generate the code for the opening of the data environment.
11633 auto &&ThenGen = [this, &D, Device, &InputInfo, &MapTypesArray,
11634 &MapNamesArray](CodeGenFunction &CGF, PrePostActionTy &) {
11635 // Emit device ID if any.
11636 llvm::Value *DeviceID = nullptr;
11637 if (Device) {
11638 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
11639 CGF.Int64Ty, /*isSigned=*/true);
11640 } else {
11641 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
11642 }
11643
11644 // Emit the number of elements in the offloading arrays.
11645 llvm::Constant *PointerNum =
11646 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
11647
11648 // Source location for the ident struct
11649 llvm::Value *RTLoc = emitUpdateLocation(CGF, D.getBeginLoc());
11650
11651 SmallVector<llvm::Value *, 13> OffloadingArgs(
11652 {RTLoc, DeviceID, PointerNum,
11653 InputInfo.BasePointersArray.emitRawPointer(CGF),
11654 InputInfo.PointersArray.emitRawPointer(CGF),
11655 InputInfo.SizesArray.emitRawPointer(CGF), MapTypesArray, MapNamesArray,
11656 InputInfo.MappersArray.emitRawPointer(CGF)});
11657
11658 // Select the right runtime function call for each standalone
11659 // directive.
11660 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
11661 RuntimeFunction RTLFn;
11662 switch (D.getDirectiveKind()) {
11663 case OMPD_target_enter_data:
11664 RTLFn = HasNowait ? OMPRTL___tgt_target_data_begin_nowait_mapper
11665 : OMPRTL___tgt_target_data_begin_mapper;
11666 break;
11667 case OMPD_target_exit_data:
11668 RTLFn = HasNowait ? OMPRTL___tgt_target_data_end_nowait_mapper
11669 : OMPRTL___tgt_target_data_end_mapper;
11670 break;
11671 case OMPD_target_update:
11672 RTLFn = HasNowait ? OMPRTL___tgt_target_data_update_nowait_mapper
11673 : OMPRTL___tgt_target_data_update_mapper;
11674 break;
11675 case OMPD_parallel:
11676 case OMPD_for:
11677 case OMPD_parallel_for:
11678 case OMPD_parallel_master:
11679 case OMPD_parallel_sections:
11680 case OMPD_for_simd:
11681 case OMPD_parallel_for_simd:
11682 case OMPD_cancel:
11683 case OMPD_cancellation_point:
11684 case OMPD_ordered:
11685 case OMPD_threadprivate:
11686 case OMPD_allocate:
11687 case OMPD_task:
11688 case OMPD_simd:
11689 case OMPD_tile:
11690 case OMPD_unroll:
11691 case OMPD_sections:
11692 case OMPD_section:
11693 case OMPD_single:
11694 case OMPD_master:
11695 case OMPD_critical:
11696 case OMPD_taskyield:
11697 case OMPD_barrier:
11698 case OMPD_taskwait:
11699 case OMPD_taskgroup:
11700 case OMPD_atomic:
11701 case OMPD_flush:
11702 case OMPD_depobj:
11703 case OMPD_scan:
11704 case OMPD_teams:
11705 case OMPD_target_data:
11706 case OMPD_distribute:
11707 case OMPD_distribute_simd:
11708 case OMPD_distribute_parallel_for:
11709 case OMPD_distribute_parallel_for_simd:
11710 case OMPD_teams_distribute:
11711 case OMPD_teams_distribute_simd:
11712 case OMPD_teams_distribute_parallel_for:
11713 case OMPD_teams_distribute_parallel_for_simd:
11714 case OMPD_declare_simd:
11715 case OMPD_declare_variant:
11716 case OMPD_begin_declare_variant:
11717 case OMPD_end_declare_variant:
11718 case OMPD_declare_target:
11719 case OMPD_end_declare_target:
11720 case OMPD_declare_reduction:
11721 case OMPD_declare_mapper:
11722 case OMPD_taskloop:
11723 case OMPD_taskloop_simd:
11724 case OMPD_master_taskloop:
11725 case OMPD_master_taskloop_simd:
11726 case OMPD_parallel_master_taskloop:
11727 case OMPD_parallel_master_taskloop_simd:
11728 case OMPD_target:
11729 case OMPD_target_simd:
11730 case OMPD_target_teams_distribute:
11731 case OMPD_target_teams_distribute_simd:
11732 case OMPD_target_teams_distribute_parallel_for:
11733 case OMPD_target_teams_distribute_parallel_for_simd:
11734 case OMPD_target_teams:
11735 case OMPD_target_parallel:
11736 case OMPD_target_parallel_for:
11737 case OMPD_target_parallel_for_simd:
11738 case OMPD_requires:
11739 case OMPD_metadirective:
11740 case OMPD_unknown:
11741 default:
11742 llvm_unreachable("Unexpected standalone target data directive.");
11743 break;
11744 }
11745 if (HasNowait) {
11746 OffloadingArgs.push_back(llvm::Constant::getNullValue(CGF.Int32Ty));
11747 OffloadingArgs.push_back(llvm::Constant::getNullValue(CGF.VoidPtrTy));
11748 OffloadingArgs.push_back(llvm::Constant::getNullValue(CGF.Int32Ty));
11749 OffloadingArgs.push_back(llvm::Constant::getNullValue(CGF.VoidPtrTy));
11750 }
11751 CGF.EmitRuntimeCall(
11752 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), RTLFn),
11753 OffloadingArgs);
11754 };
11755
11756 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
11757 &MapNamesArray](CodeGenFunction &CGF,
11758 PrePostActionTy &) {
11759 // Fill up the arrays with all the mapped variables.
11760 MappableExprsHandler::MapCombinedInfoTy CombinedInfo;
11761 CGOpenMPRuntime::TargetDataInfo Info;
11762 MappableExprsHandler MEHandler(D, CGF);
11763 genMapInfo(MEHandler, CGF, CombinedInfo, OMPBuilder);
11764 emitOffloadingArraysAndArgs(CGF, CombinedInfo, Info, OMPBuilder,
11765 /*IsNonContiguous=*/true, /*ForEndCall=*/false);
11766
11767 bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>() ||
11768 D.hasClausesOfKind<OMPNowaitClause>();
11769
11770 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
11771 InputInfo.BasePointersArray = Address(Info.RTArgs.BasePointersArray,
11772 CGF.VoidPtrTy, CGM.getPointerAlign());
11773 InputInfo.PointersArray = Address(Info.RTArgs.PointersArray, CGF.VoidPtrTy,
11774 CGM.getPointerAlign());
11775 InputInfo.SizesArray =
11776 Address(Info.RTArgs.SizesArray, CGF.Int64Ty, CGM.getPointerAlign());
11777 InputInfo.MappersArray =
11778 Address(Info.RTArgs.MappersArray, CGF.VoidPtrTy, CGM.getPointerAlign());
11779 MapTypesArray = Info.RTArgs.MapTypesArray;
11780 MapNamesArray = Info.RTArgs.MapNamesArray;
11781 if (RequiresOuterTask)
11782 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
11783 else
11784 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
11785 };
11786
11787 if (IfCond) {
11788 emitIfClause(CGF, IfCond, TargetThenGen,
11789 [](CodeGenFunction &CGF, PrePostActionTy &) {});
11790 } else {
11791 RegionCodeGenTy ThenRCG(TargetThenGen);
11792 ThenRCG(CGF);
11793 }
11794 }
11795
11796 namespace {
11797 /// Kind of parameter in a function with 'declare simd' directive.
11798 enum ParamKindTy {
11799 Linear,
11800 LinearRef,
11801 LinearUVal,
11802 LinearVal,
11803 Uniform,
11804 Vector,
11805 };
11806 /// Attribute set of the parameter.
11807 struct ParamAttrTy {
11808 ParamKindTy Kind = Vector;
11809 llvm::APSInt StrideOrArg;
11810 llvm::APSInt Alignment;
11811 bool HasVarStride = false;
11812 };
11813 } // namespace
11814
11815 static unsigned evaluateCDTSize(const FunctionDecl *FD,
11816 ArrayRef<ParamAttrTy> ParamAttrs) {
11817 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
11818 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
11819 // of that clause. The VLEN value must be power of 2.
11820 // In other case the notion of the function`s "characteristic data type" (CDT)
11821 // is used to compute the vector length.
11822 // CDT is defined in the following order:
11823 // a) For non-void function, the CDT is the return type.
11824 // b) If the function has any non-uniform, non-linear parameters, then the
11825 // CDT is the type of the first such parameter.
11826 // c) If the CDT determined by a) or b) above is struct, union, or class
11827 // type which is pass-by-value (except for the type that maps to the
11828 // built-in complex data type), the characteristic data type is int.
11829 // d) If none of the above three cases is applicable, the CDT is int.
11830 // The VLEN is then determined based on the CDT and the size of vector
11831 // register of that ISA for which current vector version is generated. The
11832 // VLEN is computed using the formula below:
11833 // VLEN = sizeof(vector_register) / sizeof(CDT),
11834 // where vector register size specified in section 3.2.1 Registers and the
11835 // Stack Frame of original AMD64 ABI document.
11836 QualType RetType = FD->getReturnType();
11837 if (RetType.isNull())
11838 return 0;
11839 ASTContext &C = FD->getASTContext();
11840 QualType CDT;
11841 if (!RetType.isNull() && !RetType->isVoidType()) {
11842 CDT = RetType;
11843 } else {
11844 unsigned Offset = 0;
11845 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11846 if (ParamAttrs[Offset].Kind == Vector)
11847 CDT = C.getPointerType(C.getCanonicalTagType(MD->getParent()));
11848 ++Offset;
11849 }
11850 if (CDT.isNull()) {
11851 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
11852 if (ParamAttrs[I + Offset].Kind == Vector) {
11853 CDT = FD->getParamDecl(I)->getType();
11854 break;
11855 }
11856 }
11857 }
11858 }
11859 if (CDT.isNull())
11860 CDT = C.IntTy;
11861 CDT = CDT->getCanonicalTypeUnqualified();
11862 if (CDT->isRecordType() || CDT->isUnionType())
11863 CDT = C.IntTy;
11864 return C.getTypeSize(CDT);
11865 }
11866
11867 /// Mangle the parameter part of the vector function name according to
11868 /// their OpenMP classification. The mangling function is defined in
11869 /// section 4.5 of the AAVFABI(2021Q1).
11870 static std::string mangleVectorParameters(ArrayRef<ParamAttrTy> ParamAttrs) {
11871 SmallString<256> Buffer;
11872 llvm::raw_svector_ostream Out(Buffer);
11873 for (const auto &ParamAttr : ParamAttrs) {
11874 switch (ParamAttr.Kind) {
11875 case Linear:
11876 Out << 'l';
11877 break;
11878 case LinearRef:
11879 Out << 'R';
11880 break;
11881 case LinearUVal:
11882 Out << 'U';
11883 break;
11884 case LinearVal:
11885 Out << 'L';
11886 break;
11887 case Uniform:
11888 Out << 'u';
11889 break;
11890 case Vector:
11891 Out << 'v';
11892 break;
11893 }
11894 if (ParamAttr.HasVarStride)
11895 Out << "s" << ParamAttr.StrideOrArg;
11896 else if (ParamAttr.Kind == Linear || ParamAttr.Kind == LinearRef ||
11897 ParamAttr.Kind == LinearUVal || ParamAttr.Kind == LinearVal) {
11898 // Don't print the step value if it is not present or if it is
11899 // equal to 1.
11900 if (ParamAttr.StrideOrArg < 0)
11901 Out << 'n' << -ParamAttr.StrideOrArg;
11902 else if (ParamAttr.StrideOrArg != 1)
11903 Out << ParamAttr.StrideOrArg;
11904 }
11905
11906 if (!!ParamAttr.Alignment)
11907 Out << 'a' << ParamAttr.Alignment;
11908 }
11909
11910 return std::string(Out.str());
11911 }
11912
11913 static void
11914 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
11915 const llvm::APSInt &VLENVal,
11916 ArrayRef<ParamAttrTy> ParamAttrs,
11917 OMPDeclareSimdDeclAttr::BranchStateTy State) {
11918 struct ISADataTy {
11919 char ISA;
11920 unsigned VecRegSize;
11921 };
11922 ISADataTy ISAData[] = {
11923 {
11924 'b', 128
11925 }, // SSE
11926 {
11927 'c', 256
11928 }, // AVX
11929 {
11930 'd', 256
11931 }, // AVX2
11932 {
11933 'e', 512
11934 }, // AVX512
11935 };
11936 llvm::SmallVector<char, 2> Masked;
11937 switch (State) {
11938 case OMPDeclareSimdDeclAttr::BS_Undefined:
11939 Masked.push_back('N');
11940 Masked.push_back('M');
11941 break;
11942 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
11943 Masked.push_back('N');
11944 break;
11945 case OMPDeclareSimdDeclAttr::BS_Inbranch:
11946 Masked.push_back('M');
11947 break;
11948 }
11949 for (char Mask : Masked) {
11950 for (const ISADataTy &Data : ISAData) {
11951 SmallString<256> Buffer;
11952 llvm::raw_svector_ostream Out(Buffer);
11953 Out << "_ZGV" << Data.ISA << Mask;
11954 if (!VLENVal) {
11955 unsigned NumElts = evaluateCDTSize(FD, ParamAttrs);
11956 assert(NumElts && "Non-zero simdlen/cdtsize expected");
11957 Out << llvm::APSInt::getUnsigned(Data.VecRegSize / NumElts);
11958 } else {
11959 Out << VLENVal;
11960 }
11961 Out << mangleVectorParameters(ParamAttrs);
11962 Out << '_' << Fn->getName();
11963 Fn->addFnAttr(Out.str());
11964 }
11965 }
11966 }
11967
11968 // This are the Functions that are needed to mangle the name of the
11969 // vector functions generated by the compiler, according to the rules
11970 // defined in the "Vector Function ABI specifications for AArch64",
11971 // available at
11972 // https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi.
11973
11974 /// Maps To Vector (MTV), as defined in 4.1.1 of the AAVFABI (2021Q1).
11975 static bool getAArch64MTV(QualType QT, ParamKindTy Kind) {
11976 QT = QT.getCanonicalType();
11977
11978 if (QT->isVoidType())
11979 return false;
11980
11981 if (Kind == ParamKindTy::Uniform)
11982 return false;
11983
11984 if (Kind == ParamKindTy::LinearUVal || Kind == ParamKindTy::LinearRef)
11985 return false;
11986
11987 if ((Kind == ParamKindTy::Linear || Kind == ParamKindTy::LinearVal) &&
11988 !QT->isReferenceType())
11989 return false;
11990
11991 return true;
11992 }
11993
11994 /// Pass By Value (PBV), as defined in 3.1.2 of the AAVFABI.
11995 static bool getAArch64PBV(QualType QT, ASTContext &C) {
11996 QT = QT.getCanonicalType();
11997 unsigned Size = C.getTypeSize(QT);
11998
11999 // Only scalars and complex within 16 bytes wide set PVB to true.
12000 if (Size != 8 && Size != 16 && Size != 32 && Size != 64 && Size != 128)
12001 return false;
12002
12003 if (QT->isFloatingType())
12004 return true;
12005
12006 if (QT->isIntegerType())
12007 return true;
12008
12009 if (QT->isPointerType())
12010 return true;
12011
12012 // TODO: Add support for complex types (section 3.1.2, item 2).
12013
12014 return false;
12015 }
12016
12017 /// Computes the lane size (LS) of a return type or of an input parameter,
12018 /// as defined by `LS(P)` in 3.2.1 of the AAVFABI.
12019 /// TODO: Add support for references, section 3.2.1, item 1.
12020 static unsigned getAArch64LS(QualType QT, ParamKindTy Kind, ASTContext &C) {
12021 if (!getAArch64MTV(QT, Kind) && QT.getCanonicalType()->isPointerType()) {
12022 QualType PTy = QT.getCanonicalType()->getPointeeType();
12023 if (getAArch64PBV(PTy, C))
12024 return C.getTypeSize(PTy);
12025 }
12026 if (getAArch64PBV(QT, C))
12027 return C.getTypeSize(QT);
12028
12029 return C.getTypeSize(C.getUIntPtrType());
12030 }
12031
12032 // Get Narrowest Data Size (NDS) and Widest Data Size (WDS) from the
12033 // signature of the scalar function, as defined in 3.2.2 of the
12034 // AAVFABI.
12035 static std::tuple<unsigned, unsigned, bool>
12036 getNDSWDS(const FunctionDecl *FD, ArrayRef<ParamAttrTy> ParamAttrs) {
12037 QualType RetType = FD->getReturnType().getCanonicalType();
12038
12039 ASTContext &C = FD->getASTContext();
12040
12041 bool OutputBecomesInput = false;
12042
12043 llvm::SmallVector<unsigned, 8> Sizes;
12044 if (!RetType->isVoidType()) {
12045 Sizes.push_back(getAArch64LS(RetType, ParamKindTy::Vector, C));
12046 if (!getAArch64PBV(RetType, C) && getAArch64MTV(RetType, {}))
12047 OutputBecomesInput = true;
12048 }
12049 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
12050 QualType QT = FD->getParamDecl(I)->getType().getCanonicalType();
12051 Sizes.push_back(getAArch64LS(QT, ParamAttrs[I].Kind, C));
12052 }
12053
12054 assert(!Sizes.empty() && "Unable to determine NDS and WDS.");
12055 // The LS of a function parameter / return value can only be a power
12056 // of 2, starting from 8 bits, up to 128.
12057 assert(llvm::all_of(Sizes,
12058 [](unsigned Size) {
12059 return Size == 8 || Size == 16 || Size == 32 ||
12060 Size == 64 || Size == 128;
12061 }) &&
12062 "Invalid size");
12063
12064 return std::make_tuple(*llvm::min_element(Sizes), *llvm::max_element(Sizes),
12065 OutputBecomesInput);
12066 }
12067
12068 // Function used to add the attribute. The parameter `VLEN` is
12069 // templated to allow the use of "x" when targeting scalable functions
12070 // for SVE.
12071 template <typename T>
12072 static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix,
12073 char ISA, StringRef ParSeq,
12074 StringRef MangledName, bool OutputBecomesInput,
12075 llvm::Function *Fn) {
12076 SmallString<256> Buffer;
12077 llvm::raw_svector_ostream Out(Buffer);
12078 Out << Prefix << ISA << LMask << VLEN;
12079 if (OutputBecomesInput)
12080 Out << "v";
12081 Out << ParSeq << "_" << MangledName;
12082 Fn->addFnAttr(Out.str());
12083 }
12084
12085 // Helper function to generate the Advanced SIMD names depending on
12086 // the value of the NDS when simdlen is not present.
12087 static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask,
12088 StringRef Prefix, char ISA,
12089 StringRef ParSeq, StringRef MangledName,
12090 bool OutputBecomesInput,
12091 llvm::Function *Fn) {
12092 switch (NDS) {
12093 case 8:
12094 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
12095 OutputBecomesInput, Fn);
12096 addAArch64VectorName(16, Mask, Prefix, ISA, ParSeq, MangledName,
12097 OutputBecomesInput, Fn);
12098 break;
12099 case 16:
12100 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
12101 OutputBecomesInput, Fn);
12102 addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
12103 OutputBecomesInput, Fn);
12104 break;
12105 case 32:
12106 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
12107 OutputBecomesInput, Fn);
12108 addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
12109 OutputBecomesInput, Fn);
12110 break;
12111 case 64:
12112 case 128:
12113 addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
12114 OutputBecomesInput, Fn);
12115 break;
12116 default:
12117 llvm_unreachable("Scalar type is too wide.");
12118 }
12119 }
12120
12121 /// Emit vector function attributes for AArch64, as defined in the AAVFABI.
12122 static void emitAArch64DeclareSimdFunction(
12123 CodeGenModule &CGM, const FunctionDecl *FD, unsigned UserVLEN,
12124 ArrayRef<ParamAttrTy> ParamAttrs,
12125 OMPDeclareSimdDeclAttr::BranchStateTy State, StringRef MangledName,
12126 char ISA, unsigned VecRegSize, llvm::Function *Fn, SourceLocation SLoc) {
12127
12128 // Get basic data for building the vector signature.
12129 const auto Data = getNDSWDS(FD, ParamAttrs);
12130 const unsigned NDS = std::get<0>(Data);
12131 const unsigned WDS = std::get<1>(Data);
12132 const bool OutputBecomesInput = std::get<2>(Data);
12133
12134 // Check the values provided via `simdlen` by the user.
12135 // 1. A `simdlen(1)` doesn't produce vector signatures,
12136 if (UserVLEN == 1) {
12137 CGM.getDiags().Report(SLoc, diag::warn_simdlen_1_no_effect);
12138 return;
12139 }
12140
12141 // 2. Section 3.3.1, item 1: user input must be a power of 2 for
12142 // Advanced SIMD output.
12143 if (ISA == 'n' && UserVLEN && !llvm::isPowerOf2_32(UserVLEN)) {
12144 CGM.getDiags().Report(SLoc, diag::warn_simdlen_requires_power_of_2);
12145 return;
12146 }
12147
12148 // 3. Section 3.4.1. SVE fixed lengh must obey the architectural
12149 // limits.
12150 if (ISA == 's' && UserVLEN != 0) {
12151 if ((UserVLEN * WDS > 2048) || (UserVLEN * WDS % 128 != 0)) {
12152 CGM.getDiags().Report(SLoc, diag::warn_simdlen_must_fit_lanes) << WDS;
12153 return;
12154 }
12155 }
12156
12157 // Sort out parameter sequence.
12158 const std::string ParSeq = mangleVectorParameters(ParamAttrs);
12159 StringRef Prefix = "_ZGV";
12160 // Generate simdlen from user input (if any).
12161 if (UserVLEN) {
12162 if (ISA == 's') {
12163 // SVE generates only a masked function.
12164 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
12165 OutputBecomesInput, Fn);
12166 } else {
12167 assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
12168 // Advanced SIMD generates one or two functions, depending on
12169 // the `[not]inbranch` clause.
12170 switch (State) {
12171 case OMPDeclareSimdDeclAttr::BS_Undefined:
12172 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
12173 OutputBecomesInput, Fn);
12174 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
12175 OutputBecomesInput, Fn);
12176 break;
12177 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
12178 addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
12179 OutputBecomesInput, Fn);
12180 break;
12181 case OMPDeclareSimdDeclAttr::BS_Inbranch:
12182 addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
12183 OutputBecomesInput, Fn);
12184 break;
12185 }
12186 }
12187 } else {
12188 // If no user simdlen is provided, follow the AAVFABI rules for
12189 // generating the vector length.
12190 if (ISA == 's') {
12191 // SVE, section 3.4.1, item 1.
12192 addAArch64VectorName("x", "M", Prefix, ISA, ParSeq, MangledName,
12193 OutputBecomesInput, Fn);
12194 } else {
12195 assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
12196 // Advanced SIMD, Section 3.3.1 of the AAVFABI, generates one or
12197 // two vector names depending on the use of the clause
12198 // `[not]inbranch`.
12199 switch (State) {
12200 case OMPDeclareSimdDeclAttr::BS_Undefined:
12201 addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
12202 OutputBecomesInput, Fn);
12203 addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
12204 OutputBecomesInput, Fn);
12205 break;
12206 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
12207 addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
12208 OutputBecomesInput, Fn);
12209 break;
12210 case OMPDeclareSimdDeclAttr::BS_Inbranch:
12211 addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
12212 OutputBecomesInput, Fn);
12213 break;
12214 }
12215 }
12216 }
12217 }
12218
12219 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
12220 llvm::Function *Fn) {
12221 ASTContext &C = CGM.getContext();
12222 FD = FD->getMostRecentDecl();
12223 while (FD) {
12224 // Map params to their positions in function decl.
12225 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
12226 if (isa<CXXMethodDecl>(FD))
12227 ParamPositions.try_emplace(FD, 0);
12228 unsigned ParamPos = ParamPositions.size();
12229 for (const ParmVarDecl *P : FD->parameters()) {
12230 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
12231 ++ParamPos;
12232 }
12233 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
12234 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
12235 // Mark uniform parameters.
12236 for (const Expr *E : Attr->uniforms()) {
12237 E = E->IgnoreParenImpCasts();
12238 unsigned Pos;
12239 if (isa<CXXThisExpr>(E)) {
12240 Pos = ParamPositions[FD];
12241 } else {
12242 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
12243 ->getCanonicalDecl();
12244 auto It = ParamPositions.find(PVD);
12245 assert(It != ParamPositions.end() && "Function parameter not found");
12246 Pos = It->second;
12247 }
12248 ParamAttrs[Pos].Kind = Uniform;
12249 }
12250 // Get alignment info.
12251 auto *NI = Attr->alignments_begin();
12252 for (const Expr *E : Attr->aligneds()) {
12253 E = E->IgnoreParenImpCasts();
12254 unsigned Pos;
12255 QualType ParmTy;
12256 if (isa<CXXThisExpr>(E)) {
12257 Pos = ParamPositions[FD];
12258 ParmTy = E->getType();
12259 } else {
12260 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
12261 ->getCanonicalDecl();
12262 auto It = ParamPositions.find(PVD);
12263 assert(It != ParamPositions.end() && "Function parameter not found");
12264 Pos = It->second;
12265 ParmTy = PVD->getType();
12266 }
12267 ParamAttrs[Pos].Alignment =
12268 (*NI)
12269 ? (*NI)->EvaluateKnownConstInt(C)
12270 : llvm::APSInt::getUnsigned(
12271 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
12272 .getQuantity());
12273 ++NI;
12274 }
12275 // Mark linear parameters.
12276 auto *SI = Attr->steps_begin();
12277 auto *MI = Attr->modifiers_begin();
12278 for (const Expr *E : Attr->linears()) {
12279 E = E->IgnoreParenImpCasts();
12280 unsigned Pos;
12281 bool IsReferenceType = false;
12282 // Rescaling factor needed to compute the linear parameter
12283 // value in the mangled name.
12284 unsigned PtrRescalingFactor = 1;
12285 if (isa<CXXThisExpr>(E)) {
12286 Pos = ParamPositions[FD];
12287 auto *P = cast<PointerType>(E->getType());
12288 PtrRescalingFactor = CGM.getContext()
12289 .getTypeSizeInChars(P->getPointeeType())
12290 .getQuantity();
12291 } else {
12292 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
12293 ->getCanonicalDecl();
12294 auto It = ParamPositions.find(PVD);
12295 assert(It != ParamPositions.end() && "Function parameter not found");
12296 Pos = It->second;
12297 if (auto *P = dyn_cast<PointerType>(PVD->getType()))
12298 PtrRescalingFactor = CGM.getContext()
12299 .getTypeSizeInChars(P->getPointeeType())
12300 .getQuantity();
12301 else if (PVD->getType()->isReferenceType()) {
12302 IsReferenceType = true;
12303 PtrRescalingFactor =
12304 CGM.getContext()
12305 .getTypeSizeInChars(PVD->getType().getNonReferenceType())
12306 .getQuantity();
12307 }
12308 }
12309 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
12310 if (*MI == OMPC_LINEAR_ref)
12311 ParamAttr.Kind = LinearRef;
12312 else if (*MI == OMPC_LINEAR_uval)
12313 ParamAttr.Kind = LinearUVal;
12314 else if (IsReferenceType)
12315 ParamAttr.Kind = LinearVal;
12316 else
12317 ParamAttr.Kind = Linear;
12318 // Assuming a stride of 1, for `linear` without modifiers.
12319 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(1);
12320 if (*SI) {
12321 Expr::EvalResult Result;
12322 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
12323 if (const auto *DRE =
12324 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
12325 if (const auto *StridePVD =
12326 dyn_cast<ParmVarDecl>(DRE->getDecl())) {
12327 ParamAttr.HasVarStride = true;
12328 auto It = ParamPositions.find(StridePVD->getCanonicalDecl());
12329 assert(It != ParamPositions.end() &&
12330 "Function parameter not found");
12331 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(It->second);
12332 }
12333 }
12334 } else {
12335 ParamAttr.StrideOrArg = Result.Val.getInt();
12336 }
12337 }
12338 // If we are using a linear clause on a pointer, we need to
12339 // rescale the value of linear_step with the byte size of the
12340 // pointee type.
12341 if (!ParamAttr.HasVarStride &&
12342 (ParamAttr.Kind == Linear || ParamAttr.Kind == LinearRef))
12343 ParamAttr.StrideOrArg = ParamAttr.StrideOrArg * PtrRescalingFactor;
12344 ++SI;
12345 ++MI;
12346 }
12347 llvm::APSInt VLENVal;
12348 SourceLocation ExprLoc;
12349 const Expr *VLENExpr = Attr->getSimdlen();
12350 if (VLENExpr) {
12351 VLENVal = VLENExpr->EvaluateKnownConstInt(C);
12352 ExprLoc = VLENExpr->getExprLoc();
12353 }
12354 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
12355 if (CGM.getTriple().isX86()) {
12356 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
12357 } else if (CGM.getTriple().getArch() == llvm::Triple::aarch64) {
12358 unsigned VLEN = VLENVal.getExtValue();
12359 StringRef MangledName = Fn->getName();
12360 if (CGM.getTarget().hasFeature("sve"))
12361 emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
12362 MangledName, 's', 128, Fn, ExprLoc);
12363 else if (CGM.getTarget().hasFeature("neon"))
12364 emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
12365 MangledName, 'n', 128, Fn, ExprLoc);
12366 }
12367 }
12368 FD = FD->getPreviousDecl();
12369 }
12370 }
12371
12372 namespace {
12373 /// Cleanup action for doacross support.
12374 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
12375 public:
12376 static const int DoacrossFinArgs = 2;
12377
12378 private:
12379 llvm::FunctionCallee RTLFn;
12380 llvm::Value *Args[DoacrossFinArgs];
12381
12382 public:
12383 DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
12384 ArrayRef<llvm::Value *> CallArgs)
12385 : RTLFn(RTLFn) {
12386 assert(CallArgs.size() == DoacrossFinArgs);
12387 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
12388 }
12389 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
12390 if (!CGF.HaveInsertPoint())
12391 return;
12392 CGF.EmitRuntimeCall(RTLFn, Args);
12393 }
12394 };
12395 } // namespace
12396
12397 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
12398 const OMPLoopDirective &D,
12399 ArrayRef<Expr *> NumIterations) {
12400 if (!CGF.HaveInsertPoint())
12401 return;
12402
12403 ASTContext &C = CGM.getContext();
12404 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
12405 RecordDecl *RD;
12406 if (KmpDimTy.isNull()) {
12407 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
12408 // kmp_int64 lo; // lower
12409 // kmp_int64 up; // upper
12410 // kmp_int64 st; // stride
12411 // };
12412 RD = C.buildImplicitRecord("kmp_dim");
12413 RD->startDefinition();
12414 addFieldToRecordDecl(C, RD, Int64Ty);
12415 addFieldToRecordDecl(C, RD, Int64Ty);
12416 addFieldToRecordDecl(C, RD, Int64Ty);
12417 RD->completeDefinition();
12418 KmpDimTy = C.getCanonicalTagType(RD);
12419 } else {
12420 RD = KmpDimTy->castAsRecordDecl();
12421 }
12422 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
12423 QualType ArrayTy = C.getConstantArrayType(KmpDimTy, Size, nullptr,
12424 ArraySizeModifier::Normal, 0);
12425
12426 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
12427 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
12428 enum { LowerFD = 0, UpperFD, StrideFD };
12429 // Fill dims with data.
12430 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
12431 LValue DimsLVal = CGF.MakeAddrLValue(
12432 CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
12433 // dims.upper = num_iterations;
12434 LValue UpperLVal = CGF.EmitLValueForField(
12435 DimsLVal, *std::next(RD->field_begin(), UpperFD));
12436 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
12437 CGF.EmitScalarExpr(NumIterations[I]), NumIterations[I]->getType(),
12438 Int64Ty, NumIterations[I]->getExprLoc());
12439 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
12440 // dims.stride = 1;
12441 LValue StrideLVal = CGF.EmitLValueForField(
12442 DimsLVal, *std::next(RD->field_begin(), StrideFD));
12443 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
12444 StrideLVal);
12445 }
12446
12447 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
12448 // kmp_int32 num_dims, struct kmp_dim * dims);
12449 llvm::Value *Args[] = {
12450 emitUpdateLocation(CGF, D.getBeginLoc()),
12451 getThreadID(CGF, D.getBeginLoc()),
12452 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
12453 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
12454 CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).emitRawPointer(CGF),
12455 CGM.VoidPtrTy)};
12456
12457 llvm::FunctionCallee RTLFn = OMPBuilder.getOrCreateRuntimeFunction(
12458 CGM.getModule(), OMPRTL___kmpc_doacross_init);
12459 CGF.EmitRuntimeCall(RTLFn, Args);
12460 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
12461 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
12462 llvm::FunctionCallee FiniRTLFn = OMPBuilder.getOrCreateRuntimeFunction(
12463 CGM.getModule(), OMPRTL___kmpc_doacross_fini);
12464 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
12465 llvm::ArrayRef(FiniArgs));
12466 }
12467
12468 template <typename T>
12469 static void EmitDoacrossOrdered(CodeGenFunction &CGF, CodeGenModule &CGM,
12470 const T *C, llvm::Value *ULoc,
12471 llvm::Value *ThreadID) {
12472 QualType Int64Ty =
12473 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
12474 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
12475 QualType ArrayTy = CGM.getContext().getConstantArrayType(
12476 Int64Ty, Size, nullptr, ArraySizeModifier::Normal, 0);
12477 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
12478 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
12479 const Expr *CounterVal = C->getLoopData(I);
12480 assert(CounterVal);
12481 llvm::Value *CntVal = CGF.EmitScalarConversion(
12482 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
12483 CounterVal->getExprLoc());
12484 CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
12485 /*Volatile=*/false, Int64Ty);
12486 }
12487 llvm::Value *Args[] = {
12488 ULoc, ThreadID,
12489 CGF.Builder.CreateConstArrayGEP(CntAddr, 0).emitRawPointer(CGF)};
12490 llvm::FunctionCallee RTLFn;
12491 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
12492 OMPDoacrossKind<T> ODK;
12493 if (ODK.isSource(C)) {
12494 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
12495 OMPRTL___kmpc_doacross_post);
12496 } else {
12497 assert(ODK.isSink(C) && "Expect sink modifier.");
12498 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
12499 OMPRTL___kmpc_doacross_wait);
12500 }
12501 CGF.EmitRuntimeCall(RTLFn, Args);
12502 }
12503
12504 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
12505 const OMPDependClause *C) {
12506 return EmitDoacrossOrdered<OMPDependClause>(
12507 CGF, CGM, C, emitUpdateLocation(CGF, C->getBeginLoc()),
12508 getThreadID(CGF, C->getBeginLoc()));
12509 }
12510
12511 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
12512 const OMPDoacrossClause *C) {
12513 return EmitDoacrossOrdered<OMPDoacrossClause>(
12514 CGF, CGM, C, emitUpdateLocation(CGF, C->getBeginLoc()),
12515 getThreadID(CGF, C->getBeginLoc()));
12516 }
12517
12518 void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
12519 llvm::FunctionCallee Callee,
12520 ArrayRef<llvm::Value *> Args) const {
12521 assert(Loc.isValid() && "Outlined function call location must be valid.");
12522 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
12523
12524 if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
12525 if (Fn->doesNotThrow()) {
12526 CGF.EmitNounwindRuntimeCall(Fn, Args);
12527 return;
12528 }
12529 }
12530 CGF.EmitRuntimeCall(Callee, Args);
12531 }
12532
12533 void CGOpenMPRuntime::emitOutlinedFunctionCall(
12534 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
12535 ArrayRef<llvm::Value *> Args) const {
12536 emitCall(CGF, Loc, OutlinedFn, Args);
12537 }
12538
12539 void CGOpenMPRuntime::emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) {
12540 if (const auto *FD = dyn_cast<FunctionDecl>(D))
12541 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD))
12542 HasEmittedDeclareTargetRegion = true;
12543 }
12544
12545 Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
12546 const VarDecl *NativeParam,
12547 const VarDecl *TargetParam) const {
12548 return CGF.GetAddrOfLocalVar(NativeParam);
12549 }
12550
12551 /// Return allocator value from expression, or return a null allocator (default
12552 /// when no allocator specified).
12553 static llvm::Value *getAllocatorVal(CodeGenFunction &CGF,
12554 const Expr *Allocator) {
12555 llvm::Value *AllocVal;
12556 if (Allocator) {
12557 AllocVal = CGF.EmitScalarExpr(Allocator);
12558 // According to the standard, the original allocator type is a enum
12559 // (integer). Convert to pointer type, if required.
12560 AllocVal = CGF.EmitScalarConversion(AllocVal, Allocator->getType(),
12561 CGF.getContext().VoidPtrTy,
12562 Allocator->getExprLoc());
12563 } else {
12564 // If no allocator specified, it defaults to the null allocator.
12565 AllocVal = llvm::Constant::getNullValue(
12566 CGF.CGM.getTypes().ConvertType(CGF.getContext().VoidPtrTy));
12567 }
12568 return AllocVal;
12569 }
12570
12571 /// Return the alignment from an allocate directive if present.
12572 static llvm::Value *getAlignmentValue(CodeGenModule &CGM, const VarDecl *VD) {
12573 std::optional<CharUnits> AllocateAlignment = CGM.getOMPAllocateAlignment(VD);
12574
12575 if (!AllocateAlignment)
12576 return nullptr;
12577
12578 return llvm::ConstantInt::get(CGM.SizeTy, AllocateAlignment->getQuantity());
12579 }
12580
12581 Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
12582 const VarDecl *VD) {
12583 if (!VD)
12584 return Address::invalid();
12585 Address UntiedAddr = Address::invalid();
12586 Address UntiedRealAddr = Address::invalid();
12587 auto It = FunctionToUntiedTaskStackMap.find(CGF.CurFn);
12588 if (It != FunctionToUntiedTaskStackMap.end()) {
12589 const UntiedLocalVarsAddressesMap &UntiedData =
12590 UntiedLocalVarsStack[It->second];
12591 auto I = UntiedData.find(VD);
12592 if (I != UntiedData.end()) {
12593 UntiedAddr = I->second.first;
12594 UntiedRealAddr = I->second.second;
12595 }
12596 }
12597 const VarDecl *CVD = VD->getCanonicalDecl();
12598 if (CVD->hasAttr<OMPAllocateDeclAttr>()) {
12599 // Use the default allocation.
12600 if (!isAllocatableDecl(VD))
12601 return UntiedAddr;
12602 llvm::Value *Size;
12603 CharUnits Align = CGM.getContext().getDeclAlign(CVD);
12604 if (CVD->getType()->isVariablyModifiedType()) {
12605 Size = CGF.getTypeSize(CVD->getType());
12606 // Align the size: ((size + align - 1) / align) * align
12607 Size = CGF.Builder.CreateNUWAdd(
12608 Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
12609 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
12610 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
12611 } else {
12612 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
12613 Size = CGM.getSize(Sz.alignTo(Align));
12614 }
12615 llvm::Value *ThreadID = getThreadID(CGF, CVD->getBeginLoc());
12616 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
12617 const Expr *Allocator = AA->getAllocator();
12618 llvm::Value *AllocVal = getAllocatorVal(CGF, Allocator);
12619 llvm::Value *Alignment = getAlignmentValue(CGM, CVD);
12620 SmallVector<llvm::Value *, 4> Args;
12621 Args.push_back(ThreadID);
12622 if (Alignment)
12623 Args.push_back(Alignment);
12624 Args.push_back(Size);
12625 Args.push_back(AllocVal);
12626 llvm::omp::RuntimeFunction FnID =
12627 Alignment ? OMPRTL___kmpc_aligned_alloc : OMPRTL___kmpc_alloc;
12628 llvm::Value *Addr = CGF.EmitRuntimeCall(
12629 OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), FnID), Args,
12630 getName({CVD->getName(), ".void.addr"}));
12631 llvm::FunctionCallee FiniRTLFn = OMPBuilder.getOrCreateRuntimeFunction(
12632 CGM.getModule(), OMPRTL___kmpc_free);
12633 QualType Ty = CGM.getContext().getPointerType(CVD->getType());
12634 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
12635 Addr, CGF.ConvertTypeForMem(Ty), getName({CVD->getName(), ".addr"}));
12636 if (UntiedAddr.isValid())
12637 CGF.EmitStoreOfScalar(Addr, UntiedAddr, /*Volatile=*/false, Ty);
12638
12639 // Cleanup action for allocate support.
12640 class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
12641 llvm::FunctionCallee RTLFn;
12642 SourceLocation::UIntTy LocEncoding;
12643 Address Addr;
12644 const Expr *AllocExpr;
12645
12646 public:
12647 OMPAllocateCleanupTy(llvm::FunctionCallee RTLFn,
12648 SourceLocation::UIntTy LocEncoding, Address Addr,
12649 const Expr *AllocExpr)
12650 : RTLFn(RTLFn), LocEncoding(LocEncoding), Addr(Addr),
12651 AllocExpr(AllocExpr) {}
12652 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
12653 if (!CGF.HaveInsertPoint())
12654 return;
12655 llvm::Value *Args[3];
12656 Args[0] = CGF.CGM.getOpenMPRuntime().getThreadID(
12657 CGF, SourceLocation::getFromRawEncoding(LocEncoding));
12658 Args[1] = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
12659 Addr.emitRawPointer(CGF), CGF.VoidPtrTy);
12660 llvm::Value *AllocVal = getAllocatorVal(CGF, AllocExpr);
12661 Args[2] = AllocVal;
12662 CGF.EmitRuntimeCall(RTLFn, Args);
12663 }
12664 };
12665 Address VDAddr =
12666 UntiedRealAddr.isValid()
12667 ? UntiedRealAddr
12668 : Address(Addr, CGF.ConvertTypeForMem(CVD->getType()), Align);
12669 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(
12670 NormalAndEHCleanup, FiniRTLFn, CVD->getLocation().getRawEncoding(),
12671 VDAddr, Allocator);
12672 if (UntiedRealAddr.isValid())
12673 if (auto *Region =
12674 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
12675 Region->emitUntiedSwitch(CGF);
12676 return VDAddr;
12677 }
12678 return UntiedAddr;
12679 }
12680
12681 bool CGOpenMPRuntime::isLocalVarInUntiedTask(CodeGenFunction &CGF,
12682 const VarDecl *VD) const {
12683 auto It = FunctionToUntiedTaskStackMap.find(CGF.CurFn);
12684 if (It == FunctionToUntiedTaskStackMap.end())
12685 return false;
12686 return UntiedLocalVarsStack[It->second].count(VD) > 0;
12687 }
12688
12689 CGOpenMPRuntime::NontemporalDeclsRAII::NontemporalDeclsRAII(
12690 CodeGenModule &CGM, const OMPLoopDirective &S)
12691 : CGM(CGM), NeedToPush(S.hasClausesOfKind<OMPNontemporalClause>()) {
12692 assert(CGM.getLangOpts().OpenMP && "Not in OpenMP mode.");
12693 if (!NeedToPush)
12694 return;
12695 NontemporalDeclsSet &DS =
12696 CGM.getOpenMPRuntime().NontemporalDeclsStack.emplace_back();
12697 for (const auto *C : S.getClausesOfKind<OMPNontemporalClause>()) {
12698 for (const Stmt *Ref : C->private_refs()) {
12699 const auto *SimpleRefExpr = cast<Expr>(Ref)->IgnoreParenImpCasts();
12700 const ValueDecl *VD;
12701 if (const auto *DRE = dyn_cast<DeclRefExpr>(SimpleRefExpr)) {
12702 VD = DRE->getDecl();
12703 } else {
12704 const auto *ME = cast<MemberExpr>(SimpleRefExpr);
12705 assert((ME->isImplicitCXXThis() ||
12706 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) &&
12707 "Expected member of current class.");
12708 VD = ME->getMemberDecl();
12709 }
12710 DS.insert(VD);
12711 }
12712 }
12713 }
12714
12715 CGOpenMPRuntime::NontemporalDeclsRAII::~NontemporalDeclsRAII() {
12716 if (!NeedToPush)
12717 return;
12718 CGM.getOpenMPRuntime().NontemporalDeclsStack.pop_back();
12719 }
12720
12721 CGOpenMPRuntime::UntiedTaskLocalDeclsRAII::UntiedTaskLocalDeclsRAII(
12722 CodeGenFunction &CGF,
12723 const llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
12724 std::pair<Address, Address>> &LocalVars)
12725 : CGM(CGF.CGM), NeedToPush(!LocalVars.empty()) {
12726 if (!NeedToPush)
12727 return;
12728 CGM.getOpenMPRuntime().FunctionToUntiedTaskStackMap.try_emplace(
12729 CGF.CurFn, CGM.getOpenMPRuntime().UntiedLocalVarsStack.size());
12730 CGM.getOpenMPRuntime().UntiedLocalVarsStack.push_back(LocalVars);
12731 }
12732
12733 CGOpenMPRuntime::UntiedTaskLocalDeclsRAII::~UntiedTaskLocalDeclsRAII() {
12734 if (!NeedToPush)
12735 return;
12736 CGM.getOpenMPRuntime().UntiedLocalVarsStack.pop_back();
12737 }
12738
12739 bool CGOpenMPRuntime::isNontemporalDecl(const ValueDecl *VD) const {
12740 assert(CGM.getLangOpts().OpenMP && "Not in OpenMP mode.");
12741
12742 return llvm::any_of(
12743 CGM.getOpenMPRuntime().NontemporalDeclsStack,
12744 [VD](const NontemporalDeclsSet &Set) { return Set.contains(VD); });
12745 }
12746
12747 void CGOpenMPRuntime::LastprivateConditionalRAII::tryToDisableInnerAnalysis(
12748 const OMPExecutableDirective &S,
12749 llvm::DenseSet<CanonicalDeclPtr<const Decl>> &NeedToAddForLPCsAsDisabled)
12750 const {
12751 llvm::DenseSet<CanonicalDeclPtr<const Decl>> NeedToCheckForLPCs;
12752 // Vars in target/task regions must be excluded completely.
12753 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()) ||
12754 isOpenMPTaskingDirective(S.getDirectiveKind())) {
12755 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
12756 getOpenMPCaptureRegions(CaptureRegions, S.getDirectiveKind());
12757 const CapturedStmt *CS = S.getCapturedStmt(CaptureRegions.front());
12758 for (const CapturedStmt::Capture &Cap : CS->captures()) {
12759 if (Cap.capturesVariable() || Cap.capturesVariableByCopy())
12760 NeedToCheckForLPCs.insert(Cap.getCapturedVar());
12761 }
12762 }
12763 // Exclude vars in private clauses.
12764 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
12765 for (const Expr *Ref : C->varlist()) {
12766 if (!Ref->getType()->isScalarType())
12767 continue;
12768 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
12769 if (!DRE)
12770 continue;
12771 NeedToCheckForLPCs.insert(DRE->getDecl());
12772 }
12773 }
12774 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
12775 for (const Expr *Ref : C->varlist()) {
12776 if (!Ref->getType()->isScalarType())
12777 continue;
12778 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
12779 if (!DRE)
12780 continue;
12781 NeedToCheckForLPCs.insert(DRE->getDecl());
12782 }
12783 }
12784 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
12785 for (const Expr *Ref : C->varlist()) {
12786 if (!Ref->getType()->isScalarType())
12787 continue;
12788 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
12789 if (!DRE)
12790 continue;
12791 NeedToCheckForLPCs.insert(DRE->getDecl());
12792 }
12793 }
12794 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
12795 for (const Expr *Ref : C->varlist()) {
12796 if (!Ref->getType()->isScalarType())
12797 continue;
12798 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
12799 if (!DRE)
12800 continue;
12801 NeedToCheckForLPCs.insert(DRE->getDecl());
12802 }
12803 }
12804 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
12805 for (const Expr *Ref : C->varlist()) {
12806 if (!Ref->getType()->isScalarType())
12807 continue;
12808 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
12809 if (!DRE)
12810 continue;
12811 NeedToCheckForLPCs.insert(DRE->getDecl());
12812 }
12813 }
12814 for (const Decl *VD : NeedToCheckForLPCs) {
12815 for (const LastprivateConditionalData &Data :
12816 llvm::reverse(CGM.getOpenMPRuntime().LastprivateConditionalStack)) {
12817 if (Data.DeclToUniqueName.count(VD) > 0) {
12818 if (!Data.Disabled)
12819 NeedToAddForLPCsAsDisabled.insert(VD);
12820 break;
12821 }
12822 }
12823 }
12824 }
12825
12826 CGOpenMPRuntime::LastprivateConditionalRAII::LastprivateConditionalRAII(
12827 CodeGenFunction &CGF, const OMPExecutableDirective &S, LValue IVLVal)
12828 : CGM(CGF.CGM),
12829 Action((CGM.getLangOpts().OpenMP >= 50 &&
12830 llvm::any_of(S.getClausesOfKind<OMPLastprivateClause>(),
12831 [](const OMPLastprivateClause *C) {
12832 return C->getKind() ==
12833 OMPC_LASTPRIVATE_conditional;
12834 }))
12835 ? ActionToDo::PushAsLastprivateConditional
12836 : ActionToDo::DoNotPush) {
12837 assert(CGM.getLangOpts().OpenMP && "Not in OpenMP mode.");
12838 if (CGM.getLangOpts().OpenMP < 50 || Action == ActionToDo::DoNotPush)
12839 return;
12840 assert(Action == ActionToDo::PushAsLastprivateConditional &&
12841 "Expected a push action.");
12842 LastprivateConditionalData &Data =
12843 CGM.getOpenMPRuntime().LastprivateConditionalStack.emplace_back();
12844 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
12845 if (C->getKind() != OMPC_LASTPRIVATE_conditional)
12846 continue;
12847
12848 for (const Expr *Ref : C->varlist()) {
12849 Data.DeclToUniqueName.insert(std::make_pair(
12850 cast<DeclRefExpr>(Ref->IgnoreParenImpCasts())->getDecl(),
12851 SmallString<16>(generateUniqueName(CGM, "pl_cond", Ref))));
12852 }
12853 }
12854 Data.IVLVal = IVLVal;
12855 Data.Fn = CGF.CurFn;
12856 }
12857
12858 CGOpenMPRuntime::LastprivateConditionalRAII::LastprivateConditionalRAII(
12859 CodeGenFunction &CGF, const OMPExecutableDirective &S)
12860 : CGM(CGF.CGM), Action(ActionToDo::DoNotPush) {
12861 assert(CGM.getLangOpts().OpenMP && "Not in OpenMP mode.");
12862 if (CGM.getLangOpts().OpenMP < 50)
12863 return;
12864 llvm::DenseSet<CanonicalDeclPtr<const Decl>> NeedToAddForLPCsAsDisabled;
12865 tryToDisableInnerAnalysis(S, NeedToAddForLPCsAsDisabled);
12866 if (!NeedToAddForLPCsAsDisabled.empty()) {
12867 Action = ActionToDo::DisableLastprivateConditional;
12868 LastprivateConditionalData &Data =
12869 CGM.getOpenMPRuntime().LastprivateConditionalStack.emplace_back();
12870 for (const Decl *VD : NeedToAddForLPCsAsDisabled)
12871 Data.DeclToUniqueName.try_emplace(VD);
12872 Data.Fn = CGF.CurFn;
12873 Data.Disabled = true;
12874 }
12875 }
12876
12877 CGOpenMPRuntime::LastprivateConditionalRAII
12878 CGOpenMPRuntime::LastprivateConditionalRAII::disable(
12879 CodeGenFunction &CGF, const OMPExecutableDirective &S) {
12880 return LastprivateConditionalRAII(CGF, S);
12881 }
12882
12883 CGOpenMPRuntime::LastprivateConditionalRAII::~LastprivateConditionalRAII() {
12884 if (CGM.getLangOpts().OpenMP < 50)
12885 return;
12886 if (Action == ActionToDo::DisableLastprivateConditional) {
12887 assert(CGM.getOpenMPRuntime().LastprivateConditionalStack.back().Disabled &&
12888 "Expected list of disabled private vars.");
12889 CGM.getOpenMPRuntime().LastprivateConditionalStack.pop_back();
12890 }
12891 if (Action == ActionToDo::PushAsLastprivateConditional) {
12892 assert(
12893 !CGM.getOpenMPRuntime().LastprivateConditionalStack.back().Disabled &&
12894 "Expected list of lastprivate conditional vars.");
12895 CGM.getOpenMPRuntime().LastprivateConditionalStack.pop_back();
12896 }
12897 }
12898
12899 Address CGOpenMPRuntime::emitLastprivateConditionalInit(CodeGenFunction &CGF,
12900 const VarDecl *VD) {
12901 ASTContext &C = CGM.getContext();
12902 auto I = LastprivateConditionalToTypes.try_emplace(CGF.CurFn).first;
12903 QualType NewType;
12904 const FieldDecl *VDField;
12905 const FieldDecl *FiredField;
12906 LValue BaseLVal;
12907 auto VI = I->getSecond().find(VD);
12908 if (VI == I->getSecond().end()) {
12909 RecordDecl *RD = C.buildImplicitRecord("lasprivate.conditional");
12910 RD->startDefinition();
12911 VDField = addFieldToRecordDecl(C, RD, VD->getType().getNonReferenceType());
12912 FiredField = addFieldToRecordDecl(C, RD, C.CharTy);
12913 RD->completeDefinition();
12914 NewType = C.getCanonicalTagType(RD);
12915 Address Addr = CGF.CreateMemTemp(NewType, C.getDeclAlign(VD), VD->getName());
12916 BaseLVal = CGF.MakeAddrLValue(Addr, NewType, AlignmentSource::Decl);
12917 I->getSecond().try_emplace(VD, NewType, VDField, FiredField, BaseLVal);
12918 } else {
12919 NewType = std::get<0>(VI->getSecond());
12920 VDField = std::get<1>(VI->getSecond());
12921 FiredField = std::get<2>(VI->getSecond());
12922 BaseLVal = std::get<3>(VI->getSecond());
12923 }
12924 LValue FiredLVal =
12925 CGF.EmitLValueForField(BaseLVal, FiredField);
12926 CGF.EmitStoreOfScalar(
12927 llvm::ConstantInt::getNullValue(CGF.ConvertTypeForMem(C.CharTy)),
12928 FiredLVal);
12929 return CGF.EmitLValueForField(BaseLVal, VDField).getAddress();
12930 }
12931
12932 namespace {
12933 /// Checks if the lastprivate conditional variable is referenced in LHS.
12934 class LastprivateConditionalRefChecker final
12935 : public ConstStmtVisitor<LastprivateConditionalRefChecker, bool> {
12936 ArrayRef<CGOpenMPRuntime::LastprivateConditionalData> LPM;
12937 const Expr *FoundE = nullptr;
12938 const Decl *FoundD = nullptr;
12939 StringRef UniqueDeclName;
12940 LValue IVLVal;
12941 llvm::Function *FoundFn = nullptr;
12942 SourceLocation Loc;
12943
12944 public:
12945 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12946 for (const CGOpenMPRuntime::LastprivateConditionalData &D :
12947 llvm::reverse(LPM)) {
12948 auto It = D.DeclToUniqueName.find(E->getDecl());
12949 if (It == D.DeclToUniqueName.end())
12950 continue;
12951 if (D.Disabled)
12952 return false;
12953 FoundE = E;
12954 FoundD = E->getDecl()->getCanonicalDecl();
12955 UniqueDeclName = It->second;
12956 IVLVal = D.IVLVal;
12957 FoundFn = D.Fn;
12958 break;
12959 }
12960 return FoundE == E;
12961 }
12962 bool VisitMemberExpr(const MemberExpr *E) {
12963 if (!CodeGenFunction::IsWrappedCXXThis(E->getBase()))
12964 return false;
12965 for (const CGOpenMPRuntime::LastprivateConditionalData &D :
12966 llvm::reverse(LPM)) {
12967 auto It = D.DeclToUniqueName.find(E->getMemberDecl());
12968 if (It == D.DeclToUniqueName.end())
12969 continue;
12970 if (D.Disabled)
12971 return false;
12972 FoundE = E;
12973 FoundD = E->getMemberDecl()->getCanonicalDecl();
12974 UniqueDeclName = It->second;
12975 IVLVal = D.IVLVal;
12976 FoundFn = D.Fn;
12977 break;
12978 }
12979 return FoundE == E;
12980 }
12981 bool VisitStmt(const Stmt *S) {
12982 for (const Stmt *Child : S->children()) {
12983 if (!Child)
12984 continue;
12985 if (const auto *E = dyn_cast<Expr>(Child))
12986 if (!E->isGLValue())
12987 continue;
12988 if (Visit(Child))
12989 return true;
12990 }
12991 return false;
12992 }
12993 explicit LastprivateConditionalRefChecker(
12994 ArrayRef<CGOpenMPRuntime::LastprivateConditionalData> LPM)
12995 : LPM(LPM) {}
12996 std::tuple<const Expr *, const Decl *, StringRef, LValue, llvm::Function *>
12997 getFoundData() const {
12998 return std::make_tuple(FoundE, FoundD, UniqueDeclName, IVLVal, FoundFn);
12999 }
13000 };
13001 } // namespace
13002
13003 void CGOpenMPRuntime::emitLastprivateConditionalUpdate(CodeGenFunction &CGF,
13004 LValue IVLVal,
13005 StringRef UniqueDeclName,
13006 LValue LVal,
13007 SourceLocation Loc) {
13008 // Last updated loop counter for the lastprivate conditional var.
13009 // int<xx> last_iv = 0;
13010 llvm::Type *LLIVTy = CGF.ConvertTypeForMem(IVLVal.getType());
13011 llvm::Constant *LastIV = OMPBuilder.getOrCreateInternalVariable(
13012 LLIVTy, getName({UniqueDeclName, "iv"}));
13013 cast<llvm::GlobalVariable>(LastIV)->setAlignment(
13014 IVLVal.getAlignment().getAsAlign());
13015 LValue LastIVLVal =
13016 CGF.MakeNaturalAlignRawAddrLValue(LastIV, IVLVal.getType());
13017
13018 // Last value of the lastprivate conditional.
13019 // decltype(priv_a) last_a;
13020 llvm::GlobalVariable *Last = OMPBuilder.getOrCreateInternalVariable(
13021 CGF.ConvertTypeForMem(LVal.getType()), UniqueDeclName);
13022 cast<llvm::GlobalVariable>(Last)->setAlignment(
13023 LVal.getAlignment().getAsAlign());
13024 LValue LastLVal =
13025 CGF.MakeRawAddrLValue(Last, LVal.getType(), LVal.getAlignment());
13026
13027 // Global loop counter. Required to handle inner parallel-for regions.
13028 // iv
13029 llvm::Value *IVVal = CGF.EmitLoadOfScalar(IVLVal, Loc);
13030
13031 // #pragma omp critical(a)
13032 // if (last_iv <= iv) {
13033 // last_iv = iv;
13034 // last_a = priv_a;
13035 // }
13036 auto &&CodeGen = [&LastIVLVal, &IVLVal, IVVal, &LVal, &LastLVal,
13037 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
13038 Action.Enter(CGF);
13039 llvm::Value *LastIVVal = CGF.EmitLoadOfScalar(LastIVLVal, Loc);
13040 // (last_iv <= iv) ? Check if the variable is updated and store new
13041 // value in global var.
13042 llvm::Value *CmpRes;
13043 if (IVLVal.getType()->isSignedIntegerType()) {
13044 CmpRes = CGF.Builder.CreateICmpSLE(LastIVVal, IVVal);
13045 } else {
13046 assert(IVLVal.getType()->isUnsignedIntegerType() &&
13047 "Loop iteration variable must be integer.");
13048 CmpRes = CGF.Builder.CreateICmpULE(LastIVVal, IVVal);
13049 }
13050 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("lp_cond_then");
13051 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("lp_cond_exit");
13052 CGF.Builder.CreateCondBr(CmpRes, ThenBB, ExitBB);
13053 // {
13054 CGF.EmitBlock(ThenBB);
13055
13056 // last_iv = iv;
13057 CGF.EmitStoreOfScalar(IVVal, LastIVLVal);
13058
13059 // last_a = priv_a;
13060 switch (CGF.getEvaluationKind(LVal.getType())) {
13061 case TEK_Scalar: {
13062 llvm::Value *PrivVal = CGF.EmitLoadOfScalar(LVal, Loc);
13063 CGF.EmitStoreOfScalar(PrivVal, LastLVal);
13064 break;
13065 }
13066 case TEK_Complex: {
13067 CodeGenFunction::ComplexPairTy PrivVal = CGF.EmitLoadOfComplex(LVal, Loc);
13068 CGF.EmitStoreOfComplex(PrivVal, LastLVal, /*isInit=*/false);
13069 break;
13070 }
13071 case TEK_Aggregate:
13072 llvm_unreachable(
13073 "Aggregates are not supported in lastprivate conditional.");
13074 }
13075 // }
13076 CGF.EmitBranch(ExitBB);
13077 // There is no need to emit line number for unconditional branch.
13078 (void)ApplyDebugLocation::CreateEmpty(CGF);
13079 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
13080 };
13081
13082 if (CGM.getLangOpts().OpenMPSimd) {
13083 // Do not emit as a critical region as no parallel region could be emitted.
13084 RegionCodeGenTy ThenRCG(CodeGen);
13085 ThenRCG(CGF);
13086 } else {
13087 emitCriticalRegion(CGF, UniqueDeclName, CodeGen, Loc);
13088 }
13089 }
13090
13091 void CGOpenMPRuntime::checkAndEmitLastprivateConditional(CodeGenFunction &CGF,
13092 const Expr *LHS) {
13093 if (CGF.getLangOpts().OpenMP < 50 || LastprivateConditionalStack.empty())
13094 return;
13095 LastprivateConditionalRefChecker Checker(LastprivateConditionalStack);
13096 if (!Checker.Visit(LHS))
13097 return;
13098 const Expr *FoundE;
13099 const Decl *FoundD;
13100 StringRef UniqueDeclName;
13101 LValue IVLVal;
13102 llvm::Function *FoundFn;
13103 std::tie(FoundE, FoundD, UniqueDeclName, IVLVal, FoundFn) =
13104 Checker.getFoundData();
13105 if (FoundFn != CGF.CurFn) {
13106 // Special codegen for inner parallel regions.
13107 // ((struct.lastprivate.conditional*)&priv_a)->Fired = 1;
13108 auto It = LastprivateConditionalToTypes[FoundFn].find(FoundD);
13109 assert(It != LastprivateConditionalToTypes[FoundFn].end() &&
13110 "Lastprivate conditional is not found in outer region.");
13111 QualType StructTy = std::get<0>(It->getSecond());
13112 const FieldDecl* FiredDecl = std::get<2>(It->getSecond());
13113 LValue PrivLVal = CGF.EmitLValue(FoundE);
13114 Address StructAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
13115 PrivLVal.getAddress(),
13116 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(StructTy)),
13117 CGF.ConvertTypeForMem(StructTy));
13118 LValue BaseLVal =
13119 CGF.MakeAddrLValue(StructAddr, StructTy, AlignmentSource::Decl);
13120 LValue FiredLVal = CGF.EmitLValueForField(BaseLVal, FiredDecl);
13121 CGF.EmitAtomicStore(RValue::get(llvm::ConstantInt::get(
13122 CGF.ConvertTypeForMem(FiredDecl->getType()), 1)),
13123 FiredLVal, llvm::AtomicOrdering::Unordered,
13124 /*IsVolatile=*/true, /*isInit=*/false);
13125 return;
13126 }
13127
13128 // Private address of the lastprivate conditional in the current context.
13129 // priv_a
13130 LValue LVal = CGF.EmitLValue(FoundE);
13131 emitLastprivateConditionalUpdate(CGF, IVLVal, UniqueDeclName, LVal,
13132 FoundE->getExprLoc());
13133 }
13134
13135 void CGOpenMPRuntime::checkAndEmitSharedLastprivateConditional(
13136 CodeGenFunction &CGF, const OMPExecutableDirective &D,
13137 const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls) {
13138 if (CGF.getLangOpts().OpenMP < 50 || LastprivateConditionalStack.empty())
13139 return;
13140 auto Range = llvm::reverse(LastprivateConditionalStack);
13141 auto It = llvm::find_if(
13142 Range, [](const LastprivateConditionalData &D) { return !D.Disabled; });
13143 if (It == Range.end() || It->Fn != CGF.CurFn)
13144 return;
13145 auto LPCI = LastprivateConditionalToTypes.find(It->Fn);
13146 assert(LPCI != LastprivateConditionalToTypes.end() &&
13147 "Lastprivates must be registered already.");
13148 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
13149 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
13150 const CapturedStmt *CS = D.getCapturedStmt(CaptureRegions.back());
13151 for (const auto &Pair : It->DeclToUniqueName) {
13152 const auto *VD = cast<VarDecl>(Pair.first->getCanonicalDecl());
13153 if (!CS->capturesVariable(VD) || IgnoredDecls.contains(VD))
13154 continue;
13155 auto I = LPCI->getSecond().find(Pair.first);
13156 assert(I != LPCI->getSecond().end() &&
13157 "Lastprivate must be rehistered already.");
13158 // bool Cmp = priv_a.Fired != 0;
13159 LValue BaseLVal = std::get<3>(I->getSecond());
13160 LValue FiredLVal =
13161 CGF.EmitLValueForField(BaseLVal, std::get<2>(I->getSecond()));
13162 llvm::Value *Res = CGF.EmitLoadOfScalar(FiredLVal, D.getBeginLoc());
13163 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Res);
13164 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("lpc.then");
13165 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("lpc.done");
13166 // if (Cmp) {
13167 CGF.Builder.CreateCondBr(Cmp, ThenBB, DoneBB);
13168 CGF.EmitBlock(ThenBB);
13169 Address Addr = CGF.GetAddrOfLocalVar(VD);
13170 LValue LVal;
13171 if (VD->getType()->isReferenceType())
13172 LVal = CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
13173 AlignmentSource::Decl);
13174 else
13175 LVal = CGF.MakeAddrLValue(Addr, VD->getType().getNonReferenceType(),
13176 AlignmentSource::Decl);
13177 emitLastprivateConditionalUpdate(CGF, It->IVLVal, Pair.second, LVal,
13178 D.getBeginLoc());
13179 auto AL = ApplyDebugLocation::CreateArtificial(CGF);
13180 CGF.EmitBlock(DoneBB, /*IsFinal=*/true);
13181 // }
13182 }
13183 }
13184
13185 void CGOpenMPRuntime::emitLastprivateConditionalFinalUpdate(
13186 CodeGenFunction &CGF, LValue PrivLVal, const VarDecl *VD,
13187 SourceLocation Loc) {
13188 if (CGF.getLangOpts().OpenMP < 50)
13189 return;
13190 auto It = LastprivateConditionalStack.back().DeclToUniqueName.find(VD);
13191 assert(It != LastprivateConditionalStack.back().DeclToUniqueName.end() &&
13192 "Unknown lastprivate conditional variable.");
13193 StringRef UniqueName = It->second;
13194 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(UniqueName);
13195 // The variable was not updated in the region - exit.
13196 if (!GV)
13197 return;
13198 LValue LPLVal = CGF.MakeRawAddrLValue(
13199 GV, PrivLVal.getType().getNonReferenceType(), PrivLVal.getAlignment());
13200 llvm::Value *Res = CGF.EmitLoadOfScalar(LPLVal, Loc);
13201 CGF.EmitStoreOfScalar(Res, PrivLVal);
13202 }
13203
13204 llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
13205 CodeGenFunction &CGF, const OMPExecutableDirective &D,
13206 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
13207 const RegionCodeGenTy &CodeGen) {
13208 llvm_unreachable("Not supported in SIMD-only mode");
13209 }
13210
13211 llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
13212 CodeGenFunction &CGF, const OMPExecutableDirective &D,
13213 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
13214 const RegionCodeGenTy &CodeGen) {
13215 llvm_unreachable("Not supported in SIMD-only mode");
13216 }
13217
13218 llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
13219 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
13220 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
13221 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
13222 bool Tied, unsigned &NumberOfParts) {
13223 llvm_unreachable("Not supported in SIMD-only mode");
13224 }
13225
13226 void CGOpenMPSIMDRuntime::emitParallelCall(
13227 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
13228 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond,
13229 llvm::Value *NumThreads, OpenMPNumThreadsClauseModifier NumThreadsModifier,
13230 OpenMPSeverityClauseKind Severity, const Expr *Message) {
13231 llvm_unreachable("Not supported in SIMD-only mode");
13232 }
13233
13234 void CGOpenMPSIMDRuntime::emitCriticalRegion(
13235 CodeGenFunction &CGF, StringRef CriticalName,
13236 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
13237 const Expr *Hint) {
13238 llvm_unreachable("Not supported in SIMD-only mode");
13239 }
13240
13241 void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
13242 const RegionCodeGenTy &MasterOpGen,
13243 SourceLocation Loc) {
13244 llvm_unreachable("Not supported in SIMD-only mode");
13245 }
13246
13247 void CGOpenMPSIMDRuntime::emitMaskedRegion(CodeGenFunction &CGF,
13248 const RegionCodeGenTy &MasterOpGen,
13249 SourceLocation Loc,
13250 const Expr *Filter) {
13251 llvm_unreachable("Not supported in SIMD-only mode");
13252 }
13253
13254 void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
13255 SourceLocation Loc) {
13256 llvm_unreachable("Not supported in SIMD-only mode");
13257 }
13258
13259 void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
13260 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
13261 SourceLocation Loc) {
13262 llvm_unreachable("Not supported in SIMD-only mode");
13263 }
13264
13265 void CGOpenMPSIMDRuntime::emitSingleRegion(
13266 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
13267 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
13268 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
13269 ArrayRef<const Expr *> AssignmentOps) {
13270 llvm_unreachable("Not supported in SIMD-only mode");
13271 }
13272
13273 void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
13274 const RegionCodeGenTy &OrderedOpGen,
13275 SourceLocation Loc,
13276 bool IsThreads) {
13277 llvm_unreachable("Not supported in SIMD-only mode");
13278 }
13279
13280 void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
13281 SourceLocation Loc,
13282 OpenMPDirectiveKind Kind,
13283 bool EmitChecks,
13284 bool ForceSimpleCall) {
13285 llvm_unreachable("Not supported in SIMD-only mode");
13286 }
13287
13288 void CGOpenMPSIMDRuntime::emitForDispatchInit(
13289 CodeGenFunction &CGF, SourceLocation Loc,
13290 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
13291 bool Ordered, const DispatchRTInput &DispatchValues) {
13292 llvm_unreachable("Not supported in SIMD-only mode");
13293 }
13294
13295 void CGOpenMPSIMDRuntime::emitForDispatchDeinit(CodeGenFunction &CGF,
13296 SourceLocation Loc) {
13297 llvm_unreachable("Not supported in SIMD-only mode");
13298 }
13299
13300 void CGOpenMPSIMDRuntime::emitForStaticInit(
13301 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
13302 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
13303 llvm_unreachable("Not supported in SIMD-only mode");
13304 }
13305
13306 void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
13307 CodeGenFunction &CGF, SourceLocation Loc,
13308 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
13309 llvm_unreachable("Not supported in SIMD-only mode");
13310 }
13311
13312 void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
13313 SourceLocation Loc,
13314 unsigned IVSize,
13315 bool IVSigned) {
13316 llvm_unreachable("Not supported in SIMD-only mode");
13317 }
13318
13319 void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
13320 SourceLocation Loc,
13321 OpenMPDirectiveKind DKind) {
13322 llvm_unreachable("Not supported in SIMD-only mode");
13323 }
13324
13325 llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
13326 SourceLocation Loc,
13327 unsigned IVSize, bool IVSigned,
13328 Address IL, Address LB,
13329 Address UB, Address ST) {
13330 llvm_unreachable("Not supported in SIMD-only mode");
13331 }
13332
13333 void CGOpenMPSIMDRuntime::emitNumThreadsClause(
13334 CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc,
13335 OpenMPNumThreadsClauseModifier Modifier, OpenMPSeverityClauseKind Severity,
13336 SourceLocation SeverityLoc, const Expr *Message,
13337 SourceLocation MessageLoc) {
13338 llvm_unreachable("Not supported in SIMD-only mode");
13339 }
13340
13341 void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
13342 ProcBindKind ProcBind,
13343 SourceLocation Loc) {
13344 llvm_unreachable("Not supported in SIMD-only mode");
13345 }
13346
13347 Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
13348 const VarDecl *VD,
13349 Address VDAddr,
13350 SourceLocation Loc) {
13351 llvm_unreachable("Not supported in SIMD-only mode");
13352 }
13353
13354 llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
13355 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
13356 CodeGenFunction *CGF) {
13357 llvm_unreachable("Not supported in SIMD-only mode");
13358 }
13359
13360 Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
13361 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
13362 llvm_unreachable("Not supported in SIMD-only mode");
13363 }
13364
13365 void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
13366 ArrayRef<const Expr *> Vars,
13367 SourceLocation Loc,
13368 llvm::AtomicOrdering AO) {
13369 llvm_unreachable("Not supported in SIMD-only mode");
13370 }
13371
13372 void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
13373 const OMPExecutableDirective &D,
13374 llvm::Function *TaskFunction,
13375 QualType SharedsTy, Address Shareds,
13376 const Expr *IfCond,
13377 const OMPTaskDataTy &Data) {
13378 llvm_unreachable("Not supported in SIMD-only mode");
13379 }
13380
13381 void CGOpenMPSIMDRuntime::emitTaskLoopCall(
13382 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
13383 llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
13384 const Expr *IfCond, const OMPTaskDataTy &Data) {
13385 llvm_unreachable("Not supported in SIMD-only mode");
13386 }
13387
13388 void CGOpenMPSIMDRuntime::emitReduction(
13389 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
13390 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
13391 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
13392 assert(Options.SimpleReduction && "Only simple reduction is expected.");
13393 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
13394 ReductionOps, Options);
13395 }
13396
13397 llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
13398 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
13399 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
13400 llvm_unreachable("Not supported in SIMD-only mode");
13401 }
13402
13403 void CGOpenMPSIMDRuntime::emitTaskReductionFini(CodeGenFunction &CGF,
13404 SourceLocation Loc,
13405 bool IsWorksharingReduction) {
13406 llvm_unreachable("Not supported in SIMD-only mode");
13407 }
13408
13409 void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
13410 SourceLocation Loc,
13411 ReductionCodeGen &RCG,
13412 unsigned N) {
13413 llvm_unreachable("Not supported in SIMD-only mode");
13414 }
13415
13416 Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
13417 SourceLocation Loc,
13418 llvm::Value *ReductionsPtr,
13419 LValue SharedLVal) {
13420 llvm_unreachable("Not supported in SIMD-only mode");
13421 }
13422
13423 void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
13424 SourceLocation Loc,
13425 const OMPTaskDataTy &Data) {
13426 llvm_unreachable("Not supported in SIMD-only mode");
13427 }
13428
13429 void CGOpenMPSIMDRuntime::emitCancellationPointCall(
13430 CodeGenFunction &CGF, SourceLocation Loc,
13431 OpenMPDirectiveKind CancelRegion) {
13432 llvm_unreachable("Not supported in SIMD-only mode");
13433 }
13434
13435 void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
13436 SourceLocation Loc, const Expr *IfCond,
13437 OpenMPDirectiveKind CancelRegion) {
13438 llvm_unreachable("Not supported in SIMD-only mode");
13439 }
13440
13441 void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
13442 const OMPExecutableDirective &D, StringRef ParentName,
13443 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
13444 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
13445 llvm_unreachable("Not supported in SIMD-only mode");
13446 }
13447
13448 void CGOpenMPSIMDRuntime::emitTargetCall(
13449 CodeGenFunction &CGF, const OMPExecutableDirective &D,
13450 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
13451 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
13452 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
13453 const OMPLoopDirective &D)>
13454 SizeEmitter) {
13455 llvm_unreachable("Not supported in SIMD-only mode");
13456 }
13457
13458 bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
13459 llvm_unreachable("Not supported in SIMD-only mode");
13460 }
13461
13462 bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
13463 llvm_unreachable("Not supported in SIMD-only mode");
13464 }
13465
13466 bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
13467 return false;
13468 }
13469
13470 void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
13471 const OMPExecutableDirective &D,
13472 SourceLocation Loc,
13473 llvm::Function *OutlinedFn,
13474 ArrayRef<llvm::Value *> CapturedVars) {
13475 llvm_unreachable("Not supported in SIMD-only mode");
13476 }
13477
13478 void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
13479 const Expr *NumTeams,
13480 const Expr *ThreadLimit,
13481 SourceLocation Loc) {
13482 llvm_unreachable("Not supported in SIMD-only mode");
13483 }
13484
13485 void CGOpenMPSIMDRuntime::emitTargetDataCalls(
13486 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
13487 const Expr *Device, const RegionCodeGenTy &CodeGen,
13488 CGOpenMPRuntime::TargetDataInfo &Info) {
13489 llvm_unreachable("Not supported in SIMD-only mode");
13490 }
13491
13492 void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
13493 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
13494 const Expr *Device) {
13495 llvm_unreachable("Not supported in SIMD-only mode");
13496 }
13497
13498 void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
13499 const OMPLoopDirective &D,
13500 ArrayRef<Expr *> NumIterations) {
13501 llvm_unreachable("Not supported in SIMD-only mode");
13502 }
13503
13504 void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
13505 const OMPDependClause *C) {
13506 llvm_unreachable("Not supported in SIMD-only mode");
13507 }
13508
13509 void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
13510 const OMPDoacrossClause *C) {
13511 llvm_unreachable("Not supported in SIMD-only mode");
13512 }
13513
13514 const VarDecl *
13515 CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
13516 const VarDecl *NativeParam) const {
13517 llvm_unreachable("Not supported in SIMD-only mode");
13518 }
13519
13520 Address
13521 CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
13522 const VarDecl *NativeParam,
13523 const VarDecl *TargetParam) const {
13524 llvm_unreachable("Not supported in SIMD-only mode");
13525 }