clang  8.0.0svn
CGOpenMPRuntime.cpp
Go to the documentation of this file.
1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides a class for OpenMP runtime code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCXXABI.h"
15 #include "CGCleanup.h"
16 #include "CGOpenMPRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/StmtOpenMP.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Value.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <cassert>
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 namespace {
37 /// Base class for handling code generation inside OpenMP regions.
38 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39 public:
40  /// Kinds of OpenMP regions used in codegen.
41  enum CGOpenMPRegionKind {
42  /// Region with outlined function for standalone 'parallel'
43  /// directive.
44  ParallelOutlinedRegion,
45  /// Region with outlined function for standalone 'task' directive.
46  TaskOutlinedRegion,
47  /// Region for constructs that do not require function outlining,
48  /// like 'for', 'sections', 'atomic' etc. directives.
49  InlinedRegion,
50  /// Region with outlined function for standalone 'target' directive.
51  TargetRegion,
52  };
53 
54  CGOpenMPRegionInfo(const CapturedStmt &CS,
55  const CGOpenMPRegionKind RegionKind,
57  bool HasCancel)
58  : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
59  CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
60 
61  CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
63  bool HasCancel)
64  : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
65  Kind(Kind), HasCancel(HasCancel) {}
66 
67  /// Get a variable or parameter for storing global thread id
68  /// inside OpenMP construct.
69  virtual const VarDecl *getThreadIDVariable() const = 0;
70 
71  /// Emit the captured statement body.
72  void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
73 
74  /// Get an LValue for the current ThreadID variable.
75  /// \return LValue for thread id variable. This LValue always has type int32*.
76  virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
77 
78  virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79 
80  CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
81 
82  OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83 
84  bool hasCancel() const { return HasCancel; }
85 
86  static bool classof(const CGCapturedStmtInfo *Info) {
87  return Info->getKind() == CR_OpenMP;
88  }
89 
90  ~CGOpenMPRegionInfo() override = default;
91 
92 protected:
93  CGOpenMPRegionKind RegionKind;
94  RegionCodeGenTy CodeGen;
96  bool HasCancel;
97 };
98 
99 /// API for captured statement code generation in OpenMP constructs.
100 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
101 public:
102  CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
103  const RegionCodeGenTy &CodeGen,
104  OpenMPDirectiveKind Kind, bool HasCancel,
105  StringRef HelperName)
106  : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107  HasCancel),
108  ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
109  assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110  }
111 
112  /// Get a variable or parameter for storing global thread id
113  /// inside OpenMP construct.
114  const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
115 
116  /// Get the name of the capture helper.
117  StringRef getHelperName() const override { return HelperName; }
118 
119  static bool classof(const CGCapturedStmtInfo *Info) {
120  return CGOpenMPRegionInfo::classof(Info) &&
121  cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122  ParallelOutlinedRegion;
123  }
124 
125 private:
126  /// A variable or parameter storing global thread id for OpenMP
127  /// constructs.
128  const VarDecl *ThreadIDVar;
129  StringRef HelperName;
130 };
131 
132 /// API for captured statement code generation in OpenMP constructs.
133 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
134 public:
135  class UntiedTaskActionTy final : public PrePostActionTy {
136  bool Untied;
137  const VarDecl *PartIDVar;
138  const RegionCodeGenTy UntiedCodeGen;
139  llvm::SwitchInst *UntiedSwitch = nullptr;
140 
141  public:
142  UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143  const RegionCodeGenTy &UntiedCodeGen)
144  : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145  void Enter(CodeGenFunction &CGF) override {
146  if (Untied) {
147  // Emit task switching point.
148  LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
149  CGF.GetAddrOfLocalVar(PartIDVar),
150  PartIDVar->getType()->castAs<PointerType>());
151  llvm::Value *Res =
152  CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153  llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
154  UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155  CGF.EmitBlock(DoneBB);
157  CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158  UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159  CGF.Builder.GetInsertBlock());
160  emitUntiedSwitch(CGF);
161  }
162  }
163  void emitUntiedSwitch(CodeGenFunction &CGF) const {
164  if (Untied) {
165  LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
166  CGF.GetAddrOfLocalVar(PartIDVar),
167  PartIDVar->getType()->castAs<PointerType>());
168  CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169  PartIdLVal);
170  UntiedCodeGen(CGF);
171  CodeGenFunction::JumpDest CurPoint =
172  CGF.getJumpDestInCurrentScope(".untied.next.");
174  CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175  UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176  CGF.Builder.GetInsertBlock());
177  CGF.EmitBranchThroughCleanup(CurPoint);
178  CGF.EmitBlock(CurPoint.getBlock());
179  }
180  }
181  unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182  };
183  CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
184  const VarDecl *ThreadIDVar,
185  const RegionCodeGenTy &CodeGen,
186  OpenMPDirectiveKind Kind, bool HasCancel,
187  const UntiedTaskActionTy &Action)
188  : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
189  ThreadIDVar(ThreadIDVar), Action(Action) {
190  assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191  }
192 
193  /// Get a variable or parameter for storing global thread id
194  /// inside OpenMP construct.
195  const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
196 
197  /// Get an LValue for the current ThreadID variable.
198  LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
199 
200  /// Get the name of the capture helper.
201  StringRef getHelperName() const override { return ".omp_outlined."; }
202 
203  void emitUntiedSwitch(CodeGenFunction &CGF) override {
204  Action.emitUntiedSwitch(CGF);
205  }
206 
207  static bool classof(const CGCapturedStmtInfo *Info) {
208  return CGOpenMPRegionInfo::classof(Info) &&
209  cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210  TaskOutlinedRegion;
211  }
212 
213 private:
214  /// A variable or parameter storing global thread id for OpenMP
215  /// constructs.
216  const VarDecl *ThreadIDVar;
217  /// Action for emitting code for untied tasks.
218  const UntiedTaskActionTy &Action;
219 };
220 
221 /// API for inlined captured statement code generation in OpenMP
222 /// constructs.
223 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224 public:
225  CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
226  const RegionCodeGenTy &CodeGen,
227  OpenMPDirectiveKind Kind, bool HasCancel)
228  : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229  OldCSI(OldCSI),
230  OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
231 
232  // Retrieve the value of the context parameter.
233  llvm::Value *getContextValue() const override {
234  if (OuterRegionInfo)
235  return OuterRegionInfo->getContextValue();
236  llvm_unreachable("No context value for inlined OpenMP region");
237  }
238 
239  void setContextValue(llvm::Value *V) override {
240  if (OuterRegionInfo) {
241  OuterRegionInfo->setContextValue(V);
242  return;
243  }
244  llvm_unreachable("No context value for inlined OpenMP region");
245  }
246 
247  /// Lookup the captured field decl for a variable.
248  const FieldDecl *lookup(const VarDecl *VD) const override {
249  if (OuterRegionInfo)
250  return OuterRegionInfo->lookup(VD);
251  // If there is no outer outlined region,no need to lookup in a list of
252  // captured variables, we can use the original one.
253  return nullptr;
254  }
255 
256  FieldDecl *getThisFieldDecl() const override {
257  if (OuterRegionInfo)
258  return OuterRegionInfo->getThisFieldDecl();
259  return nullptr;
260  }
261 
262  /// Get a variable or parameter for storing global thread id
263  /// inside OpenMP construct.
264  const VarDecl *getThreadIDVariable() const override {
265  if (OuterRegionInfo)
266  return OuterRegionInfo->getThreadIDVariable();
267  return nullptr;
268  }
269 
270  /// Get an LValue for the current ThreadID variable.
271  LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272  if (OuterRegionInfo)
273  return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274  llvm_unreachable("No LValue for inlined OpenMP construct");
275  }
276 
277  /// Get the name of the capture helper.
278  StringRef getHelperName() const override {
279  if (auto *OuterRegionInfo = getOldCSI())
280  return OuterRegionInfo->getHelperName();
281  llvm_unreachable("No helper name for inlined OpenMP construct");
282  }
283 
284  void emitUntiedSwitch(CodeGenFunction &CGF) override {
285  if (OuterRegionInfo)
286  OuterRegionInfo->emitUntiedSwitch(CGF);
287  }
288 
289  CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290 
291  static bool classof(const CGCapturedStmtInfo *Info) {
292  return CGOpenMPRegionInfo::classof(Info) &&
293  cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294  }
295 
296  ~CGOpenMPInlinedRegionInfo() override = default;
297 
298 private:
299  /// CodeGen info about outer OpenMP region.
301  CGOpenMPRegionInfo *OuterRegionInfo;
302 };
303 
304 /// API for captured statement code generation in OpenMP target
305 /// constructs. For this captures, implicit parameters are used instead of the
306 /// captured fields. The name of the target region has to be unique in a given
307 /// application so it is provided by the client, because only the client has
308 /// the information to generate that.
309 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
310 public:
311  CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
312  const RegionCodeGenTy &CodeGen, StringRef HelperName)
313  : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
314  /*HasCancel=*/false),
315  HelperName(HelperName) {}
316 
317  /// This is unused for target regions because each starts executing
318  /// with a single thread.
319  const VarDecl *getThreadIDVariable() const override { return nullptr; }
320 
321  /// Get the name of the capture helper.
322  StringRef getHelperName() const override { return HelperName; }
323 
324  static bool classof(const CGCapturedStmtInfo *Info) {
325  return CGOpenMPRegionInfo::classof(Info) &&
326  cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327  }
328 
329 private:
330  StringRef HelperName;
331 };
332 
333 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
334  llvm_unreachable("No codegen for expressions");
335 }
336 /// API for generation of expressions captured in a innermost OpenMP
337 /// region.
338 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
339 public:
340  CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341  : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342  OMPD_unknown,
343  /*HasCancel=*/false),
344  PrivScope(CGF) {
345  // Make sure the globals captured in the provided statement are local by
346  // using the privatization logic. We assume the same variable is not
347  // captured more than once.
348  for (const auto &C : CS.captures()) {
349  if (!C.capturesVariable() && !C.capturesVariableByCopy())
350  continue;
351 
352  const VarDecl *VD = C.getCapturedVar();
353  if (VD->isLocalVarDeclOrParm())
354  continue;
355 
356  DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357  /*RefersToEnclosingVariableOrCapture=*/false,
359  C.getLocation());
360  PrivScope.addPrivate(
361  VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
362  }
363  (void)PrivScope.Privatize();
364  }
365 
366  /// Lookup the captured field decl for a variable.
367  const FieldDecl *lookup(const VarDecl *VD) const override {
368  if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
369  return FD;
370  return nullptr;
371  }
372 
373  /// Emit the captured statement body.
374  void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375  llvm_unreachable("No body for expressions");
376  }
377 
378  /// Get a variable or parameter for storing global thread id
379  /// inside OpenMP construct.
380  const VarDecl *getThreadIDVariable() const override {
381  llvm_unreachable("No thread id for expressions");
382  }
383 
384  /// Get the name of the capture helper.
385  StringRef getHelperName() const override {
386  llvm_unreachable("No helper name for expressions");
387  }
388 
389  static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390 
391 private:
392  /// Private scope to capture global variables.
394 };
395 
396 /// RAII for emitting code of OpenMP constructs.
397 class InlinedOpenMPRegionRAII {
398  CodeGenFunction &CGF;
399  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400  FieldDecl *LambdaThisCaptureField = nullptr;
401  const CodeGen::CGBlockInfo *BlockInfo = nullptr;
402 
403 public:
404  /// Constructs region for combined constructs.
405  /// \param CodeGen Code generation sequence for combined directives. Includes
406  /// a list of functions used for code generation of implicitly inlined
407  /// regions.
408  InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
409  OpenMPDirectiveKind Kind, bool HasCancel)
410  : CGF(CGF) {
411  // Start emission for the construct.
412  CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413  CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
414  std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415  LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416  CGF.LambdaThisCaptureField = nullptr;
417  BlockInfo = CGF.BlockInfo;
418  CGF.BlockInfo = nullptr;
419  }
420 
421  ~InlinedOpenMPRegionRAII() {
422  // Restore original CapturedStmtInfo only if we're done with code emission.
423  auto *OldCSI =
424  cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425  delete CGF.CapturedStmtInfo;
426  CGF.CapturedStmtInfo = OldCSI;
427  std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428  CGF.LambdaThisCaptureField = LambdaThisCaptureField;
429  CGF.BlockInfo = BlockInfo;
430  }
431 };
432 
433 /// Values for bit flags used in the ident_t to describe the fields.
434 /// All enumeric elements are named and described in accordance with the code
435 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
436 enum OpenMPLocationFlags : unsigned {
437  /// Use trampoline for internal microtask.
438  OMP_IDENT_IMD = 0x01,
439  /// Use c-style ident structure.
440  OMP_IDENT_KMPC = 0x02,
441  /// Atomic reduction option for kmpc_reduce.
442  OMP_ATOMIC_REDUCE = 0x10,
443  /// Explicit 'barrier' directive.
444  OMP_IDENT_BARRIER_EXPL = 0x20,
445  /// Implicit barrier in code.
446  OMP_IDENT_BARRIER_IMPL = 0x40,
447  /// Implicit barrier in 'for' directive.
448  OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
449  /// Implicit barrier in 'sections' directive.
450  OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
451  /// Implicit barrier in 'single' directive.
452  OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453  /// Call of __kmp_for_static_init for static loop.
454  OMP_IDENT_WORK_LOOP = 0x200,
455  /// Call of __kmp_for_static_init for sections.
456  OMP_IDENT_WORK_SECTIONS = 0x400,
457  /// Call of __kmp_for_static_init for distribute.
458  OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
460 };
461 
462 /// Describes ident structure that describes a source location.
463 /// All descriptions are taken from
464 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465 /// Original structure:
466 /// typedef struct ident {
467 /// kmp_int32 reserved_1; /**< might be used in Fortran;
468 /// see above */
469 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470 /// KMP_IDENT_KMPC identifies this union
471 /// member */
472 /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473 /// see above */
474 ///#if USE_ITT_BUILD
475 /// /* but currently used for storing
476 /// region-specific ITT */
477 /// /* contextual information. */
478 ///#endif /* USE_ITT_BUILD */
479 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480 /// C++ */
481 /// char const *psource; /**< String describing the source location.
482 /// The string is composed of semi-colon separated
483 // fields which describe the source file,
484 /// the function and a pair of line numbers that
485 /// delimit the construct.
486 /// */
487 /// } ident_t;
489  /// might be used in Fortran
491  /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
493  /// Not really used in Fortran any more
495  /// Source[4] in Fortran, do not use for C++
497  /// String describing the source location. The string is composed of
498  /// semi-colon separated fields which describe the source file, the function
499  /// and a pair of line numbers that delimit the construct.
501 };
502 
503 /// Schedule types for 'omp for' loops (these enumerators are taken from
504 /// the enum sched_type in kmp.h).
506  /// Lower bound for default (unordered) versions.
514  /// static with chunk adjustment (e.g., simd)
516  /// Lower bound for 'ordered' versions.
525  /// dist_schedule types
528  /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529  /// Set if the monotonic schedule modifier was present.
531  /// Set if the nonmonotonic schedule modifier was present.
533 };
534 
536  /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
537  /// kmpc_micro microtask, ...);
539  /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
540  /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
542  /// Call to void __kmpc_threadprivate_register( ident_t *,
543  /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
545  // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
547  // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548  // kmp_critical_name *crit);
550  // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551  // global_tid, kmp_critical_name *crit, uintptr_t hint);
553  // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554  // kmp_critical_name *crit);
556  // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557  // global_tid);
559  // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
561  // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
563  // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564  // global_tid);
566  // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567  // global_tid);
569  // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570  // kmp_int32 num_threads);
572  // Call to void __kmpc_flush(ident_t *loc);
574  // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
576  // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
578  // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579  // int end_part);
581  // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
583  // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
585  // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586  // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587  // kmp_routine_entry_t *task_entry);
589  // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590  // new_task);
592  // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593  // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594  // kmp_int32 didit);
596  // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597  // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598  // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
600  // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601  // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602  // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603  // *lck);
605  // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606  // kmp_critical_name *lck);
608  // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609  // kmp_critical_name *lck);
611  // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612  // kmp_task_t * new_task);
614  // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615  // kmp_task_t * new_task);
617  // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
619  // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
621  // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622  // global_tid);
624  // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
626  // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
628  // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629  // int proc_bind);
631  // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632  // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633  // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
635  // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636  // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637  // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
639  // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640  // global_tid, kmp_int32 cncl_kind);
642  // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643  // kmp_int32 cncl_kind);
645  // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646  // kmp_int32 num_teams, kmp_int32 thread_limit);
648  // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649  // microtask, ...);
651  // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652  // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653  // sched, kmp_uint64 grainsize, void *task_dup);
655  // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656  // num_dims, struct kmp_dim *dims);
658  // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
660  // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661  // *vec);
663  // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664  // *vec);
666  // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667  // *data);
669  // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670  // *d);
672 
673  //
674  // Offloading related calls
675  //
676  // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
678  // *arg_types);
680  // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682  // *arg_types);
684  // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686  // *arg_types, int32_t num_teams, int32_t thread_limit);
688  // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689  // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690  // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
692  // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
694  // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
696  // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
699  // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701  // *arg_types);
703  // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
706  // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708  // *arg_types);
710  // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
713  // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715  // *arg_types);
717 };
718 
719 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720 /// region.
721 class CleanupTy final : public EHScopeStack::Cleanup {
722  PrePostActionTy *Action;
723 
724 public:
725  explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726  void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727  if (!CGF.HaveInsertPoint())
728  return;
729  Action->Exit(CGF);
730  }
731 };
732 
733 } // anonymous namespace
734 
737  if (PrePostAction) {
738  CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739  Callback(CodeGen, CGF, *PrePostAction);
740  } else {
741  PrePostActionTy Action;
742  Callback(CodeGen, CGF, Action);
743  }
744 }
745 
746 /// Check if the combiner is a call to UDR combiner and if it is so return the
747 /// UDR decl used for reduction.
748 static const OMPDeclareReductionDecl *
749 getReductionInit(const Expr *ReductionOp) {
750  if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752  if (const auto *DRE =
753  dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
754  if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
755  return DRD;
756  return nullptr;
757 }
758 
760  const OMPDeclareReductionDecl *DRD,
761  const Expr *InitOp,
762  Address Private, Address Original,
763  QualType Ty) {
764  if (DRD->getInitializer()) {
765  std::pair<llvm::Function *, llvm::Function *> Reduction =
766  CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
767  const auto *CE = cast<CallExpr>(InitOp);
768  const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
769  const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770  const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
771  const auto *LHSDRE =
772  cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773  const auto *RHSDRE =
774  cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
775  CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776  PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
777  [=]() { return Private; });
778  PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
779  [=]() { return Original; });
780  (void)PrivateScope.Privatize();
781  RValue Func = RValue::get(Reduction.second);
782  CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783  CGF.EmitIgnoredExpr(InitOp);
784  } else {
785  llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
786  std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
787  auto *GV = new llvm::GlobalVariable(
788  CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
789  llvm::GlobalValue::PrivateLinkage, Init, Name);
790  LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791  RValue InitRVal;
792  switch (CGF.getEvaluationKind(Ty)) {
793  case TEK_Scalar:
794  InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
795  break;
796  case TEK_Complex:
797  InitRVal =
799  break;
800  case TEK_Aggregate:
801  InitRVal = RValue::getAggregate(LV.getAddress());
802  break;
803  }
804  OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
805  CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806  CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807  /*IsInitializer=*/false);
808  }
809 }
810 
811 /// Emit initialization of arrays of complex types.
812 /// \param DestAddr Address of the array.
813 /// \param Type Type of array.
814 /// \param Init Initial expression of array.
815 /// \param SrcAddr Address of the original array.
816 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
817  QualType Type, bool EmitDeclareReductionInit,
818  const Expr *Init,
819  const OMPDeclareReductionDecl *DRD,
820  Address SrcAddr = Address::invalid()) {
821  // Perform element-by-element initialization.
822  QualType ElementTy;
823 
824  // Drill down to the base element type on both arrays.
825  const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826  llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
827  DestAddr =
828  CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829  if (DRD)
830  SrcAddr =
831  CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832 
833  llvm::Value *SrcBegin = nullptr;
834  if (DRD)
835  SrcBegin = SrcAddr.getPointer();
836  llvm::Value *DestBegin = DestAddr.getPointer();
837  // Cast from pointer to array type to pointer to single element.
838  llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
839  // The basic structure here is a while-do loop.
840  llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841  llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842  llvm::Value *IsEmpty =
843  CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844  CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845 
846  // Enter the loop body, making that address the current address.
847  llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
848  CGF.EmitBlock(BodyBB);
849 
850  CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851 
852  llvm::PHINode *SrcElementPHI = nullptr;
853  Address SrcElementCurrent = Address::invalid();
854  if (DRD) {
855  SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856  "omp.arraycpy.srcElementPast");
857  SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858  SrcElementCurrent =
859  Address(SrcElementPHI,
860  SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861  }
862  llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863  DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864  DestElementPHI->addIncoming(DestBegin, EntryBB);
865  Address DestElementCurrent =
866  Address(DestElementPHI,
867  DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868 
869  // Emit copy.
870  {
871  CodeGenFunction::RunCleanupsScope InitScope(CGF);
872  if (EmitDeclareReductionInit) {
873  emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874  SrcElementCurrent, ElementTy);
875  } else
876  CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877  /*IsInitializer=*/false);
878  }
879 
880  if (DRD) {
881  // Shift the address forward by one element.
882  llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
883  SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884  SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885  }
886 
887  // Shift the address forward by one element.
888  llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
889  DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890  // Check whether we've reached the end.
891  llvm::Value *Done =
892  CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893  CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894  DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895 
896  // Done.
897  CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898 }
899 
900 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
901  return CGF.EmitOMPSharedLValue(E);
902 }
903 
904 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
905  const Expr *E) {
906  if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
907  return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
908  return LValue();
909 }
910 
911 void ReductionCodeGen::emitAggregateInitialization(
912  CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
913  const OMPDeclareReductionDecl *DRD) {
914  // Emit VarDecl with copy init for arrays.
915  // Get the address of the original variable captured in current
916  // captured region.
917  const auto *PrivateVD =
918  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
919  bool EmitDeclareReductionInit =
920  DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
921  EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
922  EmitDeclareReductionInit,
923  EmitDeclareReductionInit ? ClausesData[N].ReductionOp
924  : PrivateVD->getInit(),
925  DRD, SharedLVal.getAddress());
926 }
927 
930  ArrayRef<const Expr *> ReductionOps) {
931  ClausesData.reserve(Shareds.size());
932  SharedAddresses.reserve(Shareds.size());
933  Sizes.reserve(Shareds.size());
934  BaseDecls.reserve(Shareds.size());
935  auto IPriv = Privates.begin();
936  auto IRed = ReductionOps.begin();
937  for (const Expr *Ref : Shareds) {
938  ClausesData.emplace_back(Ref, *IPriv, *IRed);
939  std::advance(IPriv, 1);
940  std::advance(IRed, 1);
941  }
942 }
943 
944 void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
945  assert(SharedAddresses.size() == N &&
946  "Number of generated lvalues must be exactly N.");
947  LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
948  LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
949  SharedAddresses.emplace_back(First, Second);
950 }
951 
953  const auto *PrivateVD =
954  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
955  QualType PrivateType = PrivateVD->getType();
956  bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
957  if (!PrivateType->isVariablyModifiedType()) {
958  Sizes.emplace_back(
959  CGF.getTypeSize(
960  SharedAddresses[N].first.getType().getNonReferenceType()),
961  nullptr);
962  return;
963  }
964  llvm::Value *Size;
965  llvm::Value *SizeInChars;
966  auto *ElemType =
967  cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
968  ->getElementType();
969  auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
970  if (AsArraySection) {
971  Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
972  SharedAddresses[N].first.getPointer());
973  Size = CGF.Builder.CreateNUWAdd(
974  Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
975  SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
976  } else {
977  SizeInChars = CGF.getTypeSize(
978  SharedAddresses[N].first.getType().getNonReferenceType());
979  Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
980  }
981  Sizes.emplace_back(SizeInChars, Size);
983  CGF,
984  cast<OpaqueValueExpr>(
985  CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
986  RValue::get(Size));
987  CGF.EmitVariablyModifiedType(PrivateType);
988 }
989 
991  llvm::Value *Size) {
992  const auto *PrivateVD =
993  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
994  QualType PrivateType = PrivateVD->getType();
995  if (!PrivateType->isVariablyModifiedType()) {
996  assert(!Size && !Sizes[N].second &&
997  "Size should be nullptr for non-variably modified reduction "
998  "items.");
999  return;
1000  }
1002  CGF,
1003  cast<OpaqueValueExpr>(
1004  CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005  RValue::get(Size));
1006  CGF.EmitVariablyModifiedType(PrivateType);
1007 }
1008 
1010  CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1011  llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1012  assert(SharedAddresses.size() > N && "No variable was generated");
1013  const auto *PrivateVD =
1014  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1015  const OMPDeclareReductionDecl *DRD =
1016  getReductionInit(ClausesData[N].ReductionOp);
1017  QualType PrivateType = PrivateVD->getType();
1018  PrivateAddr = CGF.Builder.CreateElementBitCast(
1019  PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1020  QualType SharedType = SharedAddresses[N].first.getType();
1021  SharedLVal = CGF.MakeAddrLValue(
1022  CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1023  CGF.ConvertTypeForMem(SharedType)),
1024  SharedType, SharedAddresses[N].first.getBaseInfo(),
1025  CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
1026  if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
1027  emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
1028  } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1029  emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1030  PrivateAddr, SharedLVal.getAddress(),
1031  SharedLVal.getType());
1032  } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1033  !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1034  CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1035  PrivateVD->getType().getQualifiers(),
1036  /*IsInitializer=*/false);
1037  }
1038 }
1039 
1041  const auto *PrivateVD =
1042  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043  QualType PrivateType = PrivateVD->getType();
1044  QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045  return DTorKind != QualType::DK_none;
1046 }
1047 
1049  Address PrivateAddr) {
1050  const auto *PrivateVD =
1051  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1052  QualType PrivateType = PrivateVD->getType();
1053  QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1054  if (needCleanups(N)) {
1055  PrivateAddr = CGF.Builder.CreateElementBitCast(
1056  PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1057  CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1058  }
1059 }
1060 
1062  LValue BaseLV) {
1063  BaseTy = BaseTy.getNonReferenceType();
1064  while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1065  !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1066  if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
1067  BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1068  } else {
1069  LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1070  BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
1071  }
1072  BaseTy = BaseTy->getPointeeType();
1073  }
1074  return CGF.MakeAddrLValue(
1076  CGF.ConvertTypeForMem(ElTy)),
1077  BaseLV.getType(), BaseLV.getBaseInfo(),
1078  CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
1079 }
1080 
1082  llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1083  llvm::Value *Addr) {
1084  Address Tmp = Address::invalid();
1085  Address TopTmp = Address::invalid();
1086  Address MostTopTmp = Address::invalid();
1087  BaseTy = BaseTy.getNonReferenceType();
1088  while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1089  !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1090  Tmp = CGF.CreateMemTemp(BaseTy);
1091  if (TopTmp.isValid())
1092  CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1093  else
1094  MostTopTmp = Tmp;
1095  TopTmp = Tmp;
1096  BaseTy = BaseTy->getPointeeType();
1097  }
1098  llvm::Type *Ty = BaseLVType;
1099  if (Tmp.isValid())
1100  Ty = Tmp.getElementType();
1101  Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1102  if (Tmp.isValid()) {
1103  CGF.Builder.CreateStore(Addr, Tmp);
1104  return MostTopTmp;
1105  }
1106  return Address(Addr, BaseLVAlignment);
1107 }
1108 
1109 static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
1110  const VarDecl *OrigVD = nullptr;
1111  if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1112  const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1113  while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1114  Base = TempOASE->getBase()->IgnoreParenImpCasts();
1115  while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1116  Base = TempASE->getBase()->IgnoreParenImpCasts();
1117  DE = cast<DeclRefExpr>(Base);
1118  OrigVD = cast<VarDecl>(DE->getDecl());
1119  } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1120  const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1121  while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1122  Base = TempASE->getBase()->IgnoreParenImpCasts();
1123  DE = cast<DeclRefExpr>(Base);
1124  OrigVD = cast<VarDecl>(DE->getDecl());
1125  }
1126  return OrigVD;
1127 }
1128 
1130  Address PrivateAddr) {
1131  const DeclRefExpr *DE;
1132  if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
1133  BaseDecls.emplace_back(OrigVD);
1134  LValue OriginalBaseLValue = CGF.EmitLValue(DE);
1135  LValue BaseLValue =
1136  loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1137  OriginalBaseLValue);
1138  llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1139  BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1140  llvm::Value *PrivatePointer =
1142  PrivateAddr.getPointer(),
1143  SharedAddresses[N].first.getAddress().getType());
1144  llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
1145  return castToBase(CGF, OrigVD->getType(),
1146  SharedAddresses[N].first.getType(),
1147  OriginalBaseLValue.getAddress().getType(),
1148  OriginalBaseLValue.getAlignment(), Ptr);
1149  }
1150  BaseDecls.emplace_back(
1151  cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1152  return PrivateAddr;
1153 }
1154 
1156  const OMPDeclareReductionDecl *DRD =
1157  getReductionInit(ClausesData[N].ReductionOp);
1158  return DRD && DRD->getInitializer();
1159 }
1160 
1161 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1162  return CGF.EmitLoadOfPointerLValue(
1163  CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1164  getThreadIDVariable()->getType()->castAs<PointerType>());
1165 }
1166 
1167 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
1168  if (!CGF.HaveInsertPoint())
1169  return;
1170  // 1.2.2 OpenMP Language Terminology
1171  // Structured block - An executable statement with a single entry at the
1172  // top and a single exit at the bottom.
1173  // The point of exit cannot be a branch out of the structured block.
1174  // longjmp() and throw() must not violate the entry/exit criteria.
1175  CGF.EHStack.pushTerminate();
1176  CodeGen(CGF);
1177  CGF.EHStack.popTerminate();
1178 }
1179 
1180 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1181  CodeGenFunction &CGF) {
1182  return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183  getThreadIDVariable()->getType(),
1185 }
1186 
1188  QualType FieldTy) {
1189  auto *Field = FieldDecl::Create(
1190  C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1192  /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1193  Field->setAccess(AS_public);
1194  DC->addDecl(Field);
1195  return Field;
1196 }
1197 
1198 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1199  StringRef Separator)
1200  : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1202  ASTContext &C = CGM.getContext();
1203  RecordDecl *RD = C.buildImplicitRecord("ident_t");
1204  QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1205  RD->startDefinition();
1206  // reserved_1
1207  addFieldToRecordDecl(C, RD, KmpInt32Ty);
1208  // flags
1209  addFieldToRecordDecl(C, RD, KmpInt32Ty);
1210  // reserved_2
1211  addFieldToRecordDecl(C, RD, KmpInt32Ty);
1212  // reserved_3
1213  addFieldToRecordDecl(C, RD, KmpInt32Ty);
1214  // psource
1215  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1216  RD->completeDefinition();
1217  IdentQTy = C.getRecordType(RD);
1218  IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
1219  KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1220 
1222 }
1223 
1224 void CGOpenMPRuntime::clear() {
1225  InternalVars.clear();
1226 }
1227 
1228 std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1229  SmallString<128> Buffer;
1230  llvm::raw_svector_ostream OS(Buffer);
1231  StringRef Sep = FirstSeparator;
1232  for (StringRef Part : Parts) {
1233  OS << Sep << Part;
1234  Sep = Separator;
1235  }
1236  return OS.str();
1237 }
1238 
1239 static llvm::Function *
1241  const Expr *CombinerInitializer, const VarDecl *In,
1242  const VarDecl *Out, bool IsCombiner) {
1243  // void .omp_combiner.(Ty *in, Ty *out);
1244  ASTContext &C = CGM.getContext();
1245  QualType PtrTy = C.getPointerType(Ty).withRestrict();
1246  FunctionArgList Args;
1247  ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1248  /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1249  ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1250  /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1251  Args.push_back(&OmpOutParm);
1252  Args.push_back(&OmpInParm);
1253  const CGFunctionInfo &FnInfo =
1255  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1256  std::string Name = CGM.getOpenMPRuntime().getName(
1257  {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1259  Name, &CGM.getModule());
1260  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1261  Fn->removeFnAttr(llvm::Attribute::NoInline);
1262  Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1263  Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1264  CodeGenFunction CGF(CGM);
1265  // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1266  // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1267  CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1268  Out->getLocation());
1270  Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1271  Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
1272  return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1273  .getAddress();
1274  });
1275  Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1276  Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
1277  return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1278  .getAddress();
1279  });
1280  (void)Scope.Privatize();
1281  if (!IsCombiner && Out->hasInit() &&
1282  !CGF.isTrivialInitializer(Out->getInit())) {
1283  CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1284  Out->getType().getQualifiers(),
1285  /*IsInitializer=*/true);
1286  }
1287  if (CombinerInitializer)
1288  CGF.EmitIgnoredExpr(CombinerInitializer);
1289  Scope.ForceCleanup();
1290  CGF.FinishFunction();
1291  return Fn;
1292 }
1293 
1295  CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1296  if (UDRMap.count(D) > 0)
1297  return;
1298  llvm::Function *Combiner = emitCombinerOrInitializer(
1299  CGM, D->getType(), D->getCombiner(),
1300  cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1301  cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
1302  /*IsCombiner=*/true);
1303  llvm::Function *Initializer = nullptr;
1304  if (const Expr *Init = D->getInitializer()) {
1305  Initializer = emitCombinerOrInitializer(
1306  CGM, D->getType(),
1308  : nullptr,
1309  cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1310  cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
1311  /*IsCombiner=*/false);
1312  }
1313  UDRMap.try_emplace(D, Combiner, Initializer);
1314  if (CGF) {
1315  auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1316  Decls.second.push_back(D);
1317  }
1318 }
1319 
1320 std::pair<llvm::Function *, llvm::Function *>
1322  auto I = UDRMap.find(D);
1323  if (I != UDRMap.end())
1324  return I->second;
1325  emitUserDefinedReduction(/*CGF=*/nullptr, D);
1326  return UDRMap.lookup(D);
1327 }
1328 
1330  CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1331  const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1332  const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1333  assert(ThreadIDVar->getType()->isPointerType() &&
1334  "thread id variable must be of type kmp_int32 *");
1335  CodeGenFunction CGF(CGM, true);
1336  bool HasCancel = false;
1337  if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1338  HasCancel = OPD->hasCancel();
1339  else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1340  HasCancel = OPSD->hasCancel();
1341  else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1342  HasCancel = OPFD->hasCancel();
1343  else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1344  HasCancel = OPFD->hasCancel();
1345  else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1346  HasCancel = OPFD->hasCancel();
1347  else if (const auto *OPFD =
1348  dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1349  HasCancel = OPFD->hasCancel();
1350  else if (const auto *OPFD =
1351  dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1352  HasCancel = OPFD->hasCancel();
1353  CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1354  HasCancel, OutlinedHelperName);
1355  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1356  return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
1357 }
1358 
1360  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1361  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1362  const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1364  CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1365 }
1366 
1368  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1369  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1370  const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1372  CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1373 }
1374 
1376  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1377  const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1378  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1379  bool Tied, unsigned &NumberOfParts) {
1380  auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1381  PrePostActionTy &) {
1382  llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1383  llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
1384  llvm::Value *TaskArgs[] = {
1385  UpLoc, ThreadID,
1386  CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1387  TaskTVar->getType()->castAs<PointerType>())
1388  .getPointer()};
1389  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1390  };
1391  CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1392  UntiedCodeGen);
1393  CodeGen.setAction(Action);
1394  assert(!ThreadIDVar->getType()->isPointerType() &&
1395  "thread id variable must be of type kmp_int32 for tasks");
1396  const OpenMPDirectiveKind Region =
1397  isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1398  : OMPD_task;
1399  const CapturedStmt *CS = D.getCapturedStmt(Region);
1400  const auto *TD = dyn_cast<OMPTaskDirective>(&D);
1401  CodeGenFunction CGF(CGM, true);
1402  CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1403  InnermostKind,
1404  TD ? TD->hasCancel() : false, Action);
1405  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1406  llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
1407  if (!Tied)
1408  NumberOfParts = Action.getNumberOfParts();
1409  return Res;
1410 }
1411 
1413  const RecordDecl *RD, const CGRecordLayout &RL,
1414  ArrayRef<llvm::Constant *> Data) {
1415  llvm::StructType *StructTy = RL.getLLVMType();
1416  unsigned PrevIdx = 0;
1417  ConstantInitBuilder CIBuilder(CGM);
1418  auto DI = Data.begin();
1419  for (const FieldDecl *FD : RD->fields()) {
1420  unsigned Idx = RL.getLLVMFieldNo(FD);
1421  // Fill the alignment.
1422  for (unsigned I = PrevIdx; I < Idx; ++I)
1423  Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1424  PrevIdx = Idx + 1;
1425  Fields.add(*DI);
1426  ++DI;
1427  }
1428 }
1429 
1430 template <class... As>
1431 static llvm::GlobalVariable *
1433  ArrayRef<llvm::Constant *> Data, const Twine &Name,
1434  As &&... Args) {
1435  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1436  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1437  ConstantInitBuilder CIBuilder(CGM);
1438  ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1439  buildStructValue(Fields, CGM, RD, RL, Data);
1440  return Fields.finishAndCreateGlobal(
1441  Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1442  std::forward<As>(Args)...);
1443 }
1444 
1445 template <typename T>
1446 static void
1448  ArrayRef<llvm::Constant *> Data,
1449  T &Parent) {
1450  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1451  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1452  ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1453  buildStructValue(Fields, CGM, RD, RL, Data);
1454  Fields.finishAndAddTo(Parent);
1455 }
1456 
1457 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
1458  CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1459  llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
1460  if (!Entry) {
1461  if (!DefaultOpenMPPSource) {
1462  // Initialize default location for psource field of ident_t structure of
1463  // all ident_t objects. Format is ";file;function;line;column;;".
1464  // Taken from
1465  // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1466  DefaultOpenMPPSource =
1467  CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
1468  DefaultOpenMPPSource =
1469  llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1470  }
1471 
1472  llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1473  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1474  llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1475  llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1476  DefaultOpenMPPSource};
1477  llvm::GlobalValue *DefaultOpenMPLocation =
1478  createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "",
1479  llvm::GlobalValue::PrivateLinkage);
1480  DefaultOpenMPLocation->setUnnamedAddr(
1481  llvm::GlobalValue::UnnamedAddr::Global);
1482 
1483  OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
1484  }
1485  return Address(Entry, Align);
1486 }
1487 
1489  bool AtCurrentPoint) {
1490  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1491  assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1492 
1493  llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1494  if (AtCurrentPoint) {
1495  Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1496  Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1497  } else {
1498  Elem.second.ServiceInsertPt =
1499  new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1500  Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1501  }
1502 }
1503 
1505  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1506  if (Elem.second.ServiceInsertPt) {
1507  llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1508  Elem.second.ServiceInsertPt = nullptr;
1509  Ptr->eraseFromParent();
1510  }
1511 }
1512 
1514  SourceLocation Loc,
1515  unsigned Flags) {
1516  Flags |= OMP_IDENT_KMPC;
1517  // If no debug info is generated - return global default location.
1518  if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1519  Loc.isInvalid())
1520  return getOrCreateDefaultLocation(Flags).getPointer();
1521 
1522  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1523 
1524  CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1525  Address LocValue = Address::invalid();
1526  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1527  if (I != OpenMPLocThreadIDMap.end())
1528  LocValue = Address(I->second.DebugLoc, Align);
1529 
1530  // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1531  // GetOpenMPThreadID was called before this routine.
1532  if (!LocValue.isValid()) {
1533  // Generate "ident_t .kmpc_loc.addr;"
1534  Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
1535  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1536  Elem.second.DebugLoc = AI.getPointer();
1537  LocValue = AI;
1538 
1539  if (!Elem.second.ServiceInsertPt)
1541  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1542  CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
1543  CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
1544  CGF.getTypeSize(IdentQTy));
1545  }
1546 
1547  // char **psource = &.kmpc_loc_<flags>.addr.psource;
1548  LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1549  auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1550  LValue PSource =
1551  CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
1552 
1553  llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1554  if (OMPDebugLoc == nullptr) {
1555  SmallString<128> Buffer2;
1556  llvm::raw_svector_ostream OS2(Buffer2);
1557  // Build debug location
1559  OS2 << ";" << PLoc.getFilename() << ";";
1560  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1561  OS2 << FD->getQualifiedNameAsString();
1562  OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1563  OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1564  OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
1565  }
1566  // *psource = ";<File>;<Function>;<Line>;<Column>;;";
1567  CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
1568 
1569  // Our callers always pass this to a runtime function, so for
1570  // convenience, go ahead and return a naked pointer.
1571  return LocValue.getPointer();
1572 }
1573 
1575  SourceLocation Loc) {
1576  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1577 
1578  llvm::Value *ThreadID = nullptr;
1579  // Check whether we've already cached a load of the thread id in this
1580  // function.
1581  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1582  if (I != OpenMPLocThreadIDMap.end()) {
1583  ThreadID = I->second.ThreadID;
1584  if (ThreadID != nullptr)
1585  return ThreadID;
1586  }
1587  // If exceptions are enabled, do not use parameter to avoid possible crash.
1588  if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1589  !CGF.getLangOpts().CXXExceptions ||
1590  CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1591  if (auto *OMPRegionInfo =
1592  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1593  if (OMPRegionInfo->getThreadIDVariable()) {
1594  // Check if this an outlined function with thread id passed as argument.
1595  LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1596  ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1597  // If value loaded in entry block, cache it and use it everywhere in
1598  // function.
1599  if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1600  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1601  Elem.second.ThreadID = ThreadID;
1602  }
1603  return ThreadID;
1604  }
1605  }
1606  }
1607 
1608  // This is not an outlined function region - need to call __kmpc_int32
1609  // kmpc_global_thread_num(ident_t *loc).
1610  // Generate thread id value and cache this value for use across the
1611  // function.
1612  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1613  if (!Elem.second.ServiceInsertPt)
1615  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1616  CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
1617  llvm::CallInst *Call = CGF.Builder.CreateCall(
1619  emitUpdateLocation(CGF, Loc));
1620  Call->setCallingConv(CGF.getRuntimeCC());
1621  Elem.second.ThreadID = Call;
1622  return Call;
1623 }
1624 
1626  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1627  if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1629  OpenMPLocThreadIDMap.erase(CGF.CurFn);
1630  }
1631  if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1632  for(auto *D : FunctionUDRMap[CGF.CurFn])
1633  UDRMap.erase(D);
1634  FunctionUDRMap.erase(CGF.CurFn);
1635  }
1636 }
1637 
1639  return IdentTy->getPointerTo();
1640 }
1641 
1643  if (!Kmpc_MicroTy) {
1644  // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1645  llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1646  llvm::PointerType::getUnqual(CGM.Int32Ty)};
1647  Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1648  }
1649  return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1650 }
1651 
1652 llvm::Constant *
1654  llvm::Constant *RTLFn = nullptr;
1655  switch (static_cast<OpenMPRTLFunction>(Function)) {
1656  case OMPRTL__kmpc_fork_call: {
1657  // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1658  // microtask, ...);
1659  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1661  auto *FnTy =
1662  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1663  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1664  break;
1665  }
1667  // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1668  llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1669  auto *FnTy =
1670  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1671  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1672  break;
1673  }
1675  // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1676  // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1677  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1679  CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1680  auto *FnTy =
1681  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1682  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1683  break;
1684  }
1685  case OMPRTL__kmpc_critical: {
1686  // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1687  // kmp_critical_name *crit);
1688  llvm::Type *TypeParams[] = {
1690  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1691  auto *FnTy =
1692  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1694  break;
1695  }
1697  // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1698  // kmp_critical_name *crit, uintptr_t hint);
1699  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1700  llvm::PointerType::getUnqual(KmpCriticalNameTy),
1701  CGM.IntPtrTy};
1702  auto *FnTy =
1703  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1704  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1705  break;
1706  }
1708  // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1709  // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1710  // typedef void *(*kmpc_ctor)(void *);
1711  auto *KmpcCtorTy =
1712  llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1713  /*isVarArg*/ false)->getPointerTo();
1714  // typedef void *(*kmpc_cctor)(void *, void *);
1715  llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1716  auto *KmpcCopyCtorTy =
1717  llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1718  /*isVarArg*/ false)
1719  ->getPointerTo();
1720  // typedef void (*kmpc_dtor)(void *);
1721  auto *KmpcDtorTy =
1722  llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1723  ->getPointerTo();
1724  llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1725  KmpcCopyCtorTy, KmpcDtorTy};
1726  auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1727  /*isVarArg*/ false);
1728  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1729  break;
1730  }
1732  // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1733  // kmp_critical_name *crit);
1734  llvm::Type *TypeParams[] = {
1736  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1737  auto *FnTy =
1738  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1739  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1740  break;
1741  }
1743  // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1744  // global_tid);
1745  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1746  auto *FnTy =
1747  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1748  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1749  break;
1750  }
1751  case OMPRTL__kmpc_barrier: {
1752  // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1753  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1754  auto *FnTy =
1755  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1756  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1757  break;
1758  }
1760  // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1761  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1762  auto *FnTy =
1763  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1764  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1765  break;
1766  }
1768  // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1769  // kmp_int32 num_threads)
1770  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1771  CGM.Int32Ty};
1772  auto *FnTy =
1773  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1774  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1775  break;
1776  }
1778  // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1779  // global_tid);
1780  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1781  auto *FnTy =
1782  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1783  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1784  break;
1785  }
1787  // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1788  // global_tid);
1789  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1790  auto *FnTy =
1791  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1792  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1793  break;
1794  }
1795  case OMPRTL__kmpc_flush: {
1796  // Build void __kmpc_flush(ident_t *loc);
1797  llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1798  auto *FnTy =
1799  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1800  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1801  break;
1802  }
1803  case OMPRTL__kmpc_master: {
1804  // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1805  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1806  auto *FnTy =
1807  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1808  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1809  break;
1810  }
1811  case OMPRTL__kmpc_end_master: {
1812  // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1813  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1814  auto *FnTy =
1815  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1817  break;
1818  }
1820  // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1821  // int end_part);
1822  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1823  auto *FnTy =
1824  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1825  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1826  break;
1827  }
1828  case OMPRTL__kmpc_single: {
1829  // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1830  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1831  auto *FnTy =
1832  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1833  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1834  break;
1835  }
1836  case OMPRTL__kmpc_end_single: {
1837  // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1838  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1839  auto *FnTy =
1840  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1841  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1842  break;
1843  }
1845  // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1846  // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1847  // kmp_routine_entry_t *task_entry);
1848  assert(KmpRoutineEntryPtrTy != nullptr &&
1849  "Type kmp_routine_entry_t must be created.");
1850  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1851  CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1852  // Return void * and then cast to particular kmp_task_t type.
1853  auto *FnTy =
1854  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1855  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1856  break;
1857  }
1858  case OMPRTL__kmpc_omp_task: {
1859  // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1860  // *new_task);
1861  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1862  CGM.VoidPtrTy};
1863  auto *FnTy =
1864  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1865  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1866  break;
1867  }
1868  case OMPRTL__kmpc_copyprivate: {
1869  // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1870  // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1871  // kmp_int32 didit);
1872  llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1873  auto *CpyFnTy =
1874  llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1875  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1876  CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1877  CGM.Int32Ty};
1878  auto *FnTy =
1879  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1880  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1881  break;
1882  }
1883  case OMPRTL__kmpc_reduce: {
1884  // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1885  // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1886  // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1887  llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1888  auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1889  /*isVarArg=*/false);
1890  llvm::Type *TypeParams[] = {
1892  CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1893  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1894  auto *FnTy =
1895  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1896  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1897  break;
1898  }
1900  // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1901  // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1902  // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1903  // *lck);
1904  llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1905  auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1906  /*isVarArg=*/false);
1907  llvm::Type *TypeParams[] = {
1909  CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1910  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1911  auto *FnTy =
1912  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1913  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1914  break;
1915  }
1916  case OMPRTL__kmpc_end_reduce: {
1917  // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1918  // kmp_critical_name *lck);
1919  llvm::Type *TypeParams[] = {
1921  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1922  auto *FnTy =
1923  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1924  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1925  break;
1926  }
1928  // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1929  // kmp_critical_name *lck);
1930  llvm::Type *TypeParams[] = {
1932  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1933  auto *FnTy =
1934  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1935  RTLFn =
1936  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1937  break;
1938  }
1940  // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1941  // *new_task);
1942  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1943  CGM.VoidPtrTy};
1944  auto *FnTy =
1945  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1946  RTLFn =
1947  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1948  break;
1949  }
1951  // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1952  // *new_task);
1953  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1954  CGM.VoidPtrTy};
1955  auto *FnTy =
1956  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1957  RTLFn = CGM.CreateRuntimeFunction(FnTy,
1958  /*Name=*/"__kmpc_omp_task_complete_if0");
1959  break;
1960  }
1961  case OMPRTL__kmpc_ordered: {
1962  // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1963  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1964  auto *FnTy =
1965  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1966  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1967  break;
1968  }
1969  case OMPRTL__kmpc_end_ordered: {
1970  // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1971  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1972  auto *FnTy =
1973  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1974  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1975  break;
1976  }
1978  // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1979  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1980  auto *FnTy =
1981  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1982  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1983  break;
1984  }
1985  case OMPRTL__kmpc_taskgroup: {
1986  // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1987  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1988  auto *FnTy =
1989  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1990  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1991  break;
1992  }
1994  // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1995  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1996  auto *FnTy =
1997  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1998  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1999  break;
2000  }
2002  // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2003  // int proc_bind)
2004  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2005  auto *FnTy =
2006  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2007  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2008  break;
2009  }
2011  // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2012  // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2013  // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2014  llvm::Type *TypeParams[] = {
2017  auto *FnTy =
2018  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2019  RTLFn =
2020  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2021  break;
2022  }
2024  // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2025  // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2026  // kmp_depend_info_t *noalias_dep_list);
2027  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2030  auto *FnTy =
2031  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2032  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2033  break;
2034  }
2036  // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2037  // global_tid, kmp_int32 cncl_kind)
2038  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2039  auto *FnTy =
2040  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2041  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2042  break;
2043  }
2044  case OMPRTL__kmpc_cancel: {
2045  // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2046  // kmp_int32 cncl_kind)
2047  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2048  auto *FnTy =
2049  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2050  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2051  break;
2052  }
2054  // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2055  // kmp_int32 num_teams, kmp_int32 num_threads)
2056  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2057  CGM.Int32Ty};
2058  auto *FnTy =
2059  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2060  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2061  break;
2062  }
2063  case OMPRTL__kmpc_fork_teams: {
2064  // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2065  // microtask, ...);
2066  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2068  auto *FnTy =
2069  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2070  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2071  break;
2072  }
2073  case OMPRTL__kmpc_taskloop: {
2074  // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2075  // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2076  // sched, kmp_uint64 grainsize, void *task_dup);
2077  llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2078  CGM.IntTy,
2079  CGM.VoidPtrTy,
2080  CGM.IntTy,
2081  CGM.Int64Ty->getPointerTo(),
2082  CGM.Int64Ty->getPointerTo(),
2083  CGM.Int64Ty,
2084  CGM.IntTy,
2085  CGM.IntTy,
2086  CGM.Int64Ty,
2087  CGM.VoidPtrTy};
2088  auto *FnTy =
2089  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2090  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2091  break;
2092  }
2094  // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2095  // num_dims, struct kmp_dim *dims);
2096  llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2097  CGM.Int32Ty,
2098  CGM.Int32Ty,
2099  CGM.VoidPtrTy};
2100  auto *FnTy =
2101  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2102  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2103  break;
2104  }
2106  // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2107  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2108  auto *FnTy =
2109  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2110  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2111  break;
2112  }
2114  // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2115  // *vec);
2116  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2117  CGM.Int64Ty->getPointerTo()};
2118  auto *FnTy =
2119  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2120  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2121  break;
2122  }
2124  // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2125  // *vec);
2126  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2127  CGM.Int64Ty->getPointerTo()};
2128  auto *FnTy =
2129  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2130  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2131  break;
2132  }
2134  // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2135  // *data);
2136  llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2137  auto *FnTy =
2138  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2139  RTLFn =
2140  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2141  break;
2142  }
2144  // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2145  // *d);
2146  llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2147  auto *FnTy =
2148  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2149  RTLFn = CGM.CreateRuntimeFunction(
2150  FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2151  break;
2152  }
2153  case OMPRTL__tgt_target: {
2154  // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2155  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2156  // *arg_types);
2157  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2158  CGM.VoidPtrTy,
2159  CGM.Int32Ty,
2160  CGM.VoidPtrPtrTy,
2161  CGM.VoidPtrPtrTy,
2162  CGM.SizeTy->getPointerTo(),
2163  CGM.Int64Ty->getPointerTo()};
2164  auto *FnTy =
2165  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2166  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2167  break;
2168  }
2170  // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2171  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2172  // int64_t *arg_types);
2173  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2174  CGM.VoidPtrTy,
2175  CGM.Int32Ty,
2176  CGM.VoidPtrPtrTy,
2177  CGM.VoidPtrPtrTy,
2178  CGM.SizeTy->getPointerTo(),
2179  CGM.Int64Ty->getPointerTo()};
2180  auto *FnTy =
2181  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2182  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2183  break;
2184  }
2185  case OMPRTL__tgt_target_teams: {
2186  // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
2187  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2188  // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2189  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2190  CGM.VoidPtrTy,
2191  CGM.Int32Ty,
2192  CGM.VoidPtrPtrTy,
2193  CGM.VoidPtrPtrTy,
2194  CGM.SizeTy->getPointerTo(),
2195  CGM.Int64Ty->getPointerTo(),
2196  CGM.Int32Ty,
2197  CGM.Int32Ty};
2198  auto *FnTy =
2199  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2200  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2201  break;
2202  }
2204  // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2205  // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2206  // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2207  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2208  CGM.VoidPtrTy,
2209  CGM.Int32Ty,
2210  CGM.VoidPtrPtrTy,
2211  CGM.VoidPtrPtrTy,
2212  CGM.SizeTy->getPointerTo(),
2213  CGM.Int64Ty->getPointerTo(),
2214  CGM.Int32Ty,
2215  CGM.Int32Ty};
2216  auto *FnTy =
2217  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2218  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2219  break;
2220  }
2221  case OMPRTL__tgt_register_lib: {
2222  // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2223  QualType ParamTy =
2225  llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2226  auto *FnTy =
2227  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2228  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2229  break;
2230  }
2232  // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2233  QualType ParamTy =
2235  llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2236  auto *FnTy =
2237  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2238  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2239  break;
2240  }
2242  // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2243  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2244  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2245  CGM.Int32Ty,
2246  CGM.VoidPtrPtrTy,
2247  CGM.VoidPtrPtrTy,
2248  CGM.SizeTy->getPointerTo(),
2249  CGM.Int64Ty->getPointerTo()};
2250  auto *FnTy =
2251  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2252  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2253  break;
2254  }
2256  // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2257  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2258  // *arg_types);
2259  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2260  CGM.Int32Ty,
2261  CGM.VoidPtrPtrTy,
2262  CGM.VoidPtrPtrTy,
2263  CGM.SizeTy->getPointerTo(),
2264  CGM.Int64Ty->getPointerTo()};
2265  auto *FnTy =
2266  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2267  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2268  break;
2269  }
2271  // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2272  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2273  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2274  CGM.Int32Ty,
2275  CGM.VoidPtrPtrTy,
2276  CGM.VoidPtrPtrTy,
2277  CGM.SizeTy->getPointerTo(),
2278  CGM.Int64Ty->getPointerTo()};
2279  auto *FnTy =
2280  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2281  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2282  break;
2283  }
2285  // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2286  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2287  // *arg_types);
2288  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2289  CGM.Int32Ty,
2290  CGM.VoidPtrPtrTy,
2291  CGM.VoidPtrPtrTy,
2292  CGM.SizeTy->getPointerTo(),
2293  CGM.Int64Ty->getPointerTo()};
2294  auto *FnTy =
2295  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2296  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2297  break;
2298  }
2300  // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2301  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2302  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2303  CGM.Int32Ty,
2304  CGM.VoidPtrPtrTy,
2305  CGM.VoidPtrPtrTy,
2306  CGM.SizeTy->getPointerTo(),
2307  CGM.Int64Ty->getPointerTo()};
2308  auto *FnTy =
2309  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2310  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2311  break;
2312  }
2314  // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2315  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2316  // *arg_types);
2317  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2318  CGM.Int32Ty,
2319  CGM.VoidPtrPtrTy,
2320  CGM.VoidPtrPtrTy,
2321  CGM.SizeTy->getPointerTo(),
2322  CGM.Int64Ty->getPointerTo()};
2323  auto *FnTy =
2324  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2325  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2326  break;
2327  }
2328  }
2329  assert(RTLFn && "Unable to find OpenMP runtime function");
2330  return RTLFn;
2331 }
2332 
2333 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2334  bool IVSigned) {
2335  assert((IVSize == 32 || IVSize == 64) &&
2336  "IV size is not compatible with the omp runtime");
2337  StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2338  : "__kmpc_for_static_init_4u")
2339  : (IVSigned ? "__kmpc_for_static_init_8"
2340  : "__kmpc_for_static_init_8u");
2341  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2342  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2343  llvm::Type *TypeParams[] = {
2344  getIdentTyPointerTy(), // loc
2345  CGM.Int32Ty, // tid
2346  CGM.Int32Ty, // schedtype
2347  llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2348  PtrTy, // p_lower
2349  PtrTy, // p_upper
2350  PtrTy, // p_stride
2351  ITy, // incr
2352  ITy // chunk
2353  };
2354  auto *FnTy =
2355  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2356  return CGM.CreateRuntimeFunction(FnTy, Name);
2357 }
2358 
2359 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2360  bool IVSigned) {
2361  assert((IVSize == 32 || IVSize == 64) &&
2362  "IV size is not compatible with the omp runtime");
2363  StringRef Name =
2364  IVSize == 32
2365  ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2366  : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2367  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2368  llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2369  CGM.Int32Ty, // tid
2370  CGM.Int32Ty, // schedtype
2371  ITy, // lower
2372  ITy, // upper
2373  ITy, // stride
2374  ITy // chunk
2375  };
2376  auto *FnTy =
2377  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2378  return CGM.CreateRuntimeFunction(FnTy, Name);
2379 }
2380 
2381 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2382  bool IVSigned) {
2383  assert((IVSize == 32 || IVSize == 64) &&
2384  "IV size is not compatible with the omp runtime");
2385  StringRef Name =
2386  IVSize == 32
2387  ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2388  : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2389  llvm::Type *TypeParams[] = {
2390  getIdentTyPointerTy(), // loc
2391  CGM.Int32Ty, // tid
2392  };
2393  auto *FnTy =
2394  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2395  return CGM.CreateRuntimeFunction(FnTy, Name);
2396 }
2397 
2398 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2399  bool IVSigned) {
2400  assert((IVSize == 32 || IVSize == 64) &&
2401  "IV size is not compatible with the omp runtime");
2402  StringRef Name =
2403  IVSize == 32
2404  ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2405  : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2406  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2407  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2408  llvm::Type *TypeParams[] = {
2409  getIdentTyPointerTy(), // loc
2410  CGM.Int32Ty, // tid
2411  llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2412  PtrTy, // p_lower
2413  PtrTy, // p_upper
2414  PtrTy // p_stride
2415  };
2416  auto *FnTy =
2417  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2418  return CGM.CreateRuntimeFunction(FnTy, Name);
2419 }
2420 
2422  if (CGM.getLangOpts().OpenMPSimd)
2423  return Address::invalid();
2425  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2426  if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2427  SmallString<64> PtrName;
2428  {
2429  llvm::raw_svector_ostream OS(PtrName);
2430  OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2431  }
2432  llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2433  if (!Ptr) {
2434  QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2436  PtrName);
2437  if (!CGM.getLangOpts().OpenMPIsDevice) {
2438  auto *GV = cast<llvm::GlobalVariable>(Ptr);
2439  GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2440  GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2441  }
2442  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2443  registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
2444  }
2445  return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2446  }
2447  return Address::invalid();
2448 }
2449 
2450 llvm::Constant *
2452  assert(!CGM.getLangOpts().OpenMPUseTLS ||
2454  // Lookup the entry, lazily creating it if necessary.
2455  std::string Suffix = getName({"cache", ""});
2457  CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
2458 }
2459 
2461  const VarDecl *VD,
2462  Address VDAddr,
2463  SourceLocation Loc) {
2464  if (CGM.getLangOpts().OpenMPUseTLS &&
2466  return VDAddr;
2467 
2468  llvm::Type *VarTy = VDAddr.getElementType();
2469  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2470  CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2471  CGM.Int8PtrTy),
2474  return Address(CGF.EmitRuntimeCall(
2476  VDAddr.getAlignment());
2477 }
2478 
2480  CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
2481  llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2482  // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2483  // library.
2484  llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
2486  OMPLoc);
2487  // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2488  // to register constructor/destructor for variable.
2489  llvm::Value *Args[] = {
2490  OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2491  Ctor, CopyCtor, Dtor};
2492  CGF.EmitRuntimeCall(
2494 }
2495 
2497  const VarDecl *VD, Address VDAddr, SourceLocation Loc,
2498  bool PerformInit, CodeGenFunction *CGF) {
2499  if (CGM.getLangOpts().OpenMPUseTLS &&
2501  return nullptr;
2502 
2503  VD = VD->getDefinition(CGM.getContext());
2504  if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2505  ThreadPrivateWithDefinition.insert(VD);
2506  QualType ASTTy = VD->getType();
2507 
2508  llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2509  const Expr *Init = VD->getAnyInitializer();
2510  if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2511  // Generate function that re-emits the declaration's initializer into the
2512  // threadprivate copy of the variable VD
2513  CodeGenFunction CtorCGF(CGM);
2514  FunctionArgList Args;
2515  ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2516  /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2518  Args.push_back(&Dst);
2519 
2520  const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2521  CGM.getContext().VoidPtrTy, Args);
2522  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2523  std::string Name = getName({"__kmpc_global_ctor_", ""});
2524  llvm::Function *Fn =
2525  CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2526  CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2527  Args, Loc, Loc);
2528  llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
2529  CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2530  CGM.getContext().VoidPtrTy, Dst.getLocation());
2531  Address Arg = Address(ArgVal, VDAddr.getAlignment());
2532  Arg = CtorCGF.Builder.CreateElementBitCast(
2533  Arg, CtorCGF.ConvertTypeForMem(ASTTy));
2534  CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2535  /*IsInitializer=*/true);
2536  ArgVal = CtorCGF.EmitLoadOfScalar(
2537  CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2538  CGM.getContext().VoidPtrTy, Dst.getLocation());
2539  CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2540  CtorCGF.FinishFunction();
2541  Ctor = Fn;
2542  }
2543  if (VD->getType().isDestructedType() != QualType::DK_none) {
2544  // Generate function that emits destructor call for the threadprivate copy
2545  // of the variable VD
2546  CodeGenFunction DtorCGF(CGM);
2547  FunctionArgList Args;
2548  ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2549  /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2551  Args.push_back(&Dst);
2552 
2553  const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2554  CGM.getContext().VoidTy, Args);
2555  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2556  std::string Name = getName({"__kmpc_global_dtor_", ""});
2557  llvm::Function *Fn =
2558  CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2559  auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2560  DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2561  Loc, Loc);
2562  // Create a scope with an artificial location for the body of this function.
2563  auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2564  llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
2565  DtorCGF.GetAddrOfLocalVar(&Dst),
2566  /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2567  DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
2568  DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2569  DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2570  DtorCGF.FinishFunction();
2571  Dtor = Fn;
2572  }
2573  // Do not emit init function if it is not required.
2574  if (!Ctor && !Dtor)
2575  return nullptr;
2576 
2577  llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2578  auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2579  /*isVarArg=*/false)
2580  ->getPointerTo();
2581  // Copying constructor for the threadprivate variable.
2582  // Must be NULL - reserved by runtime, but currently it requires that this
2583  // parameter is always NULL. Otherwise it fires assertion.
2584  CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2585  if (Ctor == nullptr) {
2586  auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2587  /*isVarArg=*/false)
2588  ->getPointerTo();
2589  Ctor = llvm::Constant::getNullValue(CtorTy);
2590  }
2591  if (Dtor == nullptr) {
2592  auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2593  /*isVarArg=*/false)
2594  ->getPointerTo();
2595  Dtor = llvm::Constant::getNullValue(DtorTy);
2596  }
2597  if (!CGF) {
2598  auto *InitFunctionTy =
2599  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2600  std::string Name = getName({"__omp_threadprivate_init_", ""});
2601  llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
2602  InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
2603  CodeGenFunction InitCGF(CGM);
2604  FunctionArgList ArgList;
2605  InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2606  CGM.getTypes().arrangeNullaryFunction(), ArgList,
2607  Loc, Loc);
2608  emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2609  InitCGF.FinishFunction();
2610  return InitFunction;
2611  }
2612  emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2613  }
2614  return nullptr;
2615 }
2616 
2617 /// Obtain information that uniquely identifies a target entry. This
2618 /// consists of the file and device IDs as well as line number associated with
2619 /// the relevant entry source location.
2621  unsigned &DeviceID, unsigned &FileID,
2622  unsigned &LineNum) {
2624 
2625  // The loc should be always valid and have a file ID (the user cannot use
2626  // #pragma directives in macros)
2627 
2628  assert(Loc.isValid() && "Source location is expected to be always valid.");
2629 
2630  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2631  assert(PLoc.isValid() && "Source location is expected to be always valid.");
2632 
2633  llvm::sys::fs::UniqueID ID;
2634  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2635  SM.getDiagnostics().Report(diag::err_cannot_open_file)
2636  << PLoc.getFilename() << EC.message();
2637 
2638  DeviceID = ID.getDevice();
2639  FileID = ID.getFile();
2640  LineNum = PLoc.getLine();
2641 }
2642 
2644  llvm::GlobalVariable *Addr,
2645  bool PerformInit) {
2647  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2648  if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2649  return CGM.getLangOpts().OpenMPIsDevice;
2650  VD = VD->getDefinition(CGM.getContext());
2651  if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2652  return CGM.getLangOpts().OpenMPIsDevice;
2653 
2654  QualType ASTTy = VD->getType();
2655 
2657  // Produce the unique prefix to identify the new target regions. We use
2658  // the source location of the variable declaration which we know to not
2659  // conflict with any target region.
2660  unsigned DeviceID;
2661  unsigned FileID;
2662  unsigned Line;
2663  getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2664  SmallString<128> Buffer, Out;
2665  {
2666  llvm::raw_svector_ostream OS(Buffer);
2667  OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2668  << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2669  }
2670 
2671  const Expr *Init = VD->getAnyInitializer();
2672  if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2673  llvm::Constant *Ctor;
2674  llvm::Constant *ID;
2675  if (CGM.getLangOpts().OpenMPIsDevice) {
2676  // Generate function that re-emits the declaration's initializer into
2677  // the threadprivate copy of the variable VD
2678  CodeGenFunction CtorCGF(CGM);
2679 
2681  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2682  llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2683  FTy, Twine(Buffer, "_ctor"), FI, Loc);
2684  auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2685  CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2686  FunctionArgList(), Loc, Loc);
2687  auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2688  CtorCGF.EmitAnyExprToMem(Init,
2689  Address(Addr, CGM.getContext().getDeclAlign(VD)),
2690  Init->getType().getQualifiers(),
2691  /*IsInitializer=*/true);
2692  CtorCGF.FinishFunction();
2693  Ctor = Fn;
2694  ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2695  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
2696  } else {
2697  Ctor = new llvm::GlobalVariable(
2698  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2699  llvm::GlobalValue::PrivateLinkage,
2700  llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2701  ID = Ctor;
2702  }
2703 
2704  // Register the information for the entry associated with the constructor.
2705  Out.clear();
2707  DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
2709  }
2710  if (VD->getType().isDestructedType() != QualType::DK_none) {
2711  llvm::Constant *Dtor;
2712  llvm::Constant *ID;
2713  if (CGM.getLangOpts().OpenMPIsDevice) {
2714  // Generate function that emits destructor call for the threadprivate
2715  // copy of the variable VD
2716  CodeGenFunction DtorCGF(CGM);
2717 
2719  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2720  llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2721  FTy, Twine(Buffer, "_dtor"), FI, Loc);
2722  auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2723  DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2724  FunctionArgList(), Loc, Loc);
2725  // Create a scope with an artificial location for the body of this
2726  // function.
2727  auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2728  DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2729  ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2730  DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2731  DtorCGF.FinishFunction();
2732  Dtor = Fn;
2733  ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2734  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
2735  } else {
2736  Dtor = new llvm::GlobalVariable(
2737  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2738  llvm::GlobalValue::PrivateLinkage,
2739  llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2740  ID = Dtor;
2741  }
2742  // Register the information for the entry associated with the destructor.
2743  Out.clear();
2745  DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
2747  }
2748  return CGM.getLangOpts().OpenMPIsDevice;
2749 }
2750 
2752  QualType VarType,
2753  StringRef Name) {
2754  std::string Suffix = getName({"artificial", ""});
2755  std::string CacheSuffix = getName({"cache", ""});
2756  llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2757  llvm::Value *GAddr =
2758  getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
2759  llvm::Value *Args[] = {
2761  getThreadID(CGF, SourceLocation()),
2763  CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2764  /*IsSigned=*/false),
2766  CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
2767  return Address(
2769  CGF.EmitRuntimeCall(
2771  VarLVType->getPointerTo(/*AddrSpace=*/0)),
2772  CGM.getPointerAlign());
2773 }
2774 
2776  const RegionCodeGenTy &ThenGen,
2777  const RegionCodeGenTy &ElseGen) {
2778  CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2779 
2780  // If the condition constant folds and can be elided, try to avoid emitting
2781  // the condition and the dead arm of the if/else.
2782  bool CondConstant;
2783  if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2784  if (CondConstant)
2785  ThenGen(CGF);
2786  else
2787  ElseGen(CGF);
2788  return;
2789  }
2790 
2791  // Otherwise, the condition did not fold, or we couldn't elide it. Just
2792  // emit the conditional branch.
2793  llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2794  llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2795  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
2796  CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2797 
2798  // Emit the 'then' code.
2799  CGF.EmitBlock(ThenBlock);
2800  ThenGen(CGF);
2801  CGF.EmitBranch(ContBlock);
2802  // Emit the 'else' code if present.
2803  // There is no need to emit line number for unconditional branch.
2805  CGF.EmitBlock(ElseBlock);
2806  ElseGen(CGF);
2807  // There is no need to emit line number for unconditional branch.
2809  CGF.EmitBranch(ContBlock);
2810  // Emit the continuation block for code after the if.
2811  CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2812 }
2813 
2815  llvm::Value *OutlinedFn,
2816  ArrayRef<llvm::Value *> CapturedVars,
2817  const Expr *IfCond) {
2818  if (!CGF.HaveInsertPoint())
2819  return;
2820  llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2821  auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2822  PrePostActionTy &) {
2823  // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2824  CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2825  llvm::Value *Args[] = {
2826  RTLoc,
2827  CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2828  CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2830  RealArgs.append(std::begin(Args), std::end(Args));
2831  RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2832 
2833  llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
2834  CGF.EmitRuntimeCall(RTLFn, RealArgs);
2835  };
2836  auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2837  PrePostActionTy &) {
2838  CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2839  llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
2840  // Build calls:
2841  // __kmpc_serialized_parallel(&Loc, GTid);
2842  llvm::Value *Args[] = {RTLoc, ThreadID};
2843  CGF.EmitRuntimeCall(
2844  RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
2845 
2846  // OutlinedFn(&GTid, &zero, CapturedStruct);
2847  Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2848  /*Name*/ ".zero.addr");
2849  CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2850  llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2851  // ThreadId for serialized parallels is 0.
2852  OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2853  OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2854  OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2855  RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2856 
2857  // __kmpc_end_serialized_parallel(&Loc, GTid);
2858  llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2859  CGF.EmitRuntimeCall(
2860  RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2861  EndArgs);
2862  };
2863  if (IfCond) {
2864  emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2865  } else {
2866  RegionCodeGenTy ThenRCG(ThenGen);
2867  ThenRCG(CGF);
2868  }
2869 }
2870 
2871 // If we're inside an (outlined) parallel region, use the region info's
2872 // thread-ID variable (it is passed in a first argument of the outlined function
2873 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2874 // regular serial code region, get thread ID by calling kmp_int32
2875 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2876 // return the address of that temp.
2878  SourceLocation Loc) {
2879  if (auto *OMPRegionInfo =
2880  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2881  if (OMPRegionInfo->getThreadIDVariable())
2882  return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2883 
2884  llvm::Value *ThreadID = getThreadID(CGF, Loc);
2885  QualType Int32Ty =
2886  CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2887  Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2888  CGF.EmitStoreOfScalar(ThreadID,
2889  CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2890 
2891  return ThreadIDTemp;
2892 }
2893 
2894 llvm::Constant *
2896  const llvm::Twine &Name) {
2897  SmallString<256> Buffer;
2898  llvm::raw_svector_ostream Out(Buffer);
2899  Out << Name;
2900  StringRef RuntimeName = Out.str();
2901  auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
2902  if (Elem.second) {
2903  assert(Elem.second->getType()->getPointerElementType() == Ty &&
2904  "OMP internal variable has different type than requested");
2905  return &*Elem.second;
2906  }
2907 
2908  return Elem.second = new llvm::GlobalVariable(
2909  CGM.getModule(), Ty, /*IsConstant*/ false,
2910  llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2911  Elem.first());
2912 }
2913 
2915  std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2916  std::string Name = getName({Prefix, "var"});
2917  return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2918 }
2919 
2920 namespace {
2921 /// Common pre(post)-action for different OpenMP constructs.
2922 class CommonActionTy final : public PrePostActionTy {
2923  llvm::Value *EnterCallee;
2924  ArrayRef<llvm::Value *> EnterArgs;
2925  llvm::Value *ExitCallee;
2926  ArrayRef<llvm::Value *> ExitArgs;
2927  bool Conditional;
2928  llvm::BasicBlock *ContBlock = nullptr;
2929 
2930 public:
2931  CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2932  llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2933  bool Conditional = false)
2934  : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2935  ExitArgs(ExitArgs), Conditional(Conditional) {}
2936  void Enter(CodeGenFunction &CGF) override {
2937  llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2938  if (Conditional) {
2939  llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2940  auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2941  ContBlock = CGF.createBasicBlock("omp_if.end");
2942  // Generate the branch (If-stmt)
2943  CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2944  CGF.EmitBlock(ThenBlock);
2945  }
2946  }
2947  void Done(CodeGenFunction &CGF) {
2948  // Emit the rest of blocks/branches
2949  CGF.EmitBranch(ContBlock);
2950  CGF.EmitBlock(ContBlock, true);
2951  }
2952  void Exit(CodeGenFunction &CGF) override {
2953  CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2954  }
2955 };
2956 } // anonymous namespace
2957 
2959  StringRef CriticalName,
2960  const RegionCodeGenTy &CriticalOpGen,
2961  SourceLocation Loc, const Expr *Hint) {
2962  // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2963  // CriticalOpGen();
2964  // __kmpc_end_critical(ident_t *, gtid, Lock);
2965  // Prepare arguments and build a call to __kmpc_critical
2966  if (!CGF.HaveInsertPoint())
2967  return;
2968  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2969  getCriticalRegionLock(CriticalName)};
2970  llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2971  std::end(Args));
2972  if (Hint) {
2973  EnterArgs.push_back(CGF.Builder.CreateIntCast(
2974  CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2975  }
2976  CommonActionTy Action(
2980  CriticalOpGen.setAction(Action);
2981  emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2982 }
2983 
2985  const RegionCodeGenTy &MasterOpGen,
2986  SourceLocation Loc) {
2987  if (!CGF.HaveInsertPoint())
2988  return;
2989  // if(__kmpc_master(ident_t *, gtid)) {
2990  // MasterOpGen();
2991  // __kmpc_end_master(ident_t *, gtid);
2992  // }
2993  // Prepare arguments and build a call to __kmpc_master
2994  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2995  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2997  /*Conditional=*/true);
2998  MasterOpGen.setAction(Action);
2999  emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3000  Action.Done(CGF);
3001 }
3002 
3004  SourceLocation Loc) {
3005  if (!CGF.HaveInsertPoint())
3006  return;
3007  // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3008  llvm::Value *Args[] = {
3009  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3010  llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
3012  if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3013  Region->emitUntiedSwitch(CGF);
3014 }
3015 
3017  const RegionCodeGenTy &TaskgroupOpGen,
3018  SourceLocation Loc) {
3019  if (!CGF.HaveInsertPoint())
3020  return;
3021  // __kmpc_taskgroup(ident_t *, gtid);
3022  // TaskgroupOpGen();
3023  // __kmpc_end_taskgroup(ident_t *, gtid);
3024  // Prepare arguments and build a call to __kmpc_taskgroup
3025  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3026  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3028  Args);
3029  TaskgroupOpGen.setAction(Action);
3030  emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
3031 }
3032 
3033 /// Given an array of pointers to variables, project the address of a
3034 /// given variable.
3036  unsigned Index, const VarDecl *Var) {
3037  // Pull out the pointer to the variable.
3038  Address PtrAddr =
3039  CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
3040  llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3041 
3042  Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
3043  Addr = CGF.Builder.CreateElementBitCast(
3044  Addr, CGF.ConvertTypeForMem(Var->getType()));
3045  return Addr;
3046 }
3047 
3049  CodeGenModule &CGM, llvm::Type *ArgsType,
3050  ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
3051  ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3052  SourceLocation Loc) {
3053  ASTContext &C = CGM.getContext();
3054  // void copy_func(void *LHSArg, void *RHSArg);
3055  FunctionArgList Args;
3056  ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3058  ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3060  Args.push_back(&LHSArg);
3061  Args.push_back(&RHSArg);
3062  const auto &CGFI =
3064  std::string Name =
3065  CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3066  auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3068  &CGM.getModule());
3069  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3070  Fn->setDoesNotRecurse();
3071  CodeGenFunction CGF(CGM);
3072  CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3073  // Dest = (void*[n])(LHSArg);
3074  // Src = (void*[n])(RHSArg);
3076  CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3077  ArgsType), CGF.getPointerAlign());
3079  CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3080  ArgsType), CGF.getPointerAlign());
3081  // *(Type0*)Dst[0] = *(Type0*)Src[0];
3082  // *(Type1*)Dst[1] = *(Type1*)Src[1];
3083  // ...
3084  // *(Typen*)Dst[n] = *(Typen*)Src[n];
3085  for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
3086  const auto *DestVar =
3087  cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
3088  Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3089 
3090  const auto *SrcVar =
3091  cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
3092  Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3093 
3094  const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
3095  QualType Type = VD->getType();
3096  CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
3097  }
3098  CGF.FinishFunction();
3099  return Fn;
3100 }
3101 
3103  const RegionCodeGenTy &SingleOpGen,
3104  SourceLocation Loc,
3105  ArrayRef<const Expr *> CopyprivateVars,
3106  ArrayRef<const Expr *> SrcExprs,
3107  ArrayRef<const Expr *> DstExprs,
3108  ArrayRef<const Expr *> AssignmentOps) {
3109  if (!CGF.HaveInsertPoint())
3110  return;
3111  assert(CopyprivateVars.size() == SrcExprs.size() &&
3112  CopyprivateVars.size() == DstExprs.size() &&
3113  CopyprivateVars.size() == AssignmentOps.size());
3114  ASTContext &C = CGM.getContext();
3115  // int32 did_it = 0;
3116  // if(__kmpc_single(ident_t *, gtid)) {
3117  // SingleOpGen();
3118  // __kmpc_end_single(ident_t *, gtid);
3119  // did_it = 1;
3120  // }
3121  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3122  // <copy_func>, did_it);
3123 
3124  Address DidIt = Address::invalid();
3125  if (!CopyprivateVars.empty()) {
3126  // int32 did_it = 0;
3127  QualType KmpInt32Ty =
3128  C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3129  DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
3130  CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
3131  }
3132  // Prepare arguments and build a call to __kmpc_single
3133  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3134  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3136  /*Conditional=*/true);
3137  SingleOpGen.setAction(Action);
3138  emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3139  if (DidIt.isValid()) {
3140  // did_it = 1;
3141  CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3142  }
3143  Action.Done(CGF);
3144  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3145  // <copy_func>, did_it);
3146  if (DidIt.isValid()) {
3147  llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
3148  QualType CopyprivateArrayTy =
3149  C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3150  /*IndexTypeQuals=*/0);
3151  // Create a list of all private variables for copyprivate.
3152  Address CopyprivateList =
3153  CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3154  for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
3155  Address Elem = CGF.Builder.CreateConstArrayGEP(
3156  CopyprivateList, I, CGF.getPointerSize());
3157  CGF.Builder.CreateStore(
3159  CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3160  Elem);
3161  }
3162  // Build function that copies private values from single region to all other
3163  // threads in the corresponding parallel region.
3165  CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
3166  CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
3167  llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
3168  Address CL =
3169  CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3170  CGF.VoidPtrTy);
3171  llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
3172  llvm::Value *Args[] = {
3173  emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3174  getThreadID(CGF, Loc), // i32 <gtid>
3175  BufSize, // size_t <buf_size>
3176  CL.getPointer(), // void *<copyprivate list>
3177  CpyFn, // void (*) (void *, void *) <copy_func>
3178  DidItVal // i32 did_it
3179  };
3181  }
3182 }
3183 
3185  const RegionCodeGenTy &OrderedOpGen,
3186  SourceLocation Loc, bool IsThreads) {
3187  if (!CGF.HaveInsertPoint())
3188  return;
3189  // __kmpc_ordered(ident_t *, gtid);
3190  // OrderedOpGen();
3191  // __kmpc_end_ordered(ident_t *, gtid);
3192  // Prepare arguments and build a call to __kmpc_ordered
3193  if (IsThreads) {
3194  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3195  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3197  Args);
3198  OrderedOpGen.setAction(Action);
3199  emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3200  return;
3201  }
3202  emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3203 }
3204 
3206  OpenMPDirectiveKind Kind, bool EmitChecks,
3207  bool ForceSimpleCall) {
3208  if (!CGF.HaveInsertPoint())
3209  return;
3210  // Build call __kmpc_cancel_barrier(loc, thread_id);
3211  // Build call __kmpc_barrier(loc, thread_id);
3212  unsigned Flags;
3213  if (Kind == OMPD_for)
3214  Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3215  else if (Kind == OMPD_sections)
3216  Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3217  else if (Kind == OMPD_single)
3218  Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3219  else if (Kind == OMPD_barrier)
3220  Flags = OMP_IDENT_BARRIER_EXPL;
3221  else
3222  Flags = OMP_IDENT_BARRIER_IMPL;
3223  // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3224  // thread_id);
3225  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3226  getThreadID(CGF, Loc)};
3227  if (auto *OMPRegionInfo =
3228  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
3229  if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
3230  llvm::Value *Result = CGF.EmitRuntimeCall(
3232  if (EmitChecks) {
3233  // if (__kmpc_cancel_barrier()) {
3234  // exit from construct;
3235  // }
3236  llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3237  llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3238  llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
3239  CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3240  CGF.EmitBlock(ExitBB);
3241  // exit from construct;
3242  CodeGenFunction::JumpDest CancelDestination =
3243  CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3244  CGF.EmitBranchThroughCleanup(CancelDestination);
3245  CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3246  }
3247  return;
3248  }
3249  }
3251 }
3252 
3253 /// Map the OpenMP loop schedule to the runtime enumeration.
3255  bool Chunked, bool Ordered) {
3256  switch (ScheduleKind) {
3257  case OMPC_SCHEDULE_static:
3258  return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3259  : (Ordered ? OMP_ord_static : OMP_sch_static);
3260  case OMPC_SCHEDULE_dynamic:
3262  case OMPC_SCHEDULE_guided:
3264  case OMPC_SCHEDULE_runtime:
3265  return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3266  case OMPC_SCHEDULE_auto:
3267  return Ordered ? OMP_ord_auto : OMP_sch_auto;
3268  case OMPC_SCHEDULE_unknown:
3269  assert(!Chunked && "chunk was specified but schedule kind not known");
3270  return Ordered ? OMP_ord_static : OMP_sch_static;
3271  }
3272  llvm_unreachable("Unexpected runtime schedule");
3273 }
3274 
3275 /// Map the OpenMP distribute schedule to the runtime enumeration.
3276 static OpenMPSchedType
3278  // only static is allowed for dist_schedule
3280 }
3281 
3283  bool Chunked) const {
3284  OpenMPSchedType Schedule =
3285  getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3286  return Schedule == OMP_sch_static;
3287 }
3288 
3290  OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3291  OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3292  return Schedule == OMP_dist_sch_static;
3293 }
3294 
3295 
3297  OpenMPSchedType Schedule =
3298  getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
3299  assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3300  return Schedule != OMP_sch_static;
3301 }
3302 
3306  int Modifier = 0;
3307  switch (M1) {
3308  case OMPC_SCHEDULE_MODIFIER_monotonic:
3309  Modifier = OMP_sch_modifier_monotonic;
3310  break;
3311  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3312  Modifier = OMP_sch_modifier_nonmonotonic;
3313  break;
3314  case OMPC_SCHEDULE_MODIFIER_simd:
3315  if (Schedule == OMP_sch_static_chunked)
3317  break;
3320  break;
3321  }
3322  switch (M2) {
3323  case OMPC_SCHEDULE_MODIFIER_monotonic:
3324  Modifier = OMP_sch_modifier_monotonic;
3325  break;
3326  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3327  Modifier = OMP_sch_modifier_nonmonotonic;
3328  break;
3329  case OMPC_SCHEDULE_MODIFIER_simd:
3330  if (Schedule == OMP_sch_static_chunked)
3332  break;
3335  break;
3336  }
3337  return Schedule | Modifier;
3338 }
3339 
3341  CodeGenFunction &CGF, SourceLocation Loc,
3342  const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3343  bool Ordered, const DispatchRTInput &DispatchValues) {
3344  if (!CGF.HaveInsertPoint())
3345  return;
3347  ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
3348  assert(Ordered ||
3349  (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
3350  Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3351  Schedule != OMP_sch_static_balanced_chunked));
3352  // Call __kmpc_dispatch_init(
3353  // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3354  // kmp_int[32|64] lower, kmp_int[32|64] upper,
3355  // kmp_int[32|64] stride, kmp_int[32|64] chunk);
3356 
3357  // If the Chunk was not specified in the clause - use default value 1.
3358  llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3359  : CGF.Builder.getIntN(IVSize, 1);
3360  llvm::Value *Args[] = {
3361  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3362  CGF.Builder.getInt32(addMonoNonMonoModifier(
3363  Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
3364  DispatchValues.LB, // Lower
3365  DispatchValues.UB, // Upper
3366  CGF.Builder.getIntN(IVSize, 1), // Stride
3367  Chunk // Chunk
3368  };
3369  CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3370 }
3371 
3373  CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3374  llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3376  const CGOpenMPRuntime::StaticRTInput &Values) {
3377  if (!CGF.HaveInsertPoint())
3378  return;
3379 
3380  assert(!Values.Ordered);
3381  assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3382  Schedule == OMP_sch_static_balanced_chunked ||
3383  Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3384  Schedule == OMP_dist_sch_static ||
3385  Schedule == OMP_dist_sch_static_chunked);
3386 
3387  // Call __kmpc_for_static_init(
3388  // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3389  // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3390  // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3391  // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3392  llvm::Value *Chunk = Values.Chunk;
3393  if (Chunk == nullptr) {
3394  assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3395  Schedule == OMP_dist_sch_static) &&
3396  "expected static non-chunked schedule");
3397  // If the Chunk was not specified in the clause - use default value 1.
3398  Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3399  } else {
3400  assert((Schedule == OMP_sch_static_chunked ||
3401  Schedule == OMP_sch_static_balanced_chunked ||
3402  Schedule == OMP_ord_static_chunked ||
3403  Schedule == OMP_dist_sch_static_chunked) &&
3404  "expected static chunked schedule");
3405  }
3406  llvm::Value *Args[] = {
3407  UpdateLocation,
3408  ThreadId,
3409  CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3410  M2)), // Schedule type
3411  Values.IL.getPointer(), // &isLastIter
3412  Values.LB.getPointer(), // &LB
3413  Values.UB.getPointer(), // &UB
3414  Values.ST.getPointer(), // &Stride
3415  CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3416  Chunk // Chunk
3417  };
3418  CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3419 }
3420 
3422  SourceLocation Loc,
3423  OpenMPDirectiveKind DKind,
3424  const OpenMPScheduleTy &ScheduleKind,
3425  const StaticRTInput &Values) {
3426  OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3427  ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3428  assert(isOpenMPWorksharingDirective(DKind) &&
3429  "Expected loop-based or sections-based directive.");
3430  llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3431  isOpenMPLoopDirective(DKind)
3432  ? OMP_IDENT_WORK_LOOP
3433  : OMP_IDENT_WORK_SECTIONS);
3434  llvm::Value *ThreadId = getThreadID(CGF, Loc);
3435  llvm::Constant *StaticInitFunction =
3437  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3438  ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
3439 }
3440 
3442  CodeGenFunction &CGF, SourceLocation Loc,
3443  OpenMPDistScheduleClauseKind SchedKind,
3444  const CGOpenMPRuntime::StaticRTInput &Values) {
3445  OpenMPSchedType ScheduleNum =
3446  getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3447  llvm::Value *UpdatedLocation =
3448  emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
3449  llvm::Value *ThreadId = getThreadID(CGF, Loc);
3450  llvm::Constant *StaticInitFunction =
3451  createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3452  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3453  ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3455 }
3456 
3458  SourceLocation Loc,
3459  OpenMPDirectiveKind DKind) {
3460  if (!CGF.HaveInsertPoint())
3461  return;
3462  // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
3463  llvm::Value *Args[] = {
3464  emitUpdateLocation(CGF, Loc,
3466  ? OMP_IDENT_WORK_DISTRIBUTE
3467  : isOpenMPLoopDirective(DKind)
3468  ? OMP_IDENT_WORK_LOOP
3469  : OMP_IDENT_WORK_SECTIONS),
3470  getThreadID(CGF, Loc)};
3472  Args);
3473 }
3474 
3476  SourceLocation Loc,
3477  unsigned IVSize,
3478  bool IVSigned) {
3479  if (!CGF.HaveInsertPoint())
3480  return;
3481  // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
3482  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3483  CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3484 }
3485 
3487  SourceLocation Loc, unsigned IVSize,
3488  bool IVSigned, Address IL,
3489  Address LB, Address UB,
3490  Address ST) {
3491  // Call __kmpc_dispatch_next(
3492  // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3493  // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3494  // kmp_int[32|64] *p_stride);
3495  llvm::Value *Args[] = {
3496  emitUpdateLocation(CGF, Loc),
3497  getThreadID(CGF, Loc),
3498  IL.getPointer(), // &isLastIter
3499  LB.getPointer(), // &Lower
3500  UB.getPointer(), // &Upper
3501  ST.getPointer() // &Stride
3502  };
3503  llvm::Value *Call =
3504  CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3505  return CGF.EmitScalarConversion(
3506  Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
3507  CGF.getContext().BoolTy, Loc);
3508 }
3509 
3511  llvm::Value *NumThreads,
3512  SourceLocation Loc) {
3513  if (!CGF.HaveInsertPoint())
3514  return;
3515  // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3516  llvm::Value *Args[] = {
3517  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3518  CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
3520  Args);
3521 }
3522 
3524  OpenMPProcBindClauseKind ProcBind,
3525  SourceLocation Loc) {
3526  if (!CGF.HaveInsertPoint())
3527  return;
3528  // Constants for proc bind value accepted by the runtime.
3529  enum ProcBindTy {
3530  ProcBindFalse = 0,
3531  ProcBindTrue,
3532  ProcBindMaster,
3533  ProcBindClose,
3534  ProcBindSpread,
3535  ProcBindIntel,
3536  ProcBindDefault
3537  } RuntimeProcBind;
3538  switch (ProcBind) {
3539  case OMPC_PROC_BIND_master:
3540  RuntimeProcBind = ProcBindMaster;
3541  break;
3542  case OMPC_PROC_BIND_close:
3543  RuntimeProcBind = ProcBindClose;
3544  break;
3545  case OMPC_PROC_BIND_spread:
3546  RuntimeProcBind = ProcBindSpread;
3547  break;
3549  llvm_unreachable("Unsupported proc_bind value.");
3550  }
3551  // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3552  llvm::Value *Args[] = {
3553  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3554  llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3556 }
3557 
3558 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3559  SourceLocation Loc) {
3560  if (!CGF.HaveInsertPoint())
3561  return;
3562  // Build call void __kmpc_flush(ident_t *loc)
3564  emitUpdateLocation(CGF, Loc));
3565 }
3566 
3567 namespace {
3568 /// Indexes of fields for type kmp_task_t.
3570  /// List of shared variables.
3571  KmpTaskTShareds,
3572  /// Task routine.
3573  KmpTaskTRoutine,
3574  /// Partition id for the untied tasks.
3575  KmpTaskTPartId,
3576  /// Function with call of destructors for private variables.
3577  Data1,
3578  /// Task priority.
3579  Data2,
3580  /// (Taskloops only) Lower bound.
3581  KmpTaskTLowerBound,
3582  /// (Taskloops only) Upper bound.
3583  KmpTaskTUpperBound,
3584  /// (Taskloops only) Stride.
3585  KmpTaskTStride,
3586  /// (Taskloops only) Is last iteration flag.
3587  KmpTaskTLastIter,
3588  /// (Taskloops only) Reduction data.
3589  KmpTaskTReductions,
3590 };
3591 } // anonymous namespace
3592 
3593 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3594  return OffloadEntriesTargetRegion.empty() &&
3595  OffloadEntriesDeviceGlobalVar.empty();
3596 }
3597 
3598 /// Initialize target region entry.
3599 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3600  initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3601  StringRef ParentName, unsigned LineNum,
3602  unsigned Order) {
3603  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3604  "only required for the device "
3605  "code generation.");
3606  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
3607  OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3608  OMPTargetRegionEntryTargetRegion);
3609  ++OffloadingEntriesNum;
3610 }
3611 
3612 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3613  registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3614  StringRef ParentName, unsigned LineNum,
3615  llvm::Constant *Addr, llvm::Constant *ID,
3616  OMPTargetRegionEntryKind Flags) {
3617  // If we are emitting code for a target, the entry is already initialized,
3618  // only has to be registered.
3619  if (CGM.getLangOpts().OpenMPIsDevice) {
3620  if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3621  unsigned DiagID = CGM.getDiags().getCustomDiagID(
3623  "Unable to find target region on line '%0' in the device code.");
3624  CGM.getDiags().Report(DiagID) << LineNum;
3625  return;
3626  }
3627  auto &Entry =
3628  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3629  assert(Entry.isValid() && "Entry not initialized!");
3630  Entry.setAddress(Addr);
3631  Entry.setID(ID);
3632  Entry.setFlags(Flags);
3633  } else {
3634  OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
3635  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3636  ++OffloadingEntriesNum;
3637  }
3638 }
3639 
3640 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3641  unsigned DeviceID, unsigned FileID, StringRef ParentName,
3642  unsigned LineNum) const {
3643  auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3644  if (PerDevice == OffloadEntriesTargetRegion.end())
3645  return false;
3646  auto PerFile = PerDevice->second.find(FileID);
3647  if (PerFile == PerDevice->second.end())
3648  return false;
3649  auto PerParentName = PerFile->second.find(ParentName);
3650  if (PerParentName == PerFile->second.end())
3651  return false;
3652  auto PerLine = PerParentName->second.find(LineNum);
3653  if (PerLine == PerParentName->second.end())
3654  return false;
3655  // Fail if this entry is already registered.
3656  if (PerLine->second.getAddress() || PerLine->second.getID())
3657  return false;
3658  return true;
3659 }
3660 
3661 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3662  const OffloadTargetRegionEntryInfoActTy &Action) {
3663  // Scan all target region entries and perform the provided action.
3664  for (const auto &D : OffloadEntriesTargetRegion)
3665  for (const auto &F : D.second)
3666  for (const auto &P : F.second)
3667  for (const auto &L : P.second)
3668  Action(D.first, F.first, P.first(), L.first, L.second);
3669 }
3670 
3671 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3672  initializeDeviceGlobalVarEntryInfo(StringRef Name,
3673  OMPTargetGlobalVarEntryKind Flags,
3674  unsigned Order) {
3675  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3676  "only required for the device "
3677  "code generation.");
3678  OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3679  ++OffloadingEntriesNum;
3680 }
3681 
3682 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3683  registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3684  CharUnits VarSize,
3685  OMPTargetGlobalVarEntryKind Flags,
3686  llvm::GlobalValue::LinkageTypes Linkage) {
3687  if (CGM.getLangOpts().OpenMPIsDevice) {
3688  auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3689  assert(Entry.isValid() && Entry.getFlags() == Flags &&
3690  "Entry not initialized!");
3691  assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3692  "Resetting with the new address.");
3693  if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3694  return;
3695  Entry.setAddress(Addr);
3696  Entry.setVarSize(VarSize);
3697  Entry.setLinkage(Linkage);
3698  } else {
3699  if (hasDeviceGlobalVarEntryInfo(VarName))
3700  return;
3701  OffloadEntriesDeviceGlobalVar.try_emplace(
3702  VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3703  ++OffloadingEntriesNum;
3704  }
3705 }
3706 
3707 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3708  actOnDeviceGlobalVarEntriesInfo(
3709  const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3710  // Scan all target region entries and perform the provided action.
3711  for (const auto &E : OffloadEntriesDeviceGlobalVar)
3712  Action(E.getKey(), E.getValue());
3713 }
3714 
3715 llvm::Function *
3717  // If we don't have entries or if we are emitting code for the device, we
3718  // don't need to do anything.
3719  if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3720  return nullptr;
3721 
3722  llvm::Module &M = CGM.getModule();
3723  ASTContext &C = CGM.getContext();
3724 
3725  // Get list of devices we care about
3726  const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
3727 
3728  // We should be creating an offloading descriptor only if there are devices
3729  // specified.
3730  assert(!Devices.empty() && "No OpenMP offloading devices??");
3731 
3732  // Create the external variables that will point to the begin and end of the
3733  // host entries section. These will be defined by the linker.
3734  llvm::Type *OffloadEntryTy =
3736  std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
3737  auto *HostEntriesBegin = new llvm::GlobalVariable(
3738  M, OffloadEntryTy, /*isConstant=*/true,
3739  llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3740  EntriesBeginName);
3741  std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3742  auto *HostEntriesEnd =
3743  new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3745  /*Initializer=*/nullptr, EntriesEndName);
3746 
3747  // Create all device images
3748  auto *DeviceImageTy = cast<llvm::StructType>(
3750  ConstantInitBuilder DeviceImagesBuilder(CGM);
3751  ConstantArrayBuilder DeviceImagesEntries =
3752  DeviceImagesBuilder.beginArray(DeviceImageTy);
3753 
3754  for (const llvm::Triple &Device : Devices) {
3755  StringRef T = Device.getTriple();
3756  std::string BeginName = getName({"omp_offloading", "img_start", ""});
3757  auto *ImgBegin = new llvm::GlobalVariable(
3758  M, CGM.Int8Ty, /*isConstant=*/true,
3759  llvm::GlobalValue::ExternalWeakLinkage,
3760  /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3761  std::string EndName = getName({"omp_offloading", "img_end", ""});
3762  auto *ImgEnd = new llvm::GlobalVariable(
3763  M, CGM.Int8Ty, /*isConstant=*/true,
3764  llvm::GlobalValue::ExternalWeakLinkage,
3765  /*Initializer=*/nullptr, Twine(EndName).concat(T));
3766 
3767  llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3768  HostEntriesEnd};
3770  DeviceImagesEntries);
3771  }
3772 
3773  // Create device images global array.
3774  std::string ImagesName = getName({"omp_offloading", "device_images"});
3775  llvm::GlobalVariable *DeviceImages =
3776  DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3777  CGM.getPointerAlign(),
3778  /*isConstant=*/true);
3779  DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3780 
3781  // This is a Zero array to be used in the creation of the constant expressions
3782  llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3783  llvm::Constant::getNullValue(CGM.Int32Ty)};
3784 
3785  // Create the target region descriptor.
3786  llvm::Constant *Data[] = {
3787  llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3788  llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3789  DeviceImages, Index),
3790  HostEntriesBegin, HostEntriesEnd};
3791  std::string Descriptor = getName({"omp_offloading", "descriptor"});
3792  llvm::GlobalVariable *Desc = createGlobalStruct(
3793  CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
3794 
3795  // Emit code to register or unregister the descriptor at execution
3796  // startup or closing, respectively.
3797 
3798  llvm::Function *UnRegFn;
3799  {
3800  FunctionArgList Args;
3802  Args.push_back(&DummyPtr);
3803 
3804  CodeGenFunction CGF(CGM);
3805  // Disable debug info for global (de-)initializer because they are not part
3806  // of some particular construct.
3807  CGF.disableDebugInfo();
3808  const auto &FI =
3810  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3811  std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3812  UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
3813  CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3815  Desc);
3816  CGF.FinishFunction();
3817  }
3818  llvm::Function *RegFn;
3819  {
3820  CodeGenFunction CGF(CGM);
3821  // Disable debug info for global (de-)initializer because they are not part
3822  // of some particular construct.
3823  CGF.disableDebugInfo();
3824  const auto &FI = CGM.getTypes().arrangeNullaryFunction();
3825  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3826 
3827  // Encode offload target triples into the registration function name. It
3828  // will serve as a comdat key for the registration/unregistration code for
3829  // this particular combination of offloading targets.
3830  SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3831  RegFnNameParts[0] = "omp_offloading";
3832  RegFnNameParts[1] = "descriptor_reg";
3833  llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3834  [](const llvm::Triple &T) -> const std::string& {
3835  return T.getTriple();
3836  });
3837  llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3838  std::string Descriptor = getName(RegFnNameParts);
3839  RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
3840  CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3842  // Create a variable to drive the registration and unregistration of the
3843  // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3844  ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3845  SourceLocation(), nullptr, C.CharTy,
3847  CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3848  CGF.FinishFunction();
3849  }
3850  if (CGM.supportsCOMDAT()) {
3851  // It is sufficient to call registration function only once, so create a
3852  // COMDAT group for registration/unregistration functions and associated
3853  // data. That would reduce startup time and code size. Registration
3854  // function serves as a COMDAT group key.
3855  llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
3856  RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3857  RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3858  RegFn->setComdat(ComdatKey);
3859  UnRegFn->setComdat(ComdatKey);
3860  DeviceImages->setComdat(ComdatKey);
3861  Desc->setComdat(ComdatKey);
3862  }
3863  return RegFn;
3864 }
3865 
3867  llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3868  llvm::GlobalValue::LinkageTypes Linkage) {
3869  StringRef Name = Addr->getName();
3870  llvm::Module &M = CGM.getModule();
3871  llvm::LLVMContext &C = M.getContext();
3872 
3873  // Create constant string with the name.
3874  llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3875 
3876  std::string StringName = getName({"omp_offloading", "entry_name"});
3877  auto *Str = new llvm::GlobalVariable(
3878  M, StrPtrInit->getType(), /*isConstant=*/true,
3879  llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
3880  Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3881 
3882  llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3883  llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3884  llvm::ConstantInt::get(CGM.SizeTy, Size),
3885  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3886  llvm::ConstantInt::get(CGM.Int32Ty, 0)};
3887  std::string EntryName = getName({"omp_offloading", "entry", ""});
3888  llvm::GlobalVariable *Entry = createGlobalStruct(
3889  CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3890  Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
3891 
3892  // The entry has to be created in the section the linker expects it to be.
3893  std::string Section = getName({"omp_offloading", "entries"});
3894  Entry->setSection(Section);
3895 }
3896 
3898  // Emit the offloading entries and metadata so that the device codegen side
3899  // can easily figure out what to emit. The produced metadata looks like
3900  // this:
3901  //
3902  // !omp_offload.info = !{!1, ...}
3903  //
3904  // Right now we only generate metadata for function that contain target
3905  // regions.
3906 
3907  // If we do not have entries, we don't need to do anything.
3909  return;
3910 
3911  llvm::Module &M = CGM.getModule();
3912  llvm::LLVMContext &C = M.getContext();
3914  OrderedEntries(OffloadEntriesInfoManager.size());
3915 
3916  // Auxiliary methods to create metadata values and strings.
3917  auto &&GetMDInt = [this](unsigned V) {
3918  return llvm::ConstantAsMetadata::get(
3919  llvm::ConstantInt::get(CGM.Int32Ty, V));
3920  };
3921 
3922  auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3923 
3924  // Create the offloading info metadata node.
3925  llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3926 
3927  // Create function that emits metadata for each target region entry;
3928  auto &&TargetRegionMetadataEmitter =
3929  [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3930  unsigned DeviceID, unsigned FileID, StringRef ParentName,
3931  unsigned Line,
3933  // Generate metadata for target regions. Each entry of this metadata
3934  // contains:
3935  // - Entry 0 -> Kind of this type of metadata (0).
3936  // - Entry 1 -> Device ID of the file where the entry was identified.
3937  // - Entry 2 -> File ID of the file where the entry was identified.
3938  // - Entry 3 -> Mangled name of the function where the entry was
3939  // identified.
3940  // - Entry 4 -> Line in the file where the entry was identified.
3941  // - Entry 5 -> Order the entry was created.
3942  // The first element of the metadata node is the kind.
3943  llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3944  GetMDInt(FileID), GetMDString(ParentName),
3945  GetMDInt(Line), GetMDInt(E.getOrder())};
3946 
3947  // Save this entry in the right position of the ordered entries array.
3948  OrderedEntries[E.getOrder()] = &E;
3949 
3950  // Add metadata to the named metadata node.
3951  MD->addOperand(llvm::MDNode::get(C, Ops));
3952  };
3953 
3955  TargetRegionMetadataEmitter);
3956 
3957  // Create function that emits metadata for each device global variable entry;
3958  auto &&DeviceGlobalVarMetadataEmitter =
3959  [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3960  MD](StringRef MangledName,
3962  &E) {
3963  // Generate metadata for global variables. Each entry of this metadata
3964  // contains:
3965  // - Entry 0 -> Kind of this type of metadata (1).
3966  // - Entry 1 -> Mangled name of the variable.
3967  // - Entry 2 -> Declare target kind.
3968  // - Entry 3 -> Order the entry was created.
3969  // The first element of the metadata node is the kind.
3970  llvm::Metadata *Ops[] = {
3971  GetMDInt(E.getKind()), GetMDString(MangledName),
3972  GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3973 
3974  // Save this entry in the right position of the ordered entries array.
3975  OrderedEntries[E.getOrder()] = &E;
3976 
3977  // Add metadata to the named metadata node.
3978  MD->addOperand(llvm::MDNode::get(C, Ops));
3979  };
3980 
3982  DeviceGlobalVarMetadataEmitter);
3983 
3984  for (const auto *E : OrderedEntries) {
3985  assert(E && "All ordered entries must exist!");
3986  if (const auto *CE =
3987  dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3988  E)) {
3989  if (!CE->getID() || !CE->getAddress()) {
3990  unsigned DiagID = CGM.getDiags().getCustomDiagID(
3992  "Offloading entry for target region is incorrect: either the "
3993  "address or the ID is invalid.");
3994  CGM.getDiags().Report(DiagID);
3995  continue;
3996  }
3997  createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
3998  CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3999  } else if (const auto *CE =
4000  dyn_cast<OffloadEntriesInfoManagerTy::
4001  OffloadEntryInfoDeviceGlobalVar>(E)) {
4004  CE->getFlags());
4005  switch (Flags) {
4007  if (!CE->getAddress()) {
4008  unsigned DiagID = CGM.getDiags().getCustomDiagID(
4010  "Offloading entry for declare target variable is incorrect: the "
4011  "address is invalid.");
4012  CGM.getDiags().Report(DiagID);
4013  continue;
4014  }
4015  // The vaiable has no definition - no need to add the entry.
4016  if (CE->getVarSize().isZero())
4017  continue;
4018  break;
4019  }
4021  assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4022  (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4023  "Declaret target link address is set.");
4024  if (CGM.getLangOpts().OpenMPIsDevice)
4025  continue;
4026  if (!CE->getAddress()) {
4027  unsigned DiagID = CGM.getDiags().getCustomDiagID(
4029  "Offloading entry for declare target variable is incorrect: the "
4030  "address is invalid.");
4031  CGM.getDiags().Report(DiagID);
4032  continue;
4033  }
4034  break;
4035  }
4036  createOffloadEntry(CE->getAddress(), CE->getAddress(),
4037  CE->getVarSize().getQuantity(), Flags,
4038  CE->getLinkage());
4039  } else {
4040  llvm_unreachable("Unsupported entry kind.");
4041  }
4042  }
4043 }
4044 
4045 /// Loads all the offload entries information from the host IR
4046 /// metadata.
4048  // If we are in target mode, load the metadata from the host IR. This code has
4049  // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4050 
4051  if (!CGM.getLangOpts().OpenMPIsDevice)
4052  return;
4053 
4054  if (CGM.getLangOpts().OMPHostIRFile.empty())
4055  return;
4056 
4057  auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
4058  if (auto EC = Buf.getError()) {
4059  CGM.getDiags().Report(diag::err_cannot_open_file)
4060  << CGM.getLangOpts().OMPHostIRFile << EC.message();
4061  return;
4062  }
4063 
4064  llvm::LLVMContext C;
4065  auto ME = expectedToErrorOrAndEmitErrors(
4066  C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
4067 
4068  if (auto EC = ME.getError()) {
4069  unsigned DiagID = CGM.getDiags().getCustomDiagID(
4070  DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4071  CGM.getDiags().Report(DiagID)
4072  << CGM.getLangOpts().OMPHostIRFile << EC.message();
4073  return;
4074  }
4075 
4076  llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4077  if (!MD)
4078  return;
4079 
4080  for (llvm::MDNode *MN : MD->operands()) {
4081  auto &&GetMDInt = [MN](unsigned Idx) {
4082  auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
4083  return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4084  };
4085 
4086  auto &&GetMDString = [MN](unsigned Idx) {
4087  auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
4088  return V->getString();
4089  };
4090 
4091  switch (GetMDInt(0)) {
4092  default:
4093  llvm_unreachable("Unexpected metadata!");
4094  break;
4098  /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4099  /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4100  /*Order=*/GetMDInt(5));
4101  break;
4105  /*MangledName=*/GetMDString(1),
4106  static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4107  /*Flags=*/GetMDInt(2)),
4108  /*Order=*/GetMDInt(3));
4109  break;
4110  }
4111  }
4112 }
4113 
4115  if (!KmpRoutineEntryPtrTy) {
4116  // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
4117  ASTContext &C = CGM.getContext();
4118  QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4120  KmpRoutineEntryPtrQTy = C.getPointerType(
4121  C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4122  KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4123  }
4124 }
4125 
4127  // Make sure the type of the entry is already created. This is the type we
4128  // have to create:
4129  // struct __tgt_offload_entry{
4130  // void *addr; // Pointer to the offload entry info.
4131  // // (function or global)
4132  // char *name; // Name of the function or global.
4133  // size_t size; // Size of the entry info (0 if it a function).
4134  // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4135  // int32_t reserved; // Reserved, to use by the runtime library.
4136  // };
4137  if (TgtOffloadEntryQTy.isNull()) {
4138  ASTContext &C = CGM.getContext();
4139  RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
4140  RD->startDefinition();
4141  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4143  addFieldToRecordDecl(C, RD, C.getSizeType());
4145  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4147  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4148  RD->completeDefinition();
4149  RD->addAttr(PackedAttr::CreateImplicit(C));
4151  }
4152  return TgtOffloadEntryQTy;
4153 }
4154 
4156  // These are the types we need to build:
4157  // struct __tgt_device_image{
4158  // void *ImageStart; // Pointer to the target code start.
4159  // void *ImageEnd; // Pointer to the target code end.
4160  // // We also add the host entries to the device image, as it may be useful
4161  // // for the target runtime to have access to that information.
4162  // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4163  // // the entries.
4164  // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4165  // // entries (non inclusive).
4166  // };
4167  if (TgtDeviceImageQTy.isNull()) {
4168  ASTContext &C = CGM.getContext();
4169  RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
4170  RD->startDefinition();
4171  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4172  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4175  RD->completeDefinition();
4177  }
4178  return TgtDeviceImageQTy;
4179 }
4180 
4182  // struct __tgt_bin_desc{
4183  // int32_t NumDevices; // Number of devices supported.
4184  // __tgt_device_image *DeviceImages; // Arrays of device images
4185  // // (one per device).
4186  // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4187  // // entries.
4188  // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4189  // // entries (non inclusive).
4190  // };
4192  ASTContext &C = CGM.getContext();
4193  RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
4194  RD->startDefinition();
4196  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4200  RD->completeDefinition();
4202  }
4203  return TgtBinaryDescriptorQTy;
4204 }
4205 
4206 namespace {
4207 struct PrivateHelpersTy {
4208  PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4209  const VarDecl *PrivateElemInit)
4210  : Original(Original), PrivateCopy(PrivateCopy),
4211  PrivateElemInit(PrivateElemInit) {}
4212  const VarDecl *Original;
4213  const VarDecl *PrivateCopy;
4214  const VarDecl *PrivateElemInit;
4215 };
4216 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
4217 } // anonymous namespace
4218 
4219 static RecordDecl *
4221  if (!Privates.empty()) {
4222  ASTContext &C = CGM.getContext();
4223  // Build struct .kmp_privates_t. {
4224  // /* private vars */
4225  // };
4226  RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
4227  RD->startDefinition();
4228  for (const auto &Pair : Privates) {
4229  const VarDecl *VD = Pair.second.Original;
4230  QualType Type = VD->getType().getNonReferenceType();
4231  FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
4232  if (VD->hasAttrs()) {
4233  for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4234  E(VD->getAttrs().end());
4235  I != E; ++I)
4236  FD->addAttr(*I);
4237  }
4238  }
4239  RD->completeDefinition();
4240  return RD;
4241  }
4242  return nullptr;
4243 }
4244 
4245 static RecordDecl *
4247  QualType KmpInt32Ty,
4248  QualType KmpRoutineEntryPointerQTy) {
4249  ASTContext &C = CGM.getContext();
4250  // Build struct kmp_task_t {
4251  // void * shareds;
4252  // kmp_routine_entry_t routine;
4253  // kmp_int32 part_id;
4254  // kmp_cmplrdata_t data1;
4255  // kmp_cmplrdata_t data2;
4256  // For taskloops additional fields:
4257  // kmp_uint64 lb;
4258  // kmp_uint64 ub;
4259  // kmp_int64 st;
4260  // kmp_int32 liter;
4261  // void * reductions;
4262  // };
4263  RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
4264  UD->startDefinition();
4265  addFieldToRecordDecl(C, UD, KmpInt32Ty);
4266  addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4267  UD->completeDefinition();
4268  QualType KmpCmplrdataTy = C.getRecordType(UD);
4269  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
4270  RD->startDefinition();
4271  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4272  addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4273  addFieldToRecordDecl(C, RD, KmpInt32Ty);
4274  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4275  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4276  if (isOpenMPTaskLoopDirective(Kind)) {
4277  QualType KmpUInt64Ty =
4278  CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4279  QualType KmpInt64Ty =
4280  CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4281  addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4282  addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4283  addFieldToRecordDecl(C, RD, KmpInt64Ty);
4284  addFieldToRecordDecl(C, RD, KmpInt32Ty);
4285  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4286  }
4287  RD->completeDefinition();
4288  return RD;
4289 }
4290 
4291 static RecordDecl *
4293  ArrayRef<PrivateDataTy> Privates) {
4294  ASTContext &C = CGM.getContext();
4295  // Build struct kmp_task_t_with_privates {
4296  // kmp_task_t task_data;
4297  // .kmp_privates_t. privates;
4298  // };
4299  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
4300  RD->startDefinition();
4301  addFieldToRecordDecl(C, RD, KmpTaskTQTy);
4302  if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
4303  addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
4304  RD->completeDefinition();
4305  return RD;
4306 }
4307 
4308 /// Emit a proxy function which accepts kmp_task_t as the second
4309 /// argument.
4310 /// \code
4311 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
4312 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
4313 /// For taskloops:
4314 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4315 /// tt->reductions, tt->shareds);
4316 /// return 0;
4317 /// }
4318 /// \endcode
4319 static llvm::Value *
4321  OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4322  QualType KmpTaskTWithPrivatesPtrQTy,
4323  QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
4324  QualType SharedsPtrTy, llvm::Value *TaskFunction,
4325  llvm::Value *TaskPrivatesMap) {
4326  ASTContext &C = CGM.getContext();
4327  FunctionArgList Args;
4328  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4330  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4331  KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4333  Args.push_back(&GtidArg);
4334  Args.push_back(&TaskTypeArg);
4335  const auto &TaskEntryFnInfo =
4336  CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4337  llvm::FunctionType *TaskEntryTy =
4338  CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
4339  std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4340  auto *TaskEntry = llvm::Function::Create(
4341  TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
4342  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
4343  TaskEntry->setDoesNotRecurse();
4344  CodeGenFunction CGF(CGM);
4345  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4346  Loc, Loc);
4347 
4348  // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
4349  // tt,
4350  // For taskloops:
4351  // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4352  // tt->task_data.shareds);
4353  llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
4354  CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
4355  LValue TDBase = CGF.EmitLoadOfPointerLValue(
4356  CGF.GetAddrOfLocalVar(&TaskTypeArg),
4357  KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4358  const auto *KmpTaskTWithPrivatesQTyRD =
4359  cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4360  LValue Base =
4361  CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4362  const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4363  auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4364  LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4365  llvm::Value *PartidParam = PartIdLVal.getPointer();
4366 
4367  auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4368  LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4370  CGF.EmitLoadOfScalar(SharedsLVal, Loc),
4371  CGF.ConvertTypeForMem(SharedsPtrTy));
4372 
4373  auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4374  llvm::Value *PrivatesParam;
4375  if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4376  LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4377  PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4378  PrivatesLVal.getPointer(), CGF.VoidPtrTy);
4379  } else {
4380  PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4381  }
4382 
4383  llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4384  TaskPrivatesMap,
4385  CGF.Builder
4387  TDBase.getAddress(), CGF.VoidPtrTy)
4388  .getPointer()};
4389  SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4390  std::end(CommonArgs));
4391  if (isOpenMPTaskLoopDirective(Kind)) {
4392  auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4393  LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4394  llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
4395  auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4396  LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4397  llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
4398  auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4399  LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4400  llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
4401  auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4402  LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4403  llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
4404  auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4405  LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4406  llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
4407  CallArgs.push_back(LBParam);
4408  CallArgs.push_back(UBParam);
4409  CallArgs.push_back(StParam);
4410  CallArgs.push_back(LIParam);
4411  CallArgs.push_back(RParam);
4412  }
4413  CallArgs.push_back(SharedsParam);
4414 
4415  CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4416  CallArgs);
4417  CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4418  CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
4419  CGF.FinishFunction();
4420  return TaskEntry;
4421 }
4422 
4424  SourceLocation Loc,
4425  QualType KmpInt32Ty,
4426  QualType KmpTaskTWithPrivatesPtrQTy,
4427  QualType KmpTaskTWithPrivatesQTy) {
4428  ASTContext &C = CGM.getContext();
4429  FunctionArgList Args;
4430  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4432  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4433  KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4435  Args.push_back(&GtidArg);
4436  Args.push_back(&TaskTypeArg);
4437  const auto &DestructorFnInfo =
4438  CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4439  llvm::FunctionType *DestructorFnTy =
4440  CGM.getTypes().GetFunctionType(DestructorFnInfo);
4441  std::string Name =
4442  CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
4443  auto *DestructorFn =
4445  Name, &CGM.getModule());
4446  CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
4447  DestructorFnInfo);
4448  DestructorFn->setDoesNotRecurse();
4449  CodeGenFunction CGF(CGM);
4450  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4451  Args, Loc, Loc);
4452 
4454  CGF.GetAddrOfLocalVar(&TaskTypeArg),
4455  KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4456  const auto *KmpTaskTWithPrivatesQTyRD =
4457  cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4458  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4459  Base = CGF.EmitLValueForField(Base, *FI);
4460  for (const auto *Field :
4461  cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4462  if (QualType::DestructionKind DtorKind =
4463  Field->getType().isDestructedType()) {
4464  LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
4465  CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4466  }
4467  }
4468  CGF.FinishFunction();
4469  return DestructorFn;
4470 }
4471 
4472 /// Emit a privates mapping function for correct handling of private and
4473 /// firstprivate variables.
4474 /// \code
4475 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4476 /// **noalias priv1,..., <tyn> **noalias privn) {
4477 /// *priv1 = &.privates.priv1;
4478 /// ...;
4479 /// *privn = &.privates.privn;
4480 /// }
4481 /// \endcode
4482 static llvm::Value *
4484  ArrayRef<const Expr *> PrivateVars,
4485  ArrayRef<const Expr *> FirstprivateVars,
4486  ArrayRef<const Expr *> LastprivateVars,
4487  QualType PrivatesQTy,
4488  ArrayRef<PrivateDataTy> Privates) {
4489  ASTContext &C = CGM.getContext();
4490  FunctionArgList Args;
4491  ImplicitParamDecl TaskPrivatesArg(
4492  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4493  C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4495  Args.push_back(&TaskPrivatesArg);
4496  llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4497  unsigned Counter = 1;
4498  for (const Expr *E : PrivateVars) {
4499  Args.push_back(ImplicitParamDecl::Create(
4500  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4502  .withConst()
4503  .withRestrict(),
4505  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4506  PrivateVarsPos[VD] = Counter;
4507  ++Counter;
4508  }
4509  for (const Expr *E : FirstprivateVars) {
4510  Args.push_back(ImplicitParamDecl::Create(
4511  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4513  .withConst()
4514  .withRestrict(),
4516  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4517  PrivateVarsPos[VD] = Counter;
4518  ++Counter;
4519  }
4520  for (const Expr *E : LastprivateVars) {
4521  Args.push_back(ImplicitParamDecl::Create(
4522  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4524  .withConst()
4525  .withRestrict(),
4527  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4528  PrivateVarsPos[VD] = Counter;
4529  ++Counter;
4530  }
4531  const auto &TaskPrivatesMapFnInfo =
4533  llvm::FunctionType *TaskPrivatesMapTy =
4534  CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4535  std::string Name =
4536  CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
4537  auto *TaskPrivatesMap = llvm::Function::Create(
4538  TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4539  &CGM.getModule());
4540  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
4541  TaskPrivatesMapFnInfo);
4542  TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
4543  TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
4544  TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
4545  CodeGenFunction CGF(CGM);
4546  CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4547  TaskPrivatesMapFnInfo, Args, Loc, Loc);
4548 
4549  // *privi = &.privates.privi;
4551  CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4552  TaskPrivatesArg.getType()->castAs<PointerType>());
4553  const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4554  Counter = 0;
4555  for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4556  LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4557  const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4558  LValue RefLVal =
4559  CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4560  LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4561  RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
4562  CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
4563  ++Counter;
4564  }
4565  CGF.FinishFunction();
4566  return TaskPrivatesMap;
4567 }
4568 
4569 static bool stable_sort_comparator(const PrivateDataTy P1,
4570  const PrivateDataTy P2) {
4571  return P1.first > P2.first;
4572 }
4573 
4574 /// Emit initialization for private variables in task-based directives.
4576  const OMPExecutableDirective &D,
4577  Address KmpTaskSharedsPtr, LValue TDBase,
4578  const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4579  QualType SharedsTy, QualType SharedsPtrTy,
4580  const OMPTaskDataTy &Data,
4581  ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4582  ASTContext &C = CGF.getContext();
4583  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4584  LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4586  ? OMPD_taskloop
4587  : OMPD_task;
4588  const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4589  CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
4590  LValue SrcBase;
4591  bool IsTargetTask =
4594  // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4595  // PointersArray and SizesArray. The original variables for these arrays are
4596  // not captured and we get their addresses explicitly.
4597  if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4598  (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
4599  SrcBase = CGF.MakeAddrLValue(
4601  KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4602  SharedsTy);
4603  }
4604  FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4605  for (const PrivateDataTy &Pair : Privates) {
4606  const VarDecl *VD = Pair.second.PrivateCopy;
4607  const Expr *Init = VD->getAnyInitializer();
4608  if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4609  !CGF.isTrivialInitializer(Init)))) {
4610  LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
4611  if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4612  const VarDecl *OriginalVD = Pair.second.Original;
4613  // Check if the variable is the target-based BasePointersArray,
4614  // PointersArray or SizesArray.
4615  LValue SharedRefLValue;
4616  QualType Type = OriginalVD->getType();
4617  const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
4618  if (IsTargetTask && !SharedField) {
4619  assert(isa<ImplicitParamDecl>(OriginalVD) &&
4620  isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4621  cast<CapturedDecl>(OriginalVD->getDeclContext())
4622  ->getNumParams() == 0 &&
4623  isa<TranslationUnitDecl>(
4624  cast<CapturedDecl>(OriginalVD->getDeclContext())
4625  ->getDeclContext()) &&
4626  "Expected artificial target data variable.");
4627  SharedRefLValue =
4628  CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4629  } else {
4630  SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4631  SharedRefLValue = CGF.MakeAddrLValue(
4632  Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4633  SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4634  SharedRefLValue.getTBAAInfo());
4635  }
4636  if (Type->isArrayType()) {
4637  // Initialize firstprivate array.
4638  if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4639  // Perform simple memcpy.
4640  CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
4641  } else {
4642  // Initialize firstprivate array using element-by-element
4643  // initialization.
4645  PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,