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  ASTContext &C = CGM.getContext();
1299  if (!In || !Out) {
1300  In = &C.Idents.get("omp_in");
1301  Out = &C.Idents.get("omp_out");
1302  }
1303  llvm::Function *Combiner = emitCombinerOrInitializer(
1304  CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1305  cast<VarDecl>(D->lookup(Out).front()),
1306  /*IsCombiner=*/true);
1307  llvm::Function *Initializer = nullptr;
1308  if (const Expr *Init = D->getInitializer()) {
1309  if (!Priv || !Orig) {
1310  Priv = &C.Idents.get("omp_priv");
1311  Orig = &C.Idents.get("omp_orig");
1312  }
1313  Initializer = emitCombinerOrInitializer(
1314  CGM, D->getType(),
1316  : nullptr,
1317  cast<VarDecl>(D->lookup(Orig).front()),
1318  cast<VarDecl>(D->lookup(Priv).front()),
1319  /*IsCombiner=*/false);
1320  }
1321  UDRMap.try_emplace(D, Combiner, Initializer);
1322  if (CGF) {
1323  auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1324  Decls.second.push_back(D);
1325  }
1326 }
1327 
1328 std::pair<llvm::Function *, llvm::Function *>
1330  auto I = UDRMap.find(D);
1331  if (I != UDRMap.end())
1332  return I->second;
1333  emitUserDefinedReduction(/*CGF=*/nullptr, D);
1334  return UDRMap.lookup(D);
1335 }
1336 
1338  CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1339  const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1340  const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1341  assert(ThreadIDVar->getType()->isPointerType() &&
1342  "thread id variable must be of type kmp_int32 *");
1343  CodeGenFunction CGF(CGM, true);
1344  bool HasCancel = false;
1345  if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1346  HasCancel = OPD->hasCancel();
1347  else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1348  HasCancel = OPSD->hasCancel();
1349  else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1350  HasCancel = OPFD->hasCancel();
1351  else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1352  HasCancel = OPFD->hasCancel();
1353  else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1354  HasCancel = OPFD->hasCancel();
1355  else if (const auto *OPFD =
1356  dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1357  HasCancel = OPFD->hasCancel();
1358  else if (const auto *OPFD =
1359  dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1360  HasCancel = OPFD->hasCancel();
1361  CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1362  HasCancel, OutlinedHelperName);
1363  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1364  return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
1365 }
1366 
1368  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1369  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1370  const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1372  CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1373 }
1374 
1376  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1377  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1378  const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1380  CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1381 }
1382 
1384  const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1385  const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1386  OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1387  bool Tied, unsigned &NumberOfParts) {
1388  auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1389  PrePostActionTy &) {
1390  llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1391  llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
1392  llvm::Value *TaskArgs[] = {
1393  UpLoc, ThreadID,
1394  CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1395  TaskTVar->getType()->castAs<PointerType>())
1396  .getPointer()};
1397  CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1398  };
1399  CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1400  UntiedCodeGen);
1401  CodeGen.setAction(Action);
1402  assert(!ThreadIDVar->getType()->isPointerType() &&
1403  "thread id variable must be of type kmp_int32 for tasks");
1404  const OpenMPDirectiveKind Region =
1405  isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1406  : OMPD_task;
1407  const CapturedStmt *CS = D.getCapturedStmt(Region);
1408  const auto *TD = dyn_cast<OMPTaskDirective>(&D);
1409  CodeGenFunction CGF(CGM, true);
1410  CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1411  InnermostKind,
1412  TD ? TD->hasCancel() : false, Action);
1413  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1414  llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
1415  if (!Tied)
1416  NumberOfParts = Action.getNumberOfParts();
1417  return Res;
1418 }
1419 
1421  const RecordDecl *RD, const CGRecordLayout &RL,
1422  ArrayRef<llvm::Constant *> Data) {
1423  llvm::StructType *StructTy = RL.getLLVMType();
1424  unsigned PrevIdx = 0;
1425  ConstantInitBuilder CIBuilder(CGM);
1426  auto DI = Data.begin();
1427  for (const FieldDecl *FD : RD->fields()) {
1428  unsigned Idx = RL.getLLVMFieldNo(FD);
1429  // Fill the alignment.
1430  for (unsigned I = PrevIdx; I < Idx; ++I)
1431  Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1432  PrevIdx = Idx + 1;
1433  Fields.add(*DI);
1434  ++DI;
1435  }
1436 }
1437 
1438 template <class... As>
1439 static llvm::GlobalVariable *
1441  ArrayRef<llvm::Constant *> Data, const Twine &Name,
1442  As &&... Args) {
1443  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1444  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1445  ConstantInitBuilder CIBuilder(CGM);
1446  ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1447  buildStructValue(Fields, CGM, RD, RL, Data);
1448  return Fields.finishAndCreateGlobal(
1449  Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1450  /*isConstant=*/true, std::forward<As>(Args)...);
1451 }
1452 
1453 template <typename T>
1454 static void
1456  ArrayRef<llvm::Constant *> Data,
1457  T &Parent) {
1458  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1459  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1460  ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1461  buildStructValue(Fields, CGM, RD, RL, Data);
1462  Fields.finishAndAddTo(Parent);
1463 }
1464 
1465 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
1466  CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1467  llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
1468  if (!Entry) {
1469  if (!DefaultOpenMPPSource) {
1470  // Initialize default location for psource field of ident_t structure of
1471  // all ident_t objects. Format is ";file;function;line;column;;".
1472  // Taken from
1473  // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1474  DefaultOpenMPPSource =
1475  CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
1476  DefaultOpenMPPSource =
1477  llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1478  }
1479 
1480  llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1481  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1482  llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1483  llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1484  DefaultOpenMPPSource};
1485  llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1486  CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1487  DefaultOpenMPLocation->setUnnamedAddr(
1488  llvm::GlobalValue::UnnamedAddr::Global);
1489 
1490  OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
1491  }
1492  return Address(Entry, Align);
1493 }
1494 
1496  SourceLocation Loc,
1497  unsigned Flags) {
1498  Flags |= OMP_IDENT_KMPC;
1499  // If no debug info is generated - return global default location.
1500  if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1501  Loc.isInvalid())
1502  return getOrCreateDefaultLocation(Flags).getPointer();
1503 
1504  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1505 
1506  CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1507  Address LocValue = Address::invalid();
1508  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1509  if (I != OpenMPLocThreadIDMap.end())
1510  LocValue = Address(I->second.DebugLoc, Align);
1511 
1512  // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1513  // GetOpenMPThreadID was called before this routine.
1514  if (!LocValue.isValid()) {
1515  // Generate "ident_t .kmpc_loc.addr;"
1516  Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
1517  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1518  Elem.second.DebugLoc = AI.getPointer();
1519  LocValue = AI;
1520 
1521  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1522  CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1523  CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
1524  CGF.getTypeSize(IdentQTy));
1525  }
1526 
1527  // char **psource = &.kmpc_loc_<flags>.addr.psource;
1528  LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1529  auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1530  LValue PSource =
1531  CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
1532 
1533  llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1534  if (OMPDebugLoc == nullptr) {
1535  SmallString<128> Buffer2;
1536  llvm::raw_svector_ostream OS2(Buffer2);
1537  // Build debug location
1539  OS2 << ";" << PLoc.getFilename() << ";";
1540  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1541  OS2 << FD->getQualifiedNameAsString();
1542  OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1543  OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1544  OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
1545  }
1546  // *psource = ";<File>;<Function>;<Line>;<Column>;;";
1547  CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
1548 
1549  // Our callers always pass this to a runtime function, so for
1550  // convenience, go ahead and return a naked pointer.
1551  return LocValue.getPointer();
1552 }
1553 
1555  SourceLocation Loc) {
1556  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1557 
1558  llvm::Value *ThreadID = nullptr;
1559  // Check whether we've already cached a load of the thread id in this
1560  // function.
1561  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1562  if (I != OpenMPLocThreadIDMap.end()) {
1563  ThreadID = I->second.ThreadID;
1564  if (ThreadID != nullptr)
1565  return ThreadID;
1566  }
1567  // If exceptions are enabled, do not use parameter to avoid possible crash.
1568  if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1569  !CGF.getLangOpts().CXXExceptions ||
1570  CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1571  if (auto *OMPRegionInfo =
1572  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1573  if (OMPRegionInfo->getThreadIDVariable()) {
1574  // Check if this an outlined function with thread id passed as argument.
1575  LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1576  ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1577  // If value loaded in entry block, cache it and use it everywhere in
1578  // function.
1579  if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1580  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1581  Elem.second.ThreadID = ThreadID;
1582  }
1583  return ThreadID;
1584  }
1585  }
1586  }
1587 
1588  // This is not an outlined function region - need to call __kmpc_int32
1589  // kmpc_global_thread_num(ident_t *loc).
1590  // Generate thread id value and cache this value for use across the
1591  // function.
1592  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1593  CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1594  llvm::CallInst *Call = CGF.Builder.CreateCall(
1596  emitUpdateLocation(CGF, Loc));
1597  Call->setCallingConv(CGF.getRuntimeCC());
1598  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1599  Elem.second.ThreadID = Call;
1600  return Call;
1601 }
1602 
1604  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1605  if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1606  OpenMPLocThreadIDMap.erase(CGF.CurFn);
1607  if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1608  for(auto *D : FunctionUDRMap[CGF.CurFn])
1609  UDRMap.erase(D);
1610  FunctionUDRMap.erase(CGF.CurFn);
1611  }
1612 }
1613 
1615  return IdentTy->getPointerTo();
1616 }
1617 
1619  if (!Kmpc_MicroTy) {
1620  // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1621  llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1622  llvm::PointerType::getUnqual(CGM.Int32Ty)};
1623  Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1624  }
1625  return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1626 }
1627 
1628 llvm::Constant *
1630  llvm::Constant *RTLFn = nullptr;
1631  switch (static_cast<OpenMPRTLFunction>(Function)) {
1632  case OMPRTL__kmpc_fork_call: {
1633  // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1634  // microtask, ...);
1635  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1637  auto *FnTy =
1638  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1639  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1640  break;
1641  }
1643  // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1644  llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1645  auto *FnTy =
1646  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1647  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1648  break;
1649  }
1651  // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1652  // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1653  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1655  CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1656  auto *FnTy =
1657  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1658  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1659  break;
1660  }
1661  case OMPRTL__kmpc_critical: {
1662  // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1663  // kmp_critical_name *crit);
1664  llvm::Type *TypeParams[] = {
1666  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1667  auto *FnTy =
1668  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1669  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1670  break;
1671  }
1673  // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1674  // kmp_critical_name *crit, uintptr_t hint);
1675  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1676  llvm::PointerType::getUnqual(KmpCriticalNameTy),
1677  CGM.IntPtrTy};
1678  auto *FnTy =
1679  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1680  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1681  break;
1682  }
1684  // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1685  // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1686  // typedef void *(*kmpc_ctor)(void *);
1687  auto *KmpcCtorTy =
1688  llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1689  /*isVarArg*/ false)->getPointerTo();
1690  // typedef void *(*kmpc_cctor)(void *, void *);
1691  llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1692  auto *KmpcCopyCtorTy =
1693  llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1694  /*isVarArg*/ false)
1695  ->getPointerTo();
1696  // typedef void (*kmpc_dtor)(void *);
1697  auto *KmpcDtorTy =
1698  llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1699  ->getPointerTo();
1700  llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1701  KmpcCopyCtorTy, KmpcDtorTy};
1702  auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1703  /*isVarArg*/ false);
1704  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1705  break;
1706  }
1708  // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1709  // kmp_critical_name *crit);
1710  llvm::Type *TypeParams[] = {
1712  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1713  auto *FnTy =
1714  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1715  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1716  break;
1717  }
1719  // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1720  // global_tid);
1721  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1722  auto *FnTy =
1723  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1724  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1725  break;
1726  }
1727  case OMPRTL__kmpc_barrier: {
1728  // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1729  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1730  auto *FnTy =
1731  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1732  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1733  break;
1734  }
1736  // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1737  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1738  auto *FnTy =
1739  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1740  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1741  break;
1742  }
1744  // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1745  // kmp_int32 num_threads)
1746  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1747  CGM.Int32Ty};
1748  auto *FnTy =
1749  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1751  break;
1752  }
1754  // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1755  // global_tid);
1756  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1757  auto *FnTy =
1758  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1759  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1760  break;
1761  }
1763  // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1764  // global_tid);
1765  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1766  auto *FnTy =
1767  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1769  break;
1770  }
1771  case OMPRTL__kmpc_flush: {
1772  // Build void __kmpc_flush(ident_t *loc);
1773  llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1774  auto *FnTy =
1775  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1776  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1777  break;
1778  }
1779  case OMPRTL__kmpc_master: {
1780  // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1781  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1782  auto *FnTy =
1783  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1784  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1785  break;
1786  }
1787  case OMPRTL__kmpc_end_master: {
1788  // Build void __kmpc_end_master(ident_t *loc, kmp_int32 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, /*Name=*/"__kmpc_end_master");
1793  break;
1794  }
1796  // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1797  // int end_part);
1798  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1799  auto *FnTy =
1800  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1801  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1802  break;
1803  }
1804  case OMPRTL__kmpc_single: {
1805  // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1806  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1807  auto *FnTy =
1808  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1809  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1810  break;
1811  }
1812  case OMPRTL__kmpc_end_single: {
1813  // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1814  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1815  auto *FnTy =
1816  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1817  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1818  break;
1819  }
1821  // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1822  // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1823  // kmp_routine_entry_t *task_entry);
1824  assert(KmpRoutineEntryPtrTy != nullptr &&
1825  "Type kmp_routine_entry_t must be created.");
1826  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1827  CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1828  // Return void * and then cast to particular kmp_task_t type.
1829  auto *FnTy =
1830  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1831  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1832  break;
1833  }
1834  case OMPRTL__kmpc_omp_task: {
1835  // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1836  // *new_task);
1837  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1838  CGM.VoidPtrTy};
1839  auto *FnTy =
1840  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1841  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1842  break;
1843  }
1844  case OMPRTL__kmpc_copyprivate: {
1845  // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1846  // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1847  // kmp_int32 didit);
1848  llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1849  auto *CpyFnTy =
1850  llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1851  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1852  CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1853  CGM.Int32Ty};
1854  auto *FnTy =
1855  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1856  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1857  break;
1858  }
1859  case OMPRTL__kmpc_reduce: {
1860  // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1861  // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1862  // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1863  llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1864  auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1865  /*isVarArg=*/false);
1866  llvm::Type *TypeParams[] = {
1868  CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1869  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1870  auto *FnTy =
1871  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1872  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1873  break;
1874  }
1876  // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1877  // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1878  // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1879  // *lck);
1880  llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1881  auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1882  /*isVarArg=*/false);
1883  llvm::Type *TypeParams[] = {
1885  CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1886  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1887  auto *FnTy =
1888  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1889  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1890  break;
1891  }
1892  case OMPRTL__kmpc_end_reduce: {
1893  // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1894  // kmp_critical_name *lck);
1895  llvm::Type *TypeParams[] = {
1897  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1898  auto *FnTy =
1899  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1900  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1901  break;
1902  }
1904  // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1905  // kmp_critical_name *lck);
1906  llvm::Type *TypeParams[] = {
1908  llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1909  auto *FnTy =
1910  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1911  RTLFn =
1912  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1913  break;
1914  }
1916  // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1917  // *new_task);
1918  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1919  CGM.VoidPtrTy};
1920  auto *FnTy =
1921  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1922  RTLFn =
1923  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1924  break;
1925  }
1927  // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1928  // *new_task);
1929  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1930  CGM.VoidPtrTy};
1931  auto *FnTy =
1932  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1933  RTLFn = CGM.CreateRuntimeFunction(FnTy,
1934  /*Name=*/"__kmpc_omp_task_complete_if0");
1935  break;
1936  }
1937  case OMPRTL__kmpc_ordered: {
1938  // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1939  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1940  auto *FnTy =
1941  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1942  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1943  break;
1944  }
1945  case OMPRTL__kmpc_end_ordered: {
1946  // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1947  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1948  auto *FnTy =
1949  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1950  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1951  break;
1952  }
1954  // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1955  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1956  auto *FnTy =
1957  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1958  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1959  break;
1960  }
1961  case OMPRTL__kmpc_taskgroup: {
1962  // Build void __kmpc_taskgroup(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_taskgroup");
1967  break;
1968  }
1970  // Build void __kmpc_end_taskgroup(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_taskgroup");
1975  break;
1976  }
1978  // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1979  // int proc_bind)
1980  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1981  auto *FnTy =
1982  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1983  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1984  break;
1985  }
1987  // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1988  // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1989  // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1990  llvm::Type *TypeParams[] = {
1993  auto *FnTy =
1994  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1995  RTLFn =
1996  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1997  break;
1998  }
2000  // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2001  // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2002  // kmp_depend_info_t *noalias_dep_list);
2003  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2006  auto *FnTy =
2007  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2008  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2009  break;
2010  }
2012  // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2013  // global_tid, kmp_int32 cncl_kind)
2014  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2015  auto *FnTy =
2016  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2017  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2018  break;
2019  }
2020  case OMPRTL__kmpc_cancel: {
2021  // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2022  // kmp_int32 cncl_kind)
2023  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2024  auto *FnTy =
2025  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2026  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2027  break;
2028  }
2030  // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2031  // kmp_int32 num_teams, kmp_int32 num_threads)
2032  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2033  CGM.Int32Ty};
2034  auto *FnTy =
2035  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2036  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2037  break;
2038  }
2039  case OMPRTL__kmpc_fork_teams: {
2040  // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2041  // microtask, ...);
2042  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2044  auto *FnTy =
2045  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2046  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2047  break;
2048  }
2049  case OMPRTL__kmpc_taskloop: {
2050  // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2051  // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2052  // sched, kmp_uint64 grainsize, void *task_dup);
2053  llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2054  CGM.IntTy,
2055  CGM.VoidPtrTy,
2056  CGM.IntTy,
2057  CGM.Int64Ty->getPointerTo(),
2058  CGM.Int64Ty->getPointerTo(),
2059  CGM.Int64Ty,
2060  CGM.IntTy,
2061  CGM.IntTy,
2062  CGM.Int64Ty,
2063  CGM.VoidPtrTy};
2064  auto *FnTy =
2065  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2066  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2067  break;
2068  }
2070  // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2071  // num_dims, struct kmp_dim *dims);
2072  llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2073  CGM.Int32Ty,
2074  CGM.Int32Ty,
2075  CGM.VoidPtrTy};
2076  auto *FnTy =
2077  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2078  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2079  break;
2080  }
2082  // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2083  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2084  auto *FnTy =
2085  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2086  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2087  break;
2088  }
2090  // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2091  // *vec);
2092  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2093  CGM.Int64Ty->getPointerTo()};
2094  auto *FnTy =
2095  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2096  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2097  break;
2098  }
2100  // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2101  // *vec);
2102  llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2103  CGM.Int64Ty->getPointerTo()};
2104  auto *FnTy =
2105  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2106  RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2107  break;
2108  }
2110  // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2111  // *data);
2112  llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2113  auto *FnTy =
2114  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2115  RTLFn =
2116  CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2117  break;
2118  }
2120  // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2121  // *d);
2122  llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2123  auto *FnTy =
2124  llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2125  RTLFn = CGM.CreateRuntimeFunction(
2126  FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2127  break;
2128  }
2129  case OMPRTL__tgt_target: {
2130  // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2131  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2132  // *arg_types);
2133  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2134  CGM.VoidPtrTy,
2135  CGM.Int32Ty,
2136  CGM.VoidPtrPtrTy,
2137  CGM.VoidPtrPtrTy,
2138  CGM.SizeTy->getPointerTo(),
2139  CGM.Int64Ty->getPointerTo()};
2140  auto *FnTy =
2141  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2142  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2143  break;
2144  }
2146  // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2147  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2148  // int64_t *arg_types);
2149  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2150  CGM.VoidPtrTy,
2151  CGM.Int32Ty,
2152  CGM.VoidPtrPtrTy,
2153  CGM.VoidPtrPtrTy,
2154  CGM.SizeTy->getPointerTo(),
2155  CGM.Int64Ty->getPointerTo()};
2156  auto *FnTy =
2157  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2158  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2159  break;
2160  }
2161  case OMPRTL__tgt_target_teams: {
2162  // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
2163  // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2164  // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2165  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2166  CGM.VoidPtrTy,
2167  CGM.Int32Ty,
2168  CGM.VoidPtrPtrTy,
2169  CGM.VoidPtrPtrTy,
2170  CGM.SizeTy->getPointerTo(),
2171  CGM.Int64Ty->getPointerTo(),
2172  CGM.Int32Ty,
2173  CGM.Int32Ty};
2174  auto *FnTy =
2175  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2176  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2177  break;
2178  }
2180  // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2181  // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2182  // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2183  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2184  CGM.VoidPtrTy,
2185  CGM.Int32Ty,
2186  CGM.VoidPtrPtrTy,
2187  CGM.VoidPtrPtrTy,
2188  CGM.SizeTy->getPointerTo(),
2189  CGM.Int64Ty->getPointerTo(),
2190  CGM.Int32Ty,
2191  CGM.Int32Ty};
2192  auto *FnTy =
2193  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2194  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2195  break;
2196  }
2197  case OMPRTL__tgt_register_lib: {
2198  // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2199  QualType ParamTy =
2201  llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2202  auto *FnTy =
2203  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2204  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2205  break;
2206  }
2208  // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2209  QualType ParamTy =
2211  llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2212  auto *FnTy =
2213  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2214  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2215  break;
2216  }
2218  // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2219  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2220  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2221  CGM.Int32Ty,
2222  CGM.VoidPtrPtrTy,
2223  CGM.VoidPtrPtrTy,
2224  CGM.SizeTy->getPointerTo(),
2225  CGM.Int64Ty->getPointerTo()};
2226  auto *FnTy =
2227  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2228  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2229  break;
2230  }
2232  // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2233  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2234  // *arg_types);
2235  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2236  CGM.Int32Ty,
2237  CGM.VoidPtrPtrTy,
2238  CGM.VoidPtrPtrTy,
2239  CGM.SizeTy->getPointerTo(),
2240  CGM.Int64Ty->getPointerTo()};
2241  auto *FnTy =
2242  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2243  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2244  break;
2245  }
2247  // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2248  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2249  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2250  CGM.Int32Ty,
2251  CGM.VoidPtrPtrTy,
2252  CGM.VoidPtrPtrTy,
2253  CGM.SizeTy->getPointerTo(),
2254  CGM.Int64Ty->getPointerTo()};
2255  auto *FnTy =
2256  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2257  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2258  break;
2259  }
2261  // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2262  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2263  // *arg_types);
2264  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2265  CGM.Int32Ty,
2266  CGM.VoidPtrPtrTy,
2267  CGM.VoidPtrPtrTy,
2268  CGM.SizeTy->getPointerTo(),
2269  CGM.Int64Ty->getPointerTo()};
2270  auto *FnTy =
2271  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2272  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2273  break;
2274  }
2276  // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2277  // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2278  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2279  CGM.Int32Ty,
2280  CGM.VoidPtrPtrTy,
2281  CGM.VoidPtrPtrTy,
2282  CGM.SizeTy->getPointerTo(),
2283  CGM.Int64Ty->getPointerTo()};
2284  auto *FnTy =
2285  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2286  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2287  break;
2288  }
2290  // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2291  // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2292  // *arg_types);
2293  llvm::Type *TypeParams[] = {CGM.Int64Ty,
2294  CGM.Int32Ty,
2295  CGM.VoidPtrPtrTy,
2296  CGM.VoidPtrPtrTy,
2297  CGM.SizeTy->getPointerTo(),
2298  CGM.Int64Ty->getPointerTo()};
2299  auto *FnTy =
2300  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2301  RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2302  break;
2303  }
2304  }
2305  assert(RTLFn && "Unable to find OpenMP runtime function");
2306  return RTLFn;
2307 }
2308 
2309 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2310  bool IVSigned) {
2311  assert((IVSize == 32 || IVSize == 64) &&
2312  "IV size is not compatible with the omp runtime");
2313  StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2314  : "__kmpc_for_static_init_4u")
2315  : (IVSigned ? "__kmpc_for_static_init_8"
2316  : "__kmpc_for_static_init_8u");
2317  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2318  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2319  llvm::Type *TypeParams[] = {
2320  getIdentTyPointerTy(), // loc
2321  CGM.Int32Ty, // tid
2322  CGM.Int32Ty, // schedtype
2323  llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2324  PtrTy, // p_lower
2325  PtrTy, // p_upper
2326  PtrTy, // p_stride
2327  ITy, // incr
2328  ITy // chunk
2329  };
2330  auto *FnTy =
2331  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2332  return CGM.CreateRuntimeFunction(FnTy, Name);
2333 }
2334 
2335 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2336  bool IVSigned) {
2337  assert((IVSize == 32 || IVSize == 64) &&
2338  "IV size is not compatible with the omp runtime");
2339  StringRef Name =
2340  IVSize == 32
2341  ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2342  : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2343  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2344  llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2345  CGM.Int32Ty, // tid
2346  CGM.Int32Ty, // schedtype
2347  ITy, // lower
2348  ITy, // upper
2349  ITy, // stride
2350  ITy // chunk
2351  };
2352  auto *FnTy =
2353  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2354  return CGM.CreateRuntimeFunction(FnTy, Name);
2355 }
2356 
2357 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2358  bool IVSigned) {
2359  assert((IVSize == 32 || IVSize == 64) &&
2360  "IV size is not compatible with the omp runtime");
2361  StringRef Name =
2362  IVSize == 32
2363  ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2364  : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2365  llvm::Type *TypeParams[] = {
2366  getIdentTyPointerTy(), // loc
2367  CGM.Int32Ty, // tid
2368  };
2369  auto *FnTy =
2370  llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2371  return CGM.CreateRuntimeFunction(FnTy, Name);
2372 }
2373 
2374 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2375  bool IVSigned) {
2376  assert((IVSize == 32 || IVSize == 64) &&
2377  "IV size is not compatible with the omp runtime");
2378  StringRef Name =
2379  IVSize == 32
2380  ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2381  : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2382  llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2383  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2384  llvm::Type *TypeParams[] = {
2385  getIdentTyPointerTy(), // loc
2386  CGM.Int32Ty, // tid
2387  llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2388  PtrTy, // p_lower
2389  PtrTy, // p_upper
2390  PtrTy // p_stride
2391  };
2392  auto *FnTy =
2393  llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2394  return CGM.CreateRuntimeFunction(FnTy, Name);
2395 }
2396 
2398  if (CGM.getLangOpts().OpenMPSimd)
2399  return Address::invalid();
2401  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2402  if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2403  SmallString<64> PtrName;
2404  {
2405  llvm::raw_svector_ostream OS(PtrName);
2406  OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2407  }
2408  llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2409  if (!Ptr) {
2410  QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2412  PtrName);
2413  if (!CGM.getLangOpts().OpenMPIsDevice) {
2414  auto *GV = cast<llvm::GlobalVariable>(Ptr);
2415  GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2416  GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2417  }
2418  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2419  registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
2420  }
2421  return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2422  }
2423  return Address::invalid();
2424 }
2425 
2426 llvm::Constant *
2428  assert(!CGM.getLangOpts().OpenMPUseTLS ||
2430  // Lookup the entry, lazily creating it if necessary.
2431  std::string Suffix = getName({"cache", ""});
2433  CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
2434 }
2435 
2437  const VarDecl *VD,
2438  Address VDAddr,
2439  SourceLocation Loc) {
2440  if (CGM.getLangOpts().OpenMPUseTLS &&
2442  return VDAddr;
2443 
2444  llvm::Type *VarTy = VDAddr.getElementType();
2445  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2446  CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2447  CGM.Int8PtrTy),
2450  return Address(CGF.EmitRuntimeCall(
2452  VDAddr.getAlignment());
2453 }
2454 
2456  CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
2457  llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2458  // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2459  // library.
2460  llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
2462  OMPLoc);
2463  // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2464  // to register constructor/destructor for variable.
2465  llvm::Value *Args[] = {
2466  OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2467  Ctor, CopyCtor, Dtor};
2468  CGF.EmitRuntimeCall(
2470 }
2471 
2473  const VarDecl *VD, Address VDAddr, SourceLocation Loc,
2474  bool PerformInit, CodeGenFunction *CGF) {
2475  if (CGM.getLangOpts().OpenMPUseTLS &&
2477  return nullptr;
2478 
2479  VD = VD->getDefinition(CGM.getContext());
2480  if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2481  ThreadPrivateWithDefinition.insert(VD);
2482  QualType ASTTy = VD->getType();
2483 
2484  llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2485  const Expr *Init = VD->getAnyInitializer();
2486  if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2487  // Generate function that re-emits the declaration's initializer into the
2488  // threadprivate copy of the variable VD
2489  CodeGenFunction CtorCGF(CGM);
2490  FunctionArgList Args;
2491  ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2492  /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2494  Args.push_back(&Dst);
2495 
2496  const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2497  CGM.getContext().VoidPtrTy, Args);
2498  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2499  std::string Name = getName({"__kmpc_global_ctor_", ""});
2500  llvm::Function *Fn =
2501  CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2502  CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2503  Args, Loc, Loc);
2504  llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
2505  CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2506  CGM.getContext().VoidPtrTy, Dst.getLocation());
2507  Address Arg = Address(ArgVal, VDAddr.getAlignment());
2508  Arg = CtorCGF.Builder.CreateElementBitCast(
2509  Arg, CtorCGF.ConvertTypeForMem(ASTTy));
2510  CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2511  /*IsInitializer=*/true);
2512  ArgVal = CtorCGF.EmitLoadOfScalar(
2513  CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2514  CGM.getContext().VoidPtrTy, Dst.getLocation());
2515  CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2516  CtorCGF.FinishFunction();
2517  Ctor = Fn;
2518  }
2519  if (VD->getType().isDestructedType() != QualType::DK_none) {
2520  // Generate function that emits destructor call for the threadprivate copy
2521  // of the variable VD
2522  CodeGenFunction DtorCGF(CGM);
2523  FunctionArgList Args;
2524  ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2525  /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2527  Args.push_back(&Dst);
2528 
2529  const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2530  CGM.getContext().VoidTy, Args);
2531  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2532  std::string Name = getName({"__kmpc_global_dtor_", ""});
2533  llvm::Function *Fn =
2534  CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2535  auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2536  DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2537  Loc, Loc);
2538  // Create a scope with an artificial location for the body of this function.
2539  auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2540  llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
2541  DtorCGF.GetAddrOfLocalVar(&Dst),
2542  /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2543  DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
2544  DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2545  DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2546  DtorCGF.FinishFunction();
2547  Dtor = Fn;
2548  }
2549  // Do not emit init function if it is not required.
2550  if (!Ctor && !Dtor)
2551  return nullptr;
2552 
2553  llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2554  auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2555  /*isVarArg=*/false)
2556  ->getPointerTo();
2557  // Copying constructor for the threadprivate variable.
2558  // Must be NULL - reserved by runtime, but currently it requires that this
2559  // parameter is always NULL. Otherwise it fires assertion.
2560  CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2561  if (Ctor == nullptr) {
2562  auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2563  /*isVarArg=*/false)
2564  ->getPointerTo();
2565  Ctor = llvm::Constant::getNullValue(CtorTy);
2566  }
2567  if (Dtor == nullptr) {
2568  auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2569  /*isVarArg=*/false)
2570  ->getPointerTo();
2571  Dtor = llvm::Constant::getNullValue(DtorTy);
2572  }
2573  if (!CGF) {
2574  auto *InitFunctionTy =
2575  llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2576  std::string Name = getName({"__omp_threadprivate_init_", ""});
2577  llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
2578  InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
2579  CodeGenFunction InitCGF(CGM);
2580  FunctionArgList ArgList;
2581  InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2582  CGM.getTypes().arrangeNullaryFunction(), ArgList,
2583  Loc, Loc);
2584  emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2585  InitCGF.FinishFunction();
2586  return InitFunction;
2587  }
2588  emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2589  }
2590  return nullptr;
2591 }
2592 
2593 /// Obtain information that uniquely identifies a target entry. This
2594 /// consists of the file and device IDs as well as line number associated with
2595 /// the relevant entry source location.
2597  unsigned &DeviceID, unsigned &FileID,
2598  unsigned &LineNum) {
2600 
2601  // The loc should be always valid and have a file ID (the user cannot use
2602  // #pragma directives in macros)
2603 
2604  assert(Loc.isValid() && "Source location is expected to be always valid.");
2605 
2606  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2607  assert(PLoc.isValid() && "Source location is expected to be always valid.");
2608 
2609  llvm::sys::fs::UniqueID ID;
2610  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2611  SM.getDiagnostics().Report(diag::err_cannot_open_file)
2612  << PLoc.getFilename() << EC.message();
2613 
2614  DeviceID = ID.getDevice();
2615  FileID = ID.getFile();
2616  LineNum = PLoc.getLine();
2617 }
2618 
2620  llvm::GlobalVariable *Addr,
2621  bool PerformInit) {
2623  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2624  if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2625  return CGM.getLangOpts().OpenMPIsDevice;
2626  VD = VD->getDefinition(CGM.getContext());
2627  if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2628  return CGM.getLangOpts().OpenMPIsDevice;
2629 
2630  QualType ASTTy = VD->getType();
2631 
2633  // Produce the unique prefix to identify the new target regions. We use
2634  // the source location of the variable declaration which we know to not
2635  // conflict with any target region.
2636  unsigned DeviceID;
2637  unsigned FileID;
2638  unsigned Line;
2639  getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2640  SmallString<128> Buffer, Out;
2641  {
2642  llvm::raw_svector_ostream OS(Buffer);
2643  OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2644  << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2645  }
2646 
2647  const Expr *Init = VD->getAnyInitializer();
2648  if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2649  llvm::Constant *Ctor;
2650  llvm::Constant *ID;
2651  if (CGM.getLangOpts().OpenMPIsDevice) {
2652  // Generate function that re-emits the declaration's initializer into
2653  // the threadprivate copy of the variable VD
2654  CodeGenFunction CtorCGF(CGM);
2655 
2657  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2658  llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2659  FTy, Twine(Buffer, "_ctor"), FI, Loc);
2660  auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2661  CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2662  FunctionArgList(), Loc, Loc);
2663  auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2664  CtorCGF.EmitAnyExprToMem(Init,
2665  Address(Addr, CGM.getContext().getDeclAlign(VD)),
2666  Init->getType().getQualifiers(),
2667  /*IsInitializer=*/true);
2668  CtorCGF.FinishFunction();
2669  Ctor = Fn;
2670  ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2671  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
2672  } else {
2673  Ctor = new llvm::GlobalVariable(
2674  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2675  llvm::GlobalValue::PrivateLinkage,
2676  llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2677  ID = Ctor;
2678  }
2679 
2680  // Register the information for the entry associated with the constructor.
2681  Out.clear();
2683  DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
2685  }
2686  if (VD->getType().isDestructedType() != QualType::DK_none) {
2687  llvm::Constant *Dtor;
2688  llvm::Constant *ID;
2689  if (CGM.getLangOpts().OpenMPIsDevice) {
2690  // Generate function that emits destructor call for the threadprivate
2691  // copy of the variable VD
2692  CodeGenFunction DtorCGF(CGM);
2693 
2695  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2696  llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2697  FTy, Twine(Buffer, "_dtor"), FI, Loc);
2698  auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2699  DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2700  FunctionArgList(), Loc, Loc);
2701  // Create a scope with an artificial location for the body of this
2702  // function.
2703  auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2704  DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2705  ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2706  DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2707  DtorCGF.FinishFunction();
2708  Dtor = Fn;
2709  ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2710  CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
2711  } else {
2712  Dtor = new llvm::GlobalVariable(
2713  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2714  llvm::GlobalValue::PrivateLinkage,
2715  llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2716  ID = Dtor;
2717  }
2718  // Register the information for the entry associated with the destructor.
2719  Out.clear();
2721  DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
2723  }
2724  return CGM.getLangOpts().OpenMPIsDevice;
2725 }
2726 
2728  QualType VarType,
2729  StringRef Name) {
2730  std::string Suffix = getName({"artificial", ""});
2731  std::string CacheSuffix = getName({"cache", ""});
2732  llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2733  llvm::Value *GAddr =
2734  getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
2735  llvm::Value *Args[] = {
2737  getThreadID(CGF, SourceLocation()),
2739  CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2740  /*IsSigned=*/false),
2742  CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
2743  return Address(
2745  CGF.EmitRuntimeCall(
2747  VarLVType->getPointerTo(/*AddrSpace=*/0)),
2748  CGM.getPointerAlign());
2749 }
2750 
2752  const RegionCodeGenTy &ThenGen,
2753  const RegionCodeGenTy &ElseGen) {
2754  CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2755 
2756  // If the condition constant folds and can be elided, try to avoid emitting
2757  // the condition and the dead arm of the if/else.
2758  bool CondConstant;
2759  if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2760  if (CondConstant)
2761  ThenGen(CGF);
2762  else
2763  ElseGen(CGF);
2764  return;
2765  }
2766 
2767  // Otherwise, the condition did not fold, or we couldn't elide it. Just
2768  // emit the conditional branch.
2769  llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2770  llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2771  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
2772  CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2773 
2774  // Emit the 'then' code.
2775  CGF.EmitBlock(ThenBlock);
2776  ThenGen(CGF);
2777  CGF.EmitBranch(ContBlock);
2778  // Emit the 'else' code if present.
2779  // There is no need to emit line number for unconditional branch.
2781  CGF.EmitBlock(ElseBlock);
2782  ElseGen(CGF);
2783  // There is no need to emit line number for unconditional branch.
2785  CGF.EmitBranch(ContBlock);
2786  // Emit the continuation block for code after the if.
2787  CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2788 }
2789 
2791  llvm::Value *OutlinedFn,
2792  ArrayRef<llvm::Value *> CapturedVars,
2793  const Expr *IfCond) {
2794  if (!CGF.HaveInsertPoint())
2795  return;
2796  llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2797  auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2798  PrePostActionTy &) {
2799  // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2800  CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2801  llvm::Value *Args[] = {
2802  RTLoc,
2803  CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2804  CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2806  RealArgs.append(std::begin(Args), std::end(Args));
2807  RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2808 
2809  llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
2810  CGF.EmitRuntimeCall(RTLFn, RealArgs);
2811  };
2812  auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2813  PrePostActionTy &) {
2814  CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2815  llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
2816  // Build calls:
2817  // __kmpc_serialized_parallel(&Loc, GTid);
2818  llvm::Value *Args[] = {RTLoc, ThreadID};
2819  CGF.EmitRuntimeCall(
2820  RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
2821 
2822  // OutlinedFn(&GTid, &zero, CapturedStruct);
2823  Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2824  /*Name*/ ".zero.addr");
2825  CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2826  llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2827  // ThreadId for serialized parallels is 0.
2828  OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2829  OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2830  OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2831  RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2832 
2833  // __kmpc_end_serialized_parallel(&Loc, GTid);
2834  llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2835  CGF.EmitRuntimeCall(
2836  RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2837  EndArgs);
2838  };
2839  if (IfCond) {
2840  emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2841  } else {
2842  RegionCodeGenTy ThenRCG(ThenGen);
2843  ThenRCG(CGF);
2844  }
2845 }
2846 
2847 // If we're inside an (outlined) parallel region, use the region info's
2848 // thread-ID variable (it is passed in a first argument of the outlined function
2849 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2850 // regular serial code region, get thread ID by calling kmp_int32
2851 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2852 // return the address of that temp.
2854  SourceLocation Loc) {
2855  if (auto *OMPRegionInfo =
2856  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2857  if (OMPRegionInfo->getThreadIDVariable())
2858  return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2859 
2860  llvm::Value *ThreadID = getThreadID(CGF, Loc);
2861  QualType Int32Ty =
2862  CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2863  Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2864  CGF.EmitStoreOfScalar(ThreadID,
2865  CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2866 
2867  return ThreadIDTemp;
2868 }
2869 
2870 llvm::Constant *
2872  const llvm::Twine &Name) {
2873  SmallString<256> Buffer;
2874  llvm::raw_svector_ostream Out(Buffer);
2875  Out << Name;
2876  StringRef RuntimeName = Out.str();
2877  auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
2878  if (Elem.second) {
2879  assert(Elem.second->getType()->getPointerElementType() == Ty &&
2880  "OMP internal variable has different type than requested");
2881  return &*Elem.second;
2882  }
2883 
2884  return Elem.second = new llvm::GlobalVariable(
2885  CGM.getModule(), Ty, /*IsConstant*/ false,
2886  llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2887  Elem.first());
2888 }
2889 
2891  std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2892  std::string Name = getName({Prefix, "var"});
2893  return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2894 }
2895 
2896 namespace {
2897 /// Common pre(post)-action for different OpenMP constructs.
2898 class CommonActionTy final : public PrePostActionTy {
2899  llvm::Value *EnterCallee;
2900  ArrayRef<llvm::Value *> EnterArgs;
2901  llvm::Value *ExitCallee;
2902  ArrayRef<llvm::Value *> ExitArgs;
2903  bool Conditional;
2904  llvm::BasicBlock *ContBlock = nullptr;
2905 
2906 public:
2907  CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2908  llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2909  bool Conditional = false)
2910  : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2911  ExitArgs(ExitArgs), Conditional(Conditional) {}
2912  void Enter(CodeGenFunction &CGF) override {
2913  llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2914  if (Conditional) {
2915  llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2916  auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2917  ContBlock = CGF.createBasicBlock("omp_if.end");
2918  // Generate the branch (If-stmt)
2919  CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2920  CGF.EmitBlock(ThenBlock);
2921  }
2922  }
2923  void Done(CodeGenFunction &CGF) {
2924  // Emit the rest of blocks/branches
2925  CGF.EmitBranch(ContBlock);
2926  CGF.EmitBlock(ContBlock, true);
2927  }
2928  void Exit(CodeGenFunction &CGF) override {
2929  CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2930  }
2931 };
2932 } // anonymous namespace
2933 
2935  StringRef CriticalName,
2936  const RegionCodeGenTy &CriticalOpGen,
2937  SourceLocation Loc, const Expr *Hint) {
2938  // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2939  // CriticalOpGen();
2940  // __kmpc_end_critical(ident_t *, gtid, Lock);
2941  // Prepare arguments and build a call to __kmpc_critical
2942  if (!CGF.HaveInsertPoint())
2943  return;
2944  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2945  getCriticalRegionLock(CriticalName)};
2946  llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2947  std::end(Args));
2948  if (Hint) {
2949  EnterArgs.push_back(CGF.Builder.CreateIntCast(
2950  CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2951  }
2952  CommonActionTy Action(
2956  CriticalOpGen.setAction(Action);
2957  emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2958 }
2959 
2961  const RegionCodeGenTy &MasterOpGen,
2962  SourceLocation Loc) {
2963  if (!CGF.HaveInsertPoint())
2964  return;
2965  // if(__kmpc_master(ident_t *, gtid)) {
2966  // MasterOpGen();
2967  // __kmpc_end_master(ident_t *, gtid);
2968  // }
2969  // Prepare arguments and build a call to __kmpc_master
2970  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2971  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2973  /*Conditional=*/true);
2974  MasterOpGen.setAction(Action);
2975  emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2976  Action.Done(CGF);
2977 }
2978 
2980  SourceLocation Loc) {
2981  if (!CGF.HaveInsertPoint())
2982  return;
2983  // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2984  llvm::Value *Args[] = {
2985  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2986  llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2988  if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2989  Region->emitUntiedSwitch(CGF);
2990 }
2991 
2993  const RegionCodeGenTy &TaskgroupOpGen,
2994  SourceLocation Loc) {
2995  if (!CGF.HaveInsertPoint())
2996  return;
2997  // __kmpc_taskgroup(ident_t *, gtid);
2998  // TaskgroupOpGen();
2999  // __kmpc_end_taskgroup(ident_t *, gtid);
3000  // Prepare arguments and build a call to __kmpc_taskgroup
3001  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3002  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3004  Args);
3005  TaskgroupOpGen.setAction(Action);
3006  emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
3007 }
3008 
3009 /// Given an array of pointers to variables, project the address of a
3010 /// given variable.
3012  unsigned Index, const VarDecl *Var) {
3013  // Pull out the pointer to the variable.
3014  Address PtrAddr =
3015  CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
3016  llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3017 
3018  Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
3019  Addr = CGF.Builder.CreateElementBitCast(
3020  Addr, CGF.ConvertTypeForMem(Var->getType()));
3021  return Addr;
3022 }
3023 
3025  CodeGenModule &CGM, llvm::Type *ArgsType,
3026  ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
3027  ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3028  SourceLocation Loc) {
3029  ASTContext &C = CGM.getContext();
3030  // void copy_func(void *LHSArg, void *RHSArg);
3031  FunctionArgList Args;
3032  ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3034  ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3036  Args.push_back(&LHSArg);
3037  Args.push_back(&RHSArg);
3038  const auto &CGFI =
3040  std::string Name =
3041  CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3042  auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3044  &CGM.getModule());
3045  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3046  Fn->setDoesNotRecurse();
3047  CodeGenFunction CGF(CGM);
3048  CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3049  // Dest = (void*[n])(LHSArg);
3050  // Src = (void*[n])(RHSArg);
3052  CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3053  ArgsType), CGF.getPointerAlign());
3055  CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3056  ArgsType), CGF.getPointerAlign());
3057  // *(Type0*)Dst[0] = *(Type0*)Src[0];
3058  // *(Type1*)Dst[1] = *(Type1*)Src[1];
3059  // ...
3060  // *(Typen*)Dst[n] = *(Typen*)Src[n];
3061  for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
3062  const auto *DestVar =
3063  cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
3064  Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3065 
3066  const auto *SrcVar =
3067  cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
3068  Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3069 
3070  const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
3071  QualType Type = VD->getType();
3072  CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
3073  }
3074  CGF.FinishFunction();
3075  return Fn;
3076 }
3077 
3079  const RegionCodeGenTy &SingleOpGen,
3080  SourceLocation Loc,
3081  ArrayRef<const Expr *> CopyprivateVars,
3082  ArrayRef<const Expr *> SrcExprs,
3083  ArrayRef<const Expr *> DstExprs,
3084  ArrayRef<const Expr *> AssignmentOps) {
3085  if (!CGF.HaveInsertPoint())
3086  return;
3087  assert(CopyprivateVars.size() == SrcExprs.size() &&
3088  CopyprivateVars.size() == DstExprs.size() &&
3089  CopyprivateVars.size() == AssignmentOps.size());
3090  ASTContext &C = CGM.getContext();
3091  // int32 did_it = 0;
3092  // if(__kmpc_single(ident_t *, gtid)) {
3093  // SingleOpGen();
3094  // __kmpc_end_single(ident_t *, gtid);
3095  // did_it = 1;
3096  // }
3097  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3098  // <copy_func>, did_it);
3099 
3100  Address DidIt = Address::invalid();
3101  if (!CopyprivateVars.empty()) {
3102  // int32 did_it = 0;
3103  QualType KmpInt32Ty =
3104  C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3105  DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
3106  CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
3107  }
3108  // Prepare arguments and build a call to __kmpc_single
3109  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3110  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3112  /*Conditional=*/true);
3113  SingleOpGen.setAction(Action);
3114  emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3115  if (DidIt.isValid()) {
3116  // did_it = 1;
3117  CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3118  }
3119  Action.Done(CGF);
3120  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3121  // <copy_func>, did_it);
3122  if (DidIt.isValid()) {
3123  llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
3124  QualType CopyprivateArrayTy =
3125  C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3126  /*IndexTypeQuals=*/0);
3127  // Create a list of all private variables for copyprivate.
3128  Address CopyprivateList =
3129  CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3130  for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
3131  Address Elem = CGF.Builder.CreateConstArrayGEP(
3132  CopyprivateList, I, CGF.getPointerSize());
3133  CGF.Builder.CreateStore(
3135  CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3136  Elem);
3137  }
3138  // Build function that copies private values from single region to all other
3139  // threads in the corresponding parallel region.
3141  CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
3142  CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
3143  llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
3144  Address CL =
3145  CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3146  CGF.VoidPtrTy);
3147  llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
3148  llvm::Value *Args[] = {
3149  emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3150  getThreadID(CGF, Loc), // i32 <gtid>
3151  BufSize, // size_t <buf_size>
3152  CL.getPointer(), // void *<copyprivate list>
3153  CpyFn, // void (*) (void *, void *) <copy_func>
3154  DidItVal // i32 did_it
3155  };
3157  }
3158 }
3159 
3161  const RegionCodeGenTy &OrderedOpGen,
3162  SourceLocation Loc, bool IsThreads) {
3163  if (!CGF.HaveInsertPoint())
3164  return;
3165  // __kmpc_ordered(ident_t *, gtid);
3166  // OrderedOpGen();
3167  // __kmpc_end_ordered(ident_t *, gtid);
3168  // Prepare arguments and build a call to __kmpc_ordered
3169  if (IsThreads) {
3170  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3171  CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3173  Args);
3174  OrderedOpGen.setAction(Action);
3175  emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3176  return;
3177  }
3178  emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3179 }
3180 
3182  OpenMPDirectiveKind Kind, bool EmitChecks,
3183  bool ForceSimpleCall) {
3184  if (!CGF.HaveInsertPoint())
3185  return;
3186  // Build call __kmpc_cancel_barrier(loc, thread_id);
3187  // Build call __kmpc_barrier(loc, thread_id);
3188  unsigned Flags;
3189  if (Kind == OMPD_for)
3190  Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3191  else if (Kind == OMPD_sections)
3192  Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3193  else if (Kind == OMPD_single)
3194  Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3195  else if (Kind == OMPD_barrier)
3196  Flags = OMP_IDENT_BARRIER_EXPL;
3197  else
3198  Flags = OMP_IDENT_BARRIER_IMPL;
3199  // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3200  // thread_id);
3201  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3202  getThreadID(CGF, Loc)};
3203  if (auto *OMPRegionInfo =
3204  dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
3205  if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
3206  llvm::Value *Result = CGF.EmitRuntimeCall(
3208  if (EmitChecks) {
3209  // if (__kmpc_cancel_barrier()) {
3210  // exit from construct;
3211  // }
3212  llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3213  llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3214  llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
3215  CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3216  CGF.EmitBlock(ExitBB);
3217  // exit from construct;
3218  CodeGenFunction::JumpDest CancelDestination =
3219  CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3220  CGF.EmitBranchThroughCleanup(CancelDestination);
3221  CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3222  }
3223  return;
3224  }
3225  }
3227 }
3228 
3229 /// Map the OpenMP loop schedule to the runtime enumeration.
3231  bool Chunked, bool Ordered) {
3232  switch (ScheduleKind) {
3233  case OMPC_SCHEDULE_static:
3234  return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3235  : (Ordered ? OMP_ord_static : OMP_sch_static);
3236  case OMPC_SCHEDULE_dynamic:
3238  case OMPC_SCHEDULE_guided:
3240  case OMPC_SCHEDULE_runtime:
3241  return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3242  case OMPC_SCHEDULE_auto:
3243  return Ordered ? OMP_ord_auto : OMP_sch_auto;
3244  case OMPC_SCHEDULE_unknown:
3245  assert(!Chunked && "chunk was specified but schedule kind not known");
3246  return Ordered ? OMP_ord_static : OMP_sch_static;
3247  }
3248  llvm_unreachable("Unexpected runtime schedule");
3249 }
3250 
3251 /// Map the OpenMP distribute schedule to the runtime enumeration.
3252 static OpenMPSchedType
3254  // only static is allowed for dist_schedule
3256 }
3257 
3259  bool Chunked) const {
3260  OpenMPSchedType Schedule =
3261  getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3262  return Schedule == OMP_sch_static;
3263 }
3264 
3266  OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3267  OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3268  return Schedule == OMP_dist_sch_static;
3269 }
3270 
3271 
3273  OpenMPSchedType Schedule =
3274  getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
3275  assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3276  return Schedule != OMP_sch_static;
3277 }
3278 
3282  int Modifier = 0;
3283  switch (M1) {
3284  case OMPC_SCHEDULE_MODIFIER_monotonic:
3285  Modifier = OMP_sch_modifier_monotonic;
3286  break;
3287  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3288  Modifier = OMP_sch_modifier_nonmonotonic;
3289  break;
3290  case OMPC_SCHEDULE_MODIFIER_simd:
3291  if (Schedule == OMP_sch_static_chunked)
3293  break;
3296  break;
3297  }
3298  switch (M2) {
3299  case OMPC_SCHEDULE_MODIFIER_monotonic:
3300  Modifier = OMP_sch_modifier_monotonic;
3301  break;
3302  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3303  Modifier = OMP_sch_modifier_nonmonotonic;
3304  break;
3305  case OMPC_SCHEDULE_MODIFIER_simd:
3306  if (Schedule == OMP_sch_static_chunked)
3308  break;
3311  break;
3312  }
3313  return Schedule | Modifier;
3314 }
3315 
3317  CodeGenFunction &CGF, SourceLocation Loc,
3318  const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3319  bool Ordered, const DispatchRTInput &DispatchValues) {
3320  if (!CGF.HaveInsertPoint())
3321  return;
3323  ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
3324  assert(Ordered ||
3325  (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
3326  Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3327  Schedule != OMP_sch_static_balanced_chunked));
3328  // Call __kmpc_dispatch_init(
3329  // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3330  // kmp_int[32|64] lower, kmp_int[32|64] upper,
3331  // kmp_int[32|64] stride, kmp_int[32|64] chunk);
3332 
3333  // If the Chunk was not specified in the clause - use default value 1.
3334  llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3335  : CGF.Builder.getIntN(IVSize, 1);
3336  llvm::Value *Args[] = {
3337  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3338  CGF.Builder.getInt32(addMonoNonMonoModifier(
3339  Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
3340  DispatchValues.LB, // Lower
3341  DispatchValues.UB, // Upper
3342  CGF.Builder.getIntN(IVSize, 1), // Stride
3343  Chunk // Chunk
3344  };
3345  CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3346 }
3347 
3349  CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3350  llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3352  const CGOpenMPRuntime::StaticRTInput &Values) {
3353  if (!CGF.HaveInsertPoint())
3354  return;
3355 
3356  assert(!Values.Ordered);
3357  assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3358  Schedule == OMP_sch_static_balanced_chunked ||
3359  Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3360  Schedule == OMP_dist_sch_static ||
3361  Schedule == OMP_dist_sch_static_chunked);
3362 
3363  // Call __kmpc_for_static_init(
3364  // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3365  // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3366  // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3367  // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3368  llvm::Value *Chunk = Values.Chunk;
3369  if (Chunk == nullptr) {
3370  assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3371  Schedule == OMP_dist_sch_static) &&
3372  "expected static non-chunked schedule");
3373  // If the Chunk was not specified in the clause - use default value 1.
3374  Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3375  } else {
3376  assert((Schedule == OMP_sch_static_chunked ||
3377  Schedule == OMP_sch_static_balanced_chunked ||
3378  Schedule == OMP_ord_static_chunked ||
3379  Schedule == OMP_dist_sch_static_chunked) &&
3380  "expected static chunked schedule");
3381  }
3382  llvm::Value *Args[] = {
3383  UpdateLocation,
3384  ThreadId,
3385  CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3386  M2)), // Schedule type
3387  Values.IL.getPointer(), // &isLastIter
3388  Values.LB.getPointer(), // &LB
3389  Values.UB.getPointer(), // &UB
3390  Values.ST.getPointer(), // &Stride
3391  CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3392  Chunk // Chunk
3393  };
3394  CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3395 }
3396 
3398  SourceLocation Loc,
3399  OpenMPDirectiveKind DKind,
3400  const OpenMPScheduleTy &ScheduleKind,
3401  const StaticRTInput &Values) {
3402  OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3403  ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3404  assert(isOpenMPWorksharingDirective(DKind) &&
3405  "Expected loop-based or sections-based directive.");
3406  llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3407  isOpenMPLoopDirective(DKind)
3408  ? OMP_IDENT_WORK_LOOP
3409  : OMP_IDENT_WORK_SECTIONS);
3410  llvm::Value *ThreadId = getThreadID(CGF, Loc);
3411  llvm::Constant *StaticInitFunction =
3413  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3414  ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
3415 }
3416 
3418  CodeGenFunction &CGF, SourceLocation Loc,
3419  OpenMPDistScheduleClauseKind SchedKind,
3420  const CGOpenMPRuntime::StaticRTInput &Values) {
3421  OpenMPSchedType ScheduleNum =
3422  getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3423  llvm::Value *UpdatedLocation =
3424  emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
3425  llvm::Value *ThreadId = getThreadID(CGF, Loc);
3426  llvm::Constant *StaticInitFunction =
3427  createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3428  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3429  ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3431 }
3432 
3434  SourceLocation Loc,
3435  OpenMPDirectiveKind DKind) {
3436  if (!CGF.HaveInsertPoint())
3437  return;
3438  // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
3439  llvm::Value *Args[] = {
3440  emitUpdateLocation(CGF, Loc,
3442  ? OMP_IDENT_WORK_DISTRIBUTE
3443  : isOpenMPLoopDirective(DKind)
3444  ? OMP_IDENT_WORK_LOOP
3445  : OMP_IDENT_WORK_SECTIONS),
3446  getThreadID(CGF, Loc)};
3448  Args);
3449 }
3450 
3452  SourceLocation Loc,
3453  unsigned IVSize,
3454  bool IVSigned) {
3455  if (!CGF.HaveInsertPoint())
3456  return;
3457  // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
3458  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3459  CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3460 }
3461 
3463  SourceLocation Loc, unsigned IVSize,
3464  bool IVSigned, Address IL,
3465  Address LB, Address UB,
3466  Address ST) {
3467  // Call __kmpc_dispatch_next(
3468  // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3469  // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3470  // kmp_int[32|64] *p_stride);
3471  llvm::Value *Args[] = {
3472  emitUpdateLocation(CGF, Loc),
3473  getThreadID(CGF, Loc),
3474  IL.getPointer(), // &isLastIter
3475  LB.getPointer(), // &Lower
3476  UB.getPointer(), // &Upper
3477  ST.getPointer() // &Stride
3478  };
3479  llvm::Value *Call =
3480  CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3481  return CGF.EmitScalarConversion(
3482  Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
3483  CGF.getContext().BoolTy, Loc);
3484 }
3485 
3487  llvm::Value *NumThreads,
3488  SourceLocation Loc) {
3489  if (!CGF.HaveInsertPoint())
3490  return;
3491  // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3492  llvm::Value *Args[] = {
3493  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3494  CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
3496  Args);
3497 }
3498 
3500  OpenMPProcBindClauseKind ProcBind,
3501  SourceLocation Loc) {
3502  if (!CGF.HaveInsertPoint())
3503  return;
3504  // Constants for proc bind value accepted by the runtime.
3505  enum ProcBindTy {
3506  ProcBindFalse = 0,
3507  ProcBindTrue,
3508  ProcBindMaster,
3509  ProcBindClose,
3510  ProcBindSpread,
3511  ProcBindIntel,
3512  ProcBindDefault
3513  } RuntimeProcBind;
3514  switch (ProcBind) {
3515  case OMPC_PROC_BIND_master:
3516  RuntimeProcBind = ProcBindMaster;
3517  break;
3518  case OMPC_PROC_BIND_close:
3519  RuntimeProcBind = ProcBindClose;
3520  break;
3521  case OMPC_PROC_BIND_spread:
3522  RuntimeProcBind = ProcBindSpread;
3523  break;
3525  llvm_unreachable("Unsupported proc_bind value.");
3526  }
3527  // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3528  llvm::Value *Args[] = {
3529  emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3530  llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3532 }
3533 
3534 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3535  SourceLocation Loc) {
3536  if (!CGF.HaveInsertPoint())
3537  return;
3538  // Build call void __kmpc_flush(ident_t *loc)
3540  emitUpdateLocation(CGF, Loc));
3541 }
3542 
3543 namespace {
3544 /// Indexes of fields for type kmp_task_t.
3546  /// List of shared variables.
3547  KmpTaskTShareds,
3548  /// Task routine.
3549  KmpTaskTRoutine,
3550  /// Partition id for the untied tasks.
3551  KmpTaskTPartId,
3552  /// Function with call of destructors for private variables.
3553  Data1,
3554  /// Task priority.
3555  Data2,
3556  /// (Taskloops only) Lower bound.
3557  KmpTaskTLowerBound,
3558  /// (Taskloops only) Upper bound.
3559  KmpTaskTUpperBound,
3560  /// (Taskloops only) Stride.
3561  KmpTaskTStride,
3562  /// (Taskloops only) Is last iteration flag.
3563  KmpTaskTLastIter,
3564  /// (Taskloops only) Reduction data.
3565  KmpTaskTReductions,
3566 };
3567 } // anonymous namespace
3568 
3569 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3570  return OffloadEntriesTargetRegion.empty() &&
3571  OffloadEntriesDeviceGlobalVar.empty();
3572 }
3573 
3574 /// Initialize target region entry.
3575 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3576  initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3577  StringRef ParentName, unsigned LineNum,
3578  unsigned Order) {
3579  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3580  "only required for the device "
3581  "code generation.");
3582  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
3583  OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3584  OMPTargetRegionEntryTargetRegion);
3585  ++OffloadingEntriesNum;
3586 }
3587 
3588 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3589  registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3590  StringRef ParentName, unsigned LineNum,
3591  llvm::Constant *Addr, llvm::Constant *ID,
3592  OMPTargetRegionEntryKind Flags) {
3593  // If we are emitting code for a target, the entry is already initialized,
3594  // only has to be registered.
3595  if (CGM.getLangOpts().OpenMPIsDevice) {
3596  if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3597  unsigned DiagID = CGM.getDiags().getCustomDiagID(
3599  "Unable to find target region on line '%0' in the device code.");
3600  CGM.getDiags().Report(DiagID) << LineNum;
3601  return;
3602  }
3603  auto &Entry =
3604  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3605  assert(Entry.isValid() && "Entry not initialized!");
3606  Entry.setAddress(Addr);
3607  Entry.setID(ID);
3608  Entry.setFlags(Flags);
3609  } else {
3610  OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
3611  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3612  ++OffloadingEntriesNum;
3613  }
3614 }
3615 
3616 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3617  unsigned DeviceID, unsigned FileID, StringRef ParentName,
3618  unsigned LineNum) const {
3619  auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3620  if (PerDevice == OffloadEntriesTargetRegion.end())
3621  return false;
3622  auto PerFile = PerDevice->second.find(FileID);
3623  if (PerFile == PerDevice->second.end())
3624  return false;
3625  auto PerParentName = PerFile->second.find(ParentName);
3626  if (PerParentName == PerFile->second.end())
3627  return false;
3628  auto PerLine = PerParentName->second.find(LineNum);
3629  if (PerLine == PerParentName->second.end())
3630  return false;
3631  // Fail if this entry is already registered.
3632  if (PerLine->second.getAddress() || PerLine->second.getID())
3633  return false;
3634  return true;
3635 }
3636 
3637 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3638  const OffloadTargetRegionEntryInfoActTy &Action) {
3639  // Scan all target region entries and perform the provided action.
3640  for (const auto &D : OffloadEntriesTargetRegion)
3641  for (const auto &F : D.second)
3642  for (const auto &P : F.second)
3643  for (const auto &L : P.second)
3644  Action(D.first, F.first, P.first(), L.first, L.second);
3645 }
3646 
3647 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3648  initializeDeviceGlobalVarEntryInfo(StringRef Name,
3649  OMPTargetGlobalVarEntryKind Flags,
3650  unsigned Order) {
3651  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3652  "only required for the device "
3653  "code generation.");
3654  OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3655  ++OffloadingEntriesNum;
3656 }
3657 
3658 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3659  registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3660  CharUnits VarSize,
3661  OMPTargetGlobalVarEntryKind Flags,
3662  llvm::GlobalValue::LinkageTypes Linkage) {
3663  if (CGM.getLangOpts().OpenMPIsDevice) {
3664  auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3665  assert(Entry.isValid() && Entry.getFlags() == Flags &&
3666  "Entry not initialized!");
3667  assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3668  "Resetting with the new address.");
3669  if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3670  return;
3671  Entry.setAddress(Addr);
3672  Entry.setVarSize(VarSize);
3673  Entry.setLinkage(Linkage);
3674  } else {
3675  if (hasDeviceGlobalVarEntryInfo(VarName))
3676  return;
3677  OffloadEntriesDeviceGlobalVar.try_emplace(
3678  VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3679  ++OffloadingEntriesNum;
3680  }
3681 }
3682 
3683 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3684  actOnDeviceGlobalVarEntriesInfo(
3685  const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3686  // Scan all target region entries and perform the provided action.
3687  for (const auto &E : OffloadEntriesDeviceGlobalVar)
3688  Action(E.getKey(), E.getValue());
3689 }
3690 
3691 llvm::Function *
3693  // If we don't have entries or if we are emitting code for the device, we
3694  // don't need to do anything.
3695  if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3696  return nullptr;
3697 
3698  llvm::Module &M = CGM.getModule();
3699  ASTContext &C = CGM.getContext();
3700 
3701  // Get list of devices we care about
3702  const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
3703 
3704  // We should be creating an offloading descriptor only if there are devices
3705  // specified.
3706  assert(!Devices.empty() && "No OpenMP offloading devices??");
3707 
3708  // Create the external variables that will point to the begin and end of the
3709  // host entries section. These will be defined by the linker.
3710  llvm::Type *OffloadEntryTy =
3712  std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
3713  auto *HostEntriesBegin = new llvm::GlobalVariable(
3714  M, OffloadEntryTy, /*isConstant=*/true,
3715  llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3716  EntriesBeginName);
3717  std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3718  auto *HostEntriesEnd =
3719  new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3721  /*Initializer=*/nullptr, EntriesEndName);
3722 
3723  // Create all device images
3724  auto *DeviceImageTy = cast<llvm::StructType>(
3726  ConstantInitBuilder DeviceImagesBuilder(CGM);
3727  ConstantArrayBuilder DeviceImagesEntries =
3728  DeviceImagesBuilder.beginArray(DeviceImageTy);
3729 
3730  for (const llvm::Triple &Device : Devices) {
3731  StringRef T = Device.getTriple();
3732  std::string BeginName = getName({"omp_offloading", "img_start", ""});
3733  auto *ImgBegin = new llvm::GlobalVariable(
3734  M, CGM.Int8Ty, /*isConstant=*/true,
3735  llvm::GlobalValue::ExternalWeakLinkage,
3736  /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3737  std::string EndName = getName({"omp_offloading", "img_end", ""});
3738  auto *ImgEnd = new llvm::GlobalVariable(
3739  M, CGM.Int8Ty, /*isConstant=*/true,
3740  llvm::GlobalValue::ExternalWeakLinkage,
3741  /*Initializer=*/nullptr, Twine(EndName).concat(T));
3742 
3743  llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3744  HostEntriesEnd};
3746  DeviceImagesEntries);
3747  }
3748 
3749  // Create device images global array.
3750  std::string ImagesName = getName({"omp_offloading", "device_images"});
3751  llvm::GlobalVariable *DeviceImages =
3752  DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3753  CGM.getPointerAlign(),
3754  /*isConstant=*/true);
3755  DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3756 
3757  // This is a Zero array to be used in the creation of the constant expressions
3758  llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3759  llvm::Constant::getNullValue(CGM.Int32Ty)};
3760 
3761  // Create the target region descriptor.
3762  llvm::Constant *Data[] = {
3763  llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3764  llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3765  DeviceImages, Index),
3766  HostEntriesBegin, HostEntriesEnd};
3767  std::string Descriptor = getName({"omp_offloading", "descriptor"});
3768  llvm::GlobalVariable *Desc = createConstantGlobalStruct(
3769  CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
3770 
3771  // Emit code to register or unregister the descriptor at execution
3772  // startup or closing, respectively.
3773 
3774  llvm::Function *UnRegFn;
3775  {
3776  FunctionArgList Args;
3778  Args.push_back(&DummyPtr);
3779 
3780  CodeGenFunction CGF(CGM);
3781  // Disable debug info for global (de-)initializer because they are not part
3782  // of some particular construct.
3783  CGF.disableDebugInfo();
3784  const auto &FI =
3786  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3787  std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3788  UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
3789  CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3791  Desc);
3792  CGF.FinishFunction();
3793  }
3794  llvm::Function *RegFn;
3795  {
3796  CodeGenFunction CGF(CGM);
3797  // Disable debug info for global (de-)initializer because they are not part
3798  // of some particular construct.
3799  CGF.disableDebugInfo();
3800  const auto &FI = CGM.getTypes().arrangeNullaryFunction();
3801  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3802 
3803  // Encode offload target triples into the registration function name. It
3804  // will serve as a comdat key for the registration/unregistration code for
3805  // this particular combination of offloading targets.
3806  SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3807  RegFnNameParts[0] = "omp_offloading";
3808  RegFnNameParts[1] = "descriptor_reg";
3809  llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3810  [](const llvm::Triple &T) -> const std::string& {
3811  return T.getTriple();
3812  });
3813  llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3814  std::string Descriptor = getName(RegFnNameParts);
3815  RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
3816  CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3818  // Create a variable to drive the registration and unregistration of the
3819  // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3820  ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3821  SourceLocation(), nullptr, C.CharTy,
3823  CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3824  CGF.FinishFunction();
3825  }
3826  if (CGM.supportsCOMDAT()) {
3827  // It is sufficient to call registration function only once, so create a
3828  // COMDAT group for registration/unregistration functions and associated
3829  // data. That would reduce startup time and code size. Registration
3830  // function serves as a COMDAT group key.
3831  llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
3832  RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3833  RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3834  RegFn->setComdat(ComdatKey);
3835  UnRegFn->setComdat(ComdatKey);
3836  DeviceImages->setComdat(ComdatKey);
3837  Desc->setComdat(ComdatKey);
3838  }
3839  return RegFn;
3840 }
3841 
3843  llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3844  llvm::GlobalValue::LinkageTypes Linkage) {
3845  StringRef Name = Addr->getName();
3846  llvm::Module &M = CGM.getModule();
3847  llvm::LLVMContext &C = M.getContext();
3848 
3849  // Create constant string with the name.
3850  llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3851 
3852  std::string StringName = getName({"omp_offloading", "entry_name"});
3853  auto *Str = new llvm::GlobalVariable(
3854  M, StrPtrInit->getType(), /*isConstant=*/true,
3855  llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
3856  Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3857 
3858  llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3859  llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3860  llvm::ConstantInt::get(CGM.SizeTy, Size),
3861  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3862  llvm::ConstantInt::get(CGM.Int32Ty, 0)};
3863  std::string EntryName = getName({"omp_offloading", "entry", ""});
3864  llvm::GlobalVariable *Entry = createConstantGlobalStruct(
3865  CGM, getTgtOffloadEntryQTy(), Data, Twine(EntryName).concat(Name),
3866  llvm::GlobalValue::WeakAnyLinkage);
3867 
3868  // The entry has to be created in the section the linker expects it to be.
3869  std::string Section = getName({"omp_offloading", "entries"});
3870  Entry->setSection(Section);
3871 }
3872 
3874  // Emit the offloading entries and metadata so that the device codegen side
3875  // can easily figure out what to emit. The produced metadata looks like
3876  // this:
3877  //
3878  // !omp_offload.info = !{!1, ...}
3879  //
3880  // Right now we only generate metadata for function that contain target
3881  // regions.
3882 
3883  // If we do not have entries, we don't need to do anything.
3885  return;
3886 
3887  llvm::Module &M = CGM.getModule();
3888  llvm::LLVMContext &C = M.getContext();
3890  OrderedEntries(OffloadEntriesInfoManager.size());
3891 
3892  // Auxiliary methods to create metadata values and strings.
3893  auto &&GetMDInt = [this](unsigned V) {
3894  return llvm::ConstantAsMetadata::get(
3895  llvm::ConstantInt::get(CGM.Int32Ty, V));
3896  };
3897 
3898  auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3899 
3900  // Create the offloading info metadata node.
3901  llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3902 
3903  // Create function that emits metadata for each target region entry;
3904  auto &&TargetRegionMetadataEmitter =
3905  [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3906  unsigned DeviceID, unsigned FileID, StringRef ParentName,
3907  unsigned Line,
3909  // Generate metadata for target regions. Each entry of this metadata
3910  // contains:
3911  // - Entry 0 -> Kind of this type of metadata (0).
3912  // - Entry 1 -> Device ID of the file where the entry was identified.
3913  // - Entry 2 -> File ID of the file where the entry was identified.
3914  // - Entry 3 -> Mangled name of the function where the entry was
3915  // identified.
3916  // - Entry 4 -> Line in the file where the entry was identified.
3917  // - Entry 5 -> Order the entry was created.
3918  // The first element of the metadata node is the kind.
3919  llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3920  GetMDInt(FileID), GetMDString(ParentName),
3921  GetMDInt(Line), GetMDInt(E.getOrder())};
3922 
3923  // Save this entry in the right position of the ordered entries array.
3924  OrderedEntries[E.getOrder()] = &E;
3925 
3926  // Add metadata to the named metadata node.
3927  MD->addOperand(llvm::MDNode::get(C, Ops));
3928  };
3929 
3931  TargetRegionMetadataEmitter);
3932 
3933  // Create function that emits metadata for each device global variable entry;
3934  auto &&DeviceGlobalVarMetadataEmitter =
3935  [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3936  MD](StringRef MangledName,
3938  &E) {
3939  // Generate metadata for global variables. Each entry of this metadata
3940  // contains:
3941  // - Entry 0 -> Kind of this type of metadata (1).
3942  // - Entry 1 -> Mangled name of the variable.
3943  // - Entry 2 -> Declare target kind.
3944  // - Entry 3 -> Order the entry was created.
3945  // The first element of the metadata node is the kind.
3946  llvm::Metadata *Ops[] = {
3947  GetMDInt(E.getKind()), GetMDString(MangledName),
3948  GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3949 
3950  // Save this entry in the right position of the ordered entries array.
3951  OrderedEntries[E.getOrder()] = &E;
3952 
3953  // Add metadata to the named metadata node.
3954  MD->addOperand(llvm::MDNode::get(C, Ops));
3955  };
3956 
3958  DeviceGlobalVarMetadataEmitter);
3959 
3960  for (const auto *E : OrderedEntries) {
3961  assert(E && "All ordered entries must exist!");
3962  if (const auto *CE =
3963  dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3964  E)) {
3965  if (!CE->getID() || !CE->getAddress()) {
3966  unsigned DiagID = CGM.getDiags().getCustomDiagID(
3968  "Offloading entry for target region is incorrect: either the "
3969  "address or the ID is invalid.");
3970  CGM.getDiags().Report(DiagID);
3971  continue;
3972  }
3973  createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
3974  CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3975  } else if (const auto *CE =
3976  dyn_cast<OffloadEntriesInfoManagerTy::
3977  OffloadEntryInfoDeviceGlobalVar>(E)) {
3980  CE->getFlags());
3981  switch (Flags) {
3983  if (!CE->getAddress()) {
3984  unsigned DiagID = CGM.getDiags().getCustomDiagID(
3986  "Offloading entry for declare target variable is incorrect: the "
3987  "address is invalid.");
3988  CGM.getDiags().Report(DiagID);
3989  continue;
3990  }
3991  break;
3992  }
3994  assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
3995  (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
3996  "Declaret target link address is set.");
3997  if (CGM.getLangOpts().OpenMPIsDevice)
3998  continue;
3999  if (!CE->getAddress()) {
4000  unsigned DiagID = CGM.getDiags().getCustomDiagID(
4002  "Offloading entry for declare target variable is incorrect: the "
4003  "address is invalid.");
4004  CGM.getDiags().Report(DiagID);
4005  continue;
4006  }
4007  break;
4008  }
4009  createOffloadEntry(CE->getAddress(), CE->getAddress(),
4010  CE->getVarSize().getQuantity(), Flags,
4011  CE->getLinkage());
4012  } else {
4013  llvm_unreachable("Unsupported entry kind.");
4014  }
4015  }
4016 }
4017 
4018 /// Loads all the offload entries information from the host IR
4019 /// metadata.
4021  // If we are in target mode, load the metadata from the host IR. This code has
4022  // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4023 
4024  if (!CGM.getLangOpts().OpenMPIsDevice)
4025  return;
4026 
4027  if (CGM.getLangOpts().OMPHostIRFile.empty())
4028  return;
4029 
4030  auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
4031  if (auto EC = Buf.getError()) {
4032  CGM.getDiags().Report(diag::err_cannot_open_file)
4033  << CGM.getLangOpts().OMPHostIRFile << EC.message();
4034  return;
4035  }
4036 
4037  llvm::LLVMContext C;
4038  auto ME = expectedToErrorOrAndEmitErrors(
4039  C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
4040 
4041  if (auto EC = ME.getError()) {
4042  unsigned DiagID = CGM.getDiags().getCustomDiagID(
4043  DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4044  CGM.getDiags().Report(DiagID)
4045  << CGM.getLangOpts().OMPHostIRFile << EC.message();
4046  return;
4047  }
4048 
4049  llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4050  if (!MD)
4051  return;
4052 
4053  for (llvm::MDNode *MN : MD->operands()) {
4054  auto &&GetMDInt = [MN](unsigned Idx) {
4055  auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
4056  return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4057  };
4058 
4059  auto &&GetMDString = [MN](unsigned Idx) {
4060  auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
4061  return V->getString();
4062  };
4063 
4064  switch (GetMDInt(0)) {
4065  default:
4066  llvm_unreachable("Unexpected metadata!");
4067  break;
4071  /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4072  /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4073  /*Order=*/GetMDInt(5));
4074  break;
4078  /*MangledName=*/GetMDString(1),
4079  static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4080  /*Flags=*/GetMDInt(2)),
4081  /*Order=*/GetMDInt(3));
4082  break;
4083  }
4084  }
4085 }
4086 
4088  if (!KmpRoutineEntryPtrTy) {
4089  // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
4090  ASTContext &C = CGM.getContext();
4091  QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4093  KmpRoutineEntryPtrQTy = C.getPointerType(
4094  C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4095  KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4096  }
4097 }
4098 
4100  // Make sure the type of the entry is already created. This is the type we
4101  // have to create:
4102  // struct __tgt_offload_entry{
4103  // void *addr; // Pointer to the offload entry info.
4104  // // (function or global)
4105  // char *name; // Name of the function or global.
4106  // size_t size; // Size of the entry info (0 if it a function).
4107  // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4108  // int32_t reserved; // Reserved, to use by the runtime library.
4109  // };
4110  if (TgtOffloadEntryQTy.isNull()) {
4111  ASTContext &C = CGM.getContext();
4112  RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
4113  RD->startDefinition();
4114  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4116  addFieldToRecordDecl(C, RD, C.getSizeType());
4118  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4120  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4121  RD->completeDefinition();
4122  RD->addAttr(PackedAttr::CreateImplicit(C));
4124  }
4125  return TgtOffloadEntryQTy;
4126 }
4127 
4129  // These are the types we need to build:
4130  // struct __tgt_device_image{
4131  // void *ImageStart; // Pointer to the target code start.
4132  // void *ImageEnd; // Pointer to the target code end.
4133  // // We also add the host entries to the device image, as it may be useful
4134  // // for the target runtime to have access to that information.
4135  // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4136  // // the entries.
4137  // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4138  // // entries (non inclusive).
4139  // };
4140  if (TgtDeviceImageQTy.isNull()) {
4141  ASTContext &C = CGM.getContext();
4142  RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
4143  RD->startDefinition();
4144  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4145  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4148  RD->completeDefinition();
4150  }
4151  return TgtDeviceImageQTy;
4152 }
4153 
4155  // struct __tgt_bin_desc{
4156  // int32_t NumDevices; // Number of devices supported.
4157  // __tgt_device_image *DeviceImages; // Arrays of device images
4158  // // (one per device).
4159  // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4160  // // entries.
4161  // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4162  // // entries (non inclusive).
4163  // };
4165  ASTContext &C = CGM.getContext();
4166  RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
4167  RD->startDefinition();
4169  C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4173  RD->completeDefinition();
4175  }
4176  return TgtBinaryDescriptorQTy;
4177 }
4178 
4179 namespace {
4180 struct PrivateHelpersTy {
4181  PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4182  const VarDecl *PrivateElemInit)
4183  : Original(Original), PrivateCopy(PrivateCopy),
4184  PrivateElemInit(PrivateElemInit) {}
4185  const VarDecl *Original;
4186  const VarDecl *PrivateCopy;
4187  const VarDecl *PrivateElemInit;
4188 };
4189 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
4190 } // anonymous namespace
4191 
4192 static RecordDecl *
4194  if (!Privates.empty()) {
4195  ASTContext &C = CGM.getContext();
4196  // Build struct .kmp_privates_t. {
4197  // /* private vars */
4198  // };
4199  RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
4200  RD->startDefinition();
4201  for (const auto &Pair : Privates) {
4202  const VarDecl *VD = Pair.second.Original;
4203  QualType Type = VD->getType().getNonReferenceType();
4204  FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
4205  if (VD->hasAttrs()) {
4206  for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4207  E(VD->getAttrs().end());
4208  I != E; ++I)
4209  FD->addAttr(*I);
4210  }
4211  }
4212  RD->completeDefinition();
4213  return RD;
4214  }
4215  return nullptr;
4216 }
4217 
4218 static RecordDecl *
4220  QualType KmpInt32Ty,
4221  QualType KmpRoutineEntryPointerQTy) {
4222  ASTContext &C = CGM.getContext();
4223  // Build struct kmp_task_t {
4224  // void * shareds;
4225  // kmp_routine_entry_t routine;
4226  // kmp_int32 part_id;
4227  // kmp_cmplrdata_t data1;
4228  // kmp_cmplrdata_t data2;
4229  // For taskloops additional fields:
4230  // kmp_uint64 lb;
4231  // kmp_uint64 ub;
4232  // kmp_int64 st;
4233  // kmp_int32 liter;
4234  // void * reductions;
4235  // };
4236  RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
4237  UD->startDefinition();
4238  addFieldToRecordDecl(C, UD, KmpInt32Ty);
4239  addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4240  UD->completeDefinition();
4241  QualType KmpCmplrdataTy = C.getRecordType(UD);
4242  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
4243  RD->startDefinition();
4244  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4245  addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4246  addFieldToRecordDecl(C, RD, KmpInt32Ty);
4247  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4248  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4249  if (isOpenMPTaskLoopDirective(Kind)) {
4250  QualType KmpUInt64Ty =
4251  CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4252  QualType KmpInt64Ty =
4253  CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4254  addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4255  addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4256  addFieldToRecordDecl(C, RD, KmpInt64Ty);
4257  addFieldToRecordDecl(C, RD, KmpInt32Ty);
4258  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4259  }
4260  RD->completeDefinition();
4261  return RD;
4262 }
4263 
4264 static RecordDecl *
4266  ArrayRef<PrivateDataTy> Privates) {
4267  ASTContext &C = CGM.getContext();
4268  // Build struct kmp_task_t_with_privates {
4269  // kmp_task_t task_data;
4270  // .kmp_privates_t. privates;
4271  // };
4272  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
4273  RD->startDefinition();
4274  addFieldToRecordDecl(C, RD, KmpTaskTQTy);
4275  if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
4276  addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
4277  RD->completeDefinition();
4278  return RD;
4279 }
4280 
4281 /// Emit a proxy function which accepts kmp_task_t as the second
4282 /// argument.
4283 /// \code
4284 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
4285 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
4286 /// For taskloops:
4287 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4288 /// tt->reductions, tt->shareds);
4289 /// return 0;
4290 /// }
4291 /// \endcode
4292 static llvm::Value *
4294  OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4295  QualType KmpTaskTWithPrivatesPtrQTy,
4296  QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
4297  QualType SharedsPtrTy, llvm::Value *TaskFunction,
4298  llvm::Value *TaskPrivatesMap) {
4299  ASTContext &C = CGM.getContext();
4300  FunctionArgList Args;
4301  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4303  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4304  KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4306  Args.push_back(&GtidArg);
4307  Args.push_back(&TaskTypeArg);
4308  const auto &TaskEntryFnInfo =
4309  CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4310  llvm::FunctionType *TaskEntryTy =
4311  CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
4312  std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4313  auto *TaskEntry = llvm::Function::Create(
4314  TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
4315  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
4316  TaskEntry->setDoesNotRecurse();
4317  CodeGenFunction CGF(CGM);
4318  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4319  Loc, Loc);
4320 
4321  // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
4322  // tt,
4323  // For taskloops:
4324  // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4325  // tt->task_data.shareds);
4326  llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
4327  CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
4328  LValue TDBase = CGF.EmitLoadOfPointerLValue(
4329  CGF.GetAddrOfLocalVar(&TaskTypeArg),
4330  KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4331  const auto *KmpTaskTWithPrivatesQTyRD =
4332  cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4333  LValue Base =
4334  CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4335  const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4336  auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4337  LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4338  llvm::Value *PartidParam = PartIdLVal.getPointer();
4339 
4340  auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4341  LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4343  CGF.EmitLoadOfScalar(SharedsLVal, Loc),
4344  CGF.ConvertTypeForMem(SharedsPtrTy));
4345 
4346  auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4347  llvm::Value *PrivatesParam;
4348  if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4349  LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4350  PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4351  PrivatesLVal.getPointer(), CGF.VoidPtrTy);
4352  } else {
4353  PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4354  }
4355 
4356  llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4357  TaskPrivatesMap,
4358  CGF.Builder
4360  TDBase.getAddress(), CGF.VoidPtrTy)
4361  .getPointer()};
4362  SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4363  std::end(CommonArgs));
4364  if (isOpenMPTaskLoopDirective(Kind)) {
4365  auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4366  LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4367  llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
4368  auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4369  LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4370  llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
4371  auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4372  LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4373  llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
4374  auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4375  LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4376  llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
4377  auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4378  LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4379  llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
4380  CallArgs.push_back(LBParam);
4381  CallArgs.push_back(UBParam);
4382  CallArgs.push_back(StParam);
4383  CallArgs.push_back(LIParam);
4384  CallArgs.push_back(RParam);
4385  }
4386  CallArgs.push_back(SharedsParam);
4387 
4388  CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4389  CallArgs);
4390  CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4391  CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
4392  CGF.FinishFunction();
4393  return TaskEntry;
4394 }
4395 
4397  SourceLocation Loc,
4398  QualType KmpInt32Ty,
4399  QualType KmpTaskTWithPrivatesPtrQTy,
4400  QualType KmpTaskTWithPrivatesQTy) {
4401  ASTContext &C = CGM.getContext();
4402  FunctionArgList Args;
4403  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4405  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4406  KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4408  Args.push_back(&GtidArg);
4409  Args.push_back(&TaskTypeArg);
4410  const auto &DestructorFnInfo =
4411  CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4412  llvm::FunctionType *DestructorFnTy =
4413  CGM.getTypes().GetFunctionType(DestructorFnInfo);
4414  std::string Name =
4415  CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
4416  auto *DestructorFn =
4418  Name, &CGM.getModule());
4419  CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
4420  DestructorFnInfo);
4421  DestructorFn->setDoesNotRecurse();
4422  CodeGenFunction CGF(CGM);
4423  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4424  Args, Loc, Loc);
4425 
4427  CGF.GetAddrOfLocalVar(&TaskTypeArg),
4428  KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4429  const auto *KmpTaskTWithPrivatesQTyRD =
4430  cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4431  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4432  Base = CGF.EmitLValueForField(Base, *FI);
4433  for (const auto *Field :
4434  cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4435  if (QualType::DestructionKind DtorKind =
4436  Field->getType().isDestructedType()) {
4437  LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
4438  CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4439  }
4440  }
4441  CGF.FinishFunction();
4442  return DestructorFn;
4443 }
4444 
4445 /// Emit a privates mapping function for correct handling of private and
4446 /// firstprivate variables.
4447 /// \code
4448 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4449 /// **noalias priv1,..., <tyn> **noalias privn) {
4450 /// *priv1 = &.privates.priv1;
4451 /// ...;
4452 /// *privn = &.privates.privn;
4453 /// }
4454 /// \endcode
4455 static llvm::Value *
4457  ArrayRef<const Expr *> PrivateVars,
4458  ArrayRef<const Expr *> FirstprivateVars,
4459  ArrayRef<const Expr *> LastprivateVars,
4460  QualType PrivatesQTy,
4461  ArrayRef<PrivateDataTy> Privates) {
4462  ASTContext &C = CGM.getContext();
4463  FunctionArgList Args;
4464  ImplicitParamDecl TaskPrivatesArg(
4465  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4466  C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4468  Args.push_back(&TaskPrivatesArg);
4469  llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4470  unsigned Counter = 1;
4471  for (const Expr *E : PrivateVars) {
4472  Args.push_back(ImplicitParamDecl::Create(
4473  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4475  .withConst()
4476  .withRestrict(),
4478  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4479  PrivateVarsPos[VD] = Counter;
4480  ++Counter;
4481  }
4482  for (const Expr *E : FirstprivateVars) {
4483  Args.push_back(ImplicitParamDecl::Create(
4484  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4486  .withConst()
4487  .withRestrict(),
4489  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4490  PrivateVarsPos[VD] = Counter;
4491  ++Counter;
4492  }
4493  for (const Expr *E : LastprivateVars) {
4494  Args.push_back(ImplicitParamDecl::Create(
4495  C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4497  .withConst()
4498  .withRestrict(),
4500  const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4501  PrivateVarsPos[VD] = Counter;
4502  ++Counter;
4503  }
4504  const auto &TaskPrivatesMapFnInfo =
4506  llvm::FunctionType *TaskPrivatesMapTy =
4507  CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4508  std::string Name =
4509  CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
4510  auto *TaskPrivatesMap = llvm::Function::Create(
4511  TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4512  &CGM.getModule());
4513  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
4514  TaskPrivatesMapFnInfo);
4515  TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
4516  TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
4517  TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
4518  CodeGenFunction CGF(CGM);
4519  CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4520  TaskPrivatesMapFnInfo, Args, Loc, Loc);
4521 
4522  // *privi = &.privates.privi;
4524  CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4525  TaskPrivatesArg.getType()->castAs<PointerType>());
4526  const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4527  Counter = 0;
4528  for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4529  LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4530  const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4531  LValue RefLVal =
4532  CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4533  LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4534  RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
4535  CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
4536  ++Counter;
4537  }
4538  CGF.FinishFunction();
4539  return TaskPrivatesMap;
4540 }
4541 
4542 static bool stable_sort_comparator(const PrivateDataTy P1,
4543  const PrivateDataTy P2) {
4544  return P1.first > P2.first;
4545 }
4546 
4547 /// Emit initialization for private variables in task-based directives.
4549  const OMPExecutableDirective &D,
4550  Address KmpTaskSharedsPtr, LValue TDBase,
4551  const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4552  QualType SharedsTy, QualType SharedsPtrTy,
4553  const OMPTaskDataTy &Data,
4554  ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4555  ASTContext &C = CGF.getContext();
4556  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4557  LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4559  ? OMPD_taskloop
4560  : OMPD_task;
4561  const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4562  CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
4563  LValue SrcBase;
4564  bool IsTargetTask =
4567  // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4568  // PointersArray and SizesArray. The original variables for these arrays are
4569  // not captured and we get their addresses explicitly.
4570  if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4571  (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
4572  SrcBase = CGF.MakeAddrLValue(
4574  KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4575  SharedsTy);
4576  }
4577  FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4578  for (const PrivateDataTy &Pair : Privates) {
4579  const VarDecl *VD = Pair.second.PrivateCopy;
4580  const Expr *Init = VD->getAnyInitializer();
4581  if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4582  !CGF.isTrivialInitializer(Init)))) {
4583  LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
4584  if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4585  const VarDecl *OriginalVD = Pair.second.Original;
4586  // Check if the variable is the target-based BasePointersArray,
4587  // PointersArray or SizesArray.
4588  LValue SharedRefLValue;
4589  QualType Type = OriginalVD->getType();
4590  const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
4591  if (IsTargetTask && !SharedField) {
4592  assert(isa<ImplicitParamDecl>(OriginalVD) &&
4593  isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4594  cast<CapturedDecl>(OriginalVD->getDeclContext())
4595  ->getNumParams() == 0 &&
4596  isa<TranslationUnitDecl>(
4597  cast<CapturedDecl>(OriginalVD->getDeclContext())
4598  ->getDeclContext()) &&
4599  "Expected artificial target data variable.");
4600  SharedRefLValue =
4601  CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4602  } else {
4603  SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4604  SharedRefLValue = CGF.MakeAddrLValue(
4605  Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4606  SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4607  SharedRefLValue.getTBAAInfo());
4608  }
4609  if (Type->isArrayType()) {
4610  // Initialize firstprivate array.
4611  if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4612  // Perform simple memcpy.
4613  CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
4614  } else {
4615  // Initialize firstprivate array using element-by-element
4616  // initialization.
4618  PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4619  [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4620  Address SrcElement) {
4621  // Clean up any temporaries needed by the initialization.
4622  CodeGenFunction::OMPPrivateScope InitScope(CGF);
4623  InitScope.addPrivate(
4624  Elem, [SrcElement]() -> Address { return SrcElement; });
4625  (void)InitScope.Privatize();
4626  // Emit initialization for single element.
4628  CGF, &CapturesInfo);
4629  CGF.EmitAnyExprToMem(Init, DestElement,
4630  Init->getType().getQualifiers(),
4631  /*IsInitializer=*/false);
4632  });
4633  }
4634  } else {
4635  CodeGenFunction::OMPPrivateScope InitScope(CGF);
4636  InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4637  return SharedRefLValue.getAddress();
4638  });
4639  (void)InitScope.Privatize();