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 "CodeGenFunction.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/StmtOpenMP.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cassert>
29 
30 using namespace clang;
31 using namespace CodeGen;
32 
33 namespace {
34 /// \brief Base class for handling code generation inside OpenMP regions.
35 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36 public:
37   /// \brief Kinds of OpenMP regions used in codegen.
38   enum CGOpenMPRegionKind {
39     /// \brief Region with outlined function for standalone 'parallel'
40     /// directive.
41     ParallelOutlinedRegion,
42     /// \brief Region with outlined function for standalone 'task' directive.
43     TaskOutlinedRegion,
44     /// \brief Region for constructs that do not require function outlining,
45     /// like 'for', 'sections', 'atomic' etc. directives.
46     InlinedRegion,
47     /// \brief Region with outlined function for standalone 'target' directive.
48     TargetRegion,
49   };
50 
51   CGOpenMPRegionInfo(const CapturedStmt &CS,
52                      const CGOpenMPRegionKind RegionKind,
53                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54                      bool HasCancel)
55       : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
56         CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
57 
58   CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
59                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60                      bool HasCancel)
61       : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
62         Kind(Kind), HasCancel(HasCancel) {}
63 
64   /// \brief Get a variable or parameter for storing global thread id
65   /// inside OpenMP construct.
66   virtual const VarDecl *getThreadIDVariable() const = 0;
67 
68   /// \brief Emit the captured statement body.
69   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
70 
71   /// \brief Get an LValue for the current ThreadID variable.
72   /// \return LValue for thread id variable. This LValue always has type int32*.
73   virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
74 
75   CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
76 
77   OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
78 
79   bool hasCancel() const { return HasCancel; }
80 
81   static bool classof(const CGCapturedStmtInfo *Info) {
82     return Info->getKind() == CR_OpenMP;
83   }
84 
85 protected:
86   CGOpenMPRegionKind RegionKind;
87   RegionCodeGenTy CodeGen;
88   OpenMPDirectiveKind Kind;
89   bool HasCancel;
90 };
91 
92 /// \brief API for captured statement code generation in OpenMP constructs.
93 class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
94 public:
95   CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
96                              const RegionCodeGenTy &CodeGen,
97                              OpenMPDirectiveKind Kind, bool HasCancel)
98       : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
99                            HasCancel),
100         ThreadIDVar(ThreadIDVar) {
101     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
102   }
103 
104   /// \brief Get a variable or parameter for storing global thread id
105   /// inside OpenMP construct.
106   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
107 
108   /// \brief Get the name of the capture helper.
109   StringRef getHelperName() const override { return ".omp_outlined."; }
110 
111   static bool classof(const CGCapturedStmtInfo *Info) {
112     return CGOpenMPRegionInfo::classof(Info) &&
113            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
114                ParallelOutlinedRegion;
115   }
116 
117 private:
118   /// \brief A variable or parameter storing global thread id for OpenMP
119   /// constructs.
120   const VarDecl *ThreadIDVar;
121 };
122 
123 /// \brief API for captured statement code generation in OpenMP constructs.
124 class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
125 public:
126   CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
127                                  const VarDecl *ThreadIDVar,
128                                  const RegionCodeGenTy &CodeGen,
129                                  OpenMPDirectiveKind Kind, bool HasCancel)
130       : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
131         ThreadIDVar(ThreadIDVar) {
132     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
133   }
134 
135   /// \brief Get a variable or parameter for storing global thread id
136   /// inside OpenMP construct.
137   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
138 
139   /// \brief Get an LValue for the current ThreadID variable.
140   LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
141 
142   /// \brief Get the name of the capture helper.
143   StringRef getHelperName() const override { return ".omp_outlined."; }
144 
145   static bool classof(const CGCapturedStmtInfo *Info) {
146     return CGOpenMPRegionInfo::classof(Info) &&
147            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
148                TaskOutlinedRegion;
149   }
150 
151 private:
152   /// \brief A variable or parameter storing global thread id for OpenMP
153   /// constructs.
154   const VarDecl *ThreadIDVar;
155 };
156 
157 /// \brief API for inlined captured statement code generation in OpenMP
158 /// constructs.
159 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
160 public:
161   CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
162                             const RegionCodeGenTy &CodeGen,
163                             OpenMPDirectiveKind Kind, bool HasCancel)
164       : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
165         OldCSI(OldCSI),
166         OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
167 
168   // \brief Retrieve the value of the context parameter.
169   llvm::Value *getContextValue() const override {
170     if (OuterRegionInfo)
171       return OuterRegionInfo->getContextValue();
172     llvm_unreachable("No context value for inlined OpenMP region");
173   }
174 
175   void setContextValue(llvm::Value *V) override {
176     if (OuterRegionInfo) {
177       OuterRegionInfo->setContextValue(V);
178       return;
179     }
180     llvm_unreachable("No context value for inlined OpenMP region");
181   }
182 
183   /// \brief Lookup the captured field decl for a variable.
184   const FieldDecl *lookup(const VarDecl *VD) const override {
185     if (OuterRegionInfo)
186       return OuterRegionInfo->lookup(VD);
187     // If there is no outer outlined region,no need to lookup in a list of
188     // captured variables, we can use the original one.
189     return nullptr;
190   }
191 
192   FieldDecl *getThisFieldDecl() const override {
193     if (OuterRegionInfo)
194       return OuterRegionInfo->getThisFieldDecl();
195     return nullptr;
196   }
197 
198   /// \brief Get a variable or parameter for storing global thread id
199   /// inside OpenMP construct.
200   const VarDecl *getThreadIDVariable() const override {
201     if (OuterRegionInfo)
202       return OuterRegionInfo->getThreadIDVariable();
203     return nullptr;
204   }
205 
206   /// \brief Get the name of the capture helper.
207   StringRef getHelperName() const override {
208     if (auto *OuterRegionInfo = getOldCSI())
209       return OuterRegionInfo->getHelperName();
210     llvm_unreachable("No helper name for inlined OpenMP construct");
211   }
212 
213   CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
214 
215   static bool classof(const CGCapturedStmtInfo *Info) {
216     return CGOpenMPRegionInfo::classof(Info) &&
217            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
218   }
219 
220 private:
221   /// \brief CodeGen info about outer OpenMP region.
222   CodeGenFunction::CGCapturedStmtInfo *OldCSI;
223   CGOpenMPRegionInfo *OuterRegionInfo;
224 };
225 
226 /// \brief API for captured statement code generation in OpenMP target
227 /// constructs. For this captures, implicit parameters are used instead of the
228 /// captured fields. The name of the target region has to be unique in a given
229 /// application so it is provided by the client, because only the client has
230 /// the information to generate that.
231 class CGOpenMPTargetRegionInfo : public CGOpenMPRegionInfo {
232 public:
233   CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
234                            const RegionCodeGenTy &CodeGen, StringRef HelperName)
235       : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
236                            /*HasCancel=*/false),
237         HelperName(HelperName) {}
238 
239   /// \brief This is unused for target regions because each starts executing
240   /// with a single thread.
241   const VarDecl *getThreadIDVariable() const override { return nullptr; }
242 
243   /// \brief Get the name of the capture helper.
244   StringRef getHelperName() const override { return HelperName; }
245 
246   static bool classof(const CGCapturedStmtInfo *Info) {
247     return CGOpenMPRegionInfo::classof(Info) &&
248            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
249   }
250 
251 private:
252   StringRef HelperName;
253 };
254 
255 static void EmptyCodeGen(CodeGenFunction &) {
256   llvm_unreachable("No codegen for expressions");
257 }
258 /// \brief API for generation of expressions captured in a innermost OpenMP
259 /// region.
260 class CGOpenMPInnerExprInfo : public CGOpenMPInlinedRegionInfo {
261 public:
262   CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
263       : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
264                                   OMPD_unknown,
265                                   /*HasCancel=*/false),
266         PrivScope(CGF) {
267     // Make sure the globals captured in the provided statement are local by
268     // using the privatization logic. We assume the same variable is not
269     // captured more than once.
270     for (auto &C : CS.captures()) {
271       if (!C.capturesVariable() && !C.capturesVariableByCopy())
272         continue;
273 
274       const VarDecl *VD = C.getCapturedVar();
275       if (VD->isLocalVarDeclOrParm())
276         continue;
277 
278       DeclRefExpr DRE(const_cast<VarDecl *>(VD),
279                       /*RefersToEnclosingVariableOrCapture=*/false,
280                       VD->getType().getNonReferenceType(), VK_LValue,
281                       SourceLocation());
282       PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
283         return CGF.EmitLValue(&DRE).getAddress();
284       });
285     }
286     (void)PrivScope.Privatize();
287   }
288 
289   /// \brief Lookup the captured field decl for a variable.
290   const FieldDecl *lookup(const VarDecl *VD) const override {
291     if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
292       return FD;
293     return nullptr;
294   }
295 
296   /// \brief Emit the captured statement body.
297   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
298     llvm_unreachable("No body for expressions");
299   }
300 
301   /// \brief Get a variable or parameter for storing global thread id
302   /// inside OpenMP construct.
303   const VarDecl *getThreadIDVariable() const override {
304     llvm_unreachable("No thread id for expressions");
305   }
306 
307   /// \brief Get the name of the capture helper.
308   StringRef getHelperName() const override {
309     llvm_unreachable("No helper name for expressions");
310   }
311 
312   static bool classof(const CGCapturedStmtInfo *Info) { return false; }
313 
314 private:
315   /// Private scope to capture global variables.
316   CodeGenFunction::OMPPrivateScope PrivScope;
317 };
318 
319 /// \brief RAII for emitting code of OpenMP constructs.
320 class InlinedOpenMPRegionRAII {
321   CodeGenFunction &CGF;
322 
323 public:
324   /// \brief Constructs region for combined constructs.
325   /// \param CodeGen Code generation sequence for combined directives. Includes
326   /// a list of functions used for code generation of implicitly inlined
327   /// regions.
328   InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
329                           OpenMPDirectiveKind Kind, bool HasCancel)
330       : CGF(CGF) {
331     // Start emission for the construct.
332     CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
333         CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
334   }
335 
336   ~InlinedOpenMPRegionRAII() {
337     // Restore original CapturedStmtInfo only if we're done with code emission.
338     auto *OldCSI =
339         cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
340     delete CGF.CapturedStmtInfo;
341     CGF.CapturedStmtInfo = OldCSI;
342   }
343 };
344 
345 /// \brief Values for bit flags used in the ident_t to describe the fields.
346 /// All enumeric elements are named and described in accordance with the code
347 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
348 enum OpenMPLocationFlags {
349   /// \brief Use trampoline for internal microtask.
350   OMP_IDENT_IMD = 0x01,
351   /// \brief Use c-style ident structure.
352   OMP_IDENT_KMPC = 0x02,
353   /// \brief Atomic reduction option for kmpc_reduce.
354   OMP_ATOMIC_REDUCE = 0x10,
355   /// \brief Explicit 'barrier' directive.
356   OMP_IDENT_BARRIER_EXPL = 0x20,
357   /// \brief Implicit barrier in code.
358   OMP_IDENT_BARRIER_IMPL = 0x40,
359   /// \brief Implicit barrier in 'for' directive.
360   OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
361   /// \brief Implicit barrier in 'sections' directive.
362   OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
363   /// \brief Implicit barrier in 'single' directive.
364   OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
365 };
366 
367 /// \brief Describes ident structure that describes a source location.
368 /// All descriptions are taken from
369 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
370 /// Original structure:
371 /// typedef struct ident {
372 ///    kmp_int32 reserved_1;   /**<  might be used in Fortran;
373 ///                                  see above  */
374 ///    kmp_int32 flags;        /**<  also f.flags; KMP_IDENT_xxx flags;
375 ///                                  KMP_IDENT_KMPC identifies this union
376 ///                                  member  */
377 ///    kmp_int32 reserved_2;   /**<  not really used in Fortran any more;
378 ///                                  see above */
379 ///#if USE_ITT_BUILD
380 ///                            /*  but currently used for storing
381 ///                                region-specific ITT */
382 ///                            /*  contextual information. */
383 ///#endif /* USE_ITT_BUILD */
384 ///    kmp_int32 reserved_3;   /**< source[4] in Fortran, do not use for
385 ///                                 C++  */
386 ///    char const *psource;    /**< String describing the source location.
387 ///                            The string is composed of semi-colon separated
388 //                             fields which describe the source file,
389 ///                            the function and a pair of line numbers that
390 ///                            delimit the construct.
391 ///                             */
392 /// } ident_t;
393 enum IdentFieldIndex {
394   /// \brief might be used in Fortran
395   IdentField_Reserved_1,
396   /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
397   IdentField_Flags,
398   /// \brief Not really used in Fortran any more
399   IdentField_Reserved_2,
400   /// \brief Source[4] in Fortran, do not use for C++
401   IdentField_Reserved_3,
402   /// \brief String describing the source location. The string is composed of
403   /// semi-colon separated fields which describe the source file, the function
404   /// and a pair of line numbers that delimit the construct.
405   IdentField_PSource
406 };
407 
408 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
409 /// the enum sched_type in kmp.h).
410 enum OpenMPSchedType {
411   /// \brief Lower bound for default (unordered) versions.
412   OMP_sch_lower = 32,
413   OMP_sch_static_chunked = 33,
414   OMP_sch_static = 34,
415   OMP_sch_dynamic_chunked = 35,
416   OMP_sch_guided_chunked = 36,
417   OMP_sch_runtime = 37,
418   OMP_sch_auto = 38,
419   /// \brief Lower bound for 'ordered' versions.
420   OMP_ord_lower = 64,
421   OMP_ord_static_chunked = 65,
422   OMP_ord_static = 66,
423   OMP_ord_dynamic_chunked = 67,
424   OMP_ord_guided_chunked = 68,
425   OMP_ord_runtime = 69,
426   OMP_ord_auto = 70,
427   OMP_sch_default = OMP_sch_static,
428   /// \brief dist_schedule types
429   OMP_dist_sch_static_chunked = 91,
430   OMP_dist_sch_static = 92,
431 };
432 
433 enum OpenMPRTLFunction {
434   /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
435   /// kmpc_micro microtask, ...);
436   OMPRTL__kmpc_fork_call,
437   /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
438   /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
439   OMPRTL__kmpc_threadprivate_cached,
440   /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
441   /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
442   OMPRTL__kmpc_threadprivate_register,
443   // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
444   OMPRTL__kmpc_global_thread_num,
445   // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
446   // kmp_critical_name *crit);
447   OMPRTL__kmpc_critical,
448   // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
449   // global_tid, kmp_critical_name *crit, uintptr_t hint);
450   OMPRTL__kmpc_critical_with_hint,
451   // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
452   // kmp_critical_name *crit);
453   OMPRTL__kmpc_end_critical,
454   // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
455   // global_tid);
456   OMPRTL__kmpc_cancel_barrier,
457   // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
458   OMPRTL__kmpc_barrier,
459   // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
460   OMPRTL__kmpc_for_static_fini,
461   // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
462   // global_tid);
463   OMPRTL__kmpc_serialized_parallel,
464   // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
465   // global_tid);
466   OMPRTL__kmpc_end_serialized_parallel,
467   // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
468   // kmp_int32 num_threads);
469   OMPRTL__kmpc_push_num_threads,
470   // Call to void __kmpc_flush(ident_t *loc);
471   OMPRTL__kmpc_flush,
472   // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
473   OMPRTL__kmpc_master,
474   // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
475   OMPRTL__kmpc_end_master,
476   // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
477   // int end_part);
478   OMPRTL__kmpc_omp_taskyield,
479   // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
480   OMPRTL__kmpc_single,
481   // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
482   OMPRTL__kmpc_end_single,
483   // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
484   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
485   // kmp_routine_entry_t *task_entry);
486   OMPRTL__kmpc_omp_task_alloc,
487   // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
488   // new_task);
489   OMPRTL__kmpc_omp_task,
490   // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
491   // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
492   // kmp_int32 didit);
493   OMPRTL__kmpc_copyprivate,
494   // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
495   // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
496   // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
497   OMPRTL__kmpc_reduce,
498   // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
499   // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
500   // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
501   // *lck);
502   OMPRTL__kmpc_reduce_nowait,
503   // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
504   // kmp_critical_name *lck);
505   OMPRTL__kmpc_end_reduce,
506   // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
507   // kmp_critical_name *lck);
508   OMPRTL__kmpc_end_reduce_nowait,
509   // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
510   // kmp_task_t * new_task);
511   OMPRTL__kmpc_omp_task_begin_if0,
512   // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
513   // kmp_task_t * new_task);
514   OMPRTL__kmpc_omp_task_complete_if0,
515   // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
516   OMPRTL__kmpc_ordered,
517   // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
518   OMPRTL__kmpc_end_ordered,
519   // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
520   // global_tid);
521   OMPRTL__kmpc_omp_taskwait,
522   // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
523   OMPRTL__kmpc_taskgroup,
524   // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
525   OMPRTL__kmpc_end_taskgroup,
526   // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
527   // int proc_bind);
528   OMPRTL__kmpc_push_proc_bind,
529   // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
530   // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
531   // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
532   OMPRTL__kmpc_omp_task_with_deps,
533   // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
534   // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
535   // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
536   OMPRTL__kmpc_omp_wait_deps,
537   // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
538   // global_tid, kmp_int32 cncl_kind);
539   OMPRTL__kmpc_cancellationpoint,
540   // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
541   // kmp_int32 cncl_kind);
542   OMPRTL__kmpc_cancel,
543   // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
544   // kmp_int32 num_teams, kmp_int32 thread_limit);
545   OMPRTL__kmpc_push_num_teams,
546   /// \brief Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
547   /// kmpc_micro microtask, ...);
548   OMPRTL__kmpc_fork_teams,
549 
550   //
551   // Offloading related calls
552   //
553   // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
554   // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
555   // *arg_types);
556   OMPRTL__tgt_target,
557   // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
558   // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
559   // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
560   OMPRTL__tgt_target_teams,
561   // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
562   OMPRTL__tgt_register_lib,
563   // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
564   OMPRTL__tgt_unregister_lib,
565 };
566 
567 } // anonymous namespace
568 
569 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
570   return CGF.EmitLoadOfPointerLValue(
571       CGF.GetAddrOfLocalVar(getThreadIDVariable()),
572       getThreadIDVariable()->getType()->castAs<PointerType>());
573 }
574 
575 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
576   if (!CGF.HaveInsertPoint())
577     return;
578   // 1.2.2 OpenMP Language Terminology
579   // Structured block - An executable statement with a single entry at the
580   // top and a single exit at the bottom.
581   // The point of exit cannot be a branch out of the structured block.
582   // longjmp() and throw() must not violate the entry/exit criteria.
583   CGF.EHStack.pushTerminate();
584   {
585     CodeGenFunction::RunCleanupsScope Scope(CGF);
586     CodeGen(CGF);
587   }
588   CGF.EHStack.popTerminate();
589 }
590 
591 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
592     CodeGenFunction &CGF) {
593   return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
594                             getThreadIDVariable()->getType(),
595                             AlignmentSource::Decl);
596 }
597 
598 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
599     : CGM(CGM), OffloadEntriesInfoManager(CGM) {
600   IdentTy = llvm::StructType::create(
601       "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
602       CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
603       CGM.Int8PtrTy /* psource */, nullptr);
604   // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
605   llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
606                                llvm::PointerType::getUnqual(CGM.Int32Ty)};
607   Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
608   KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
609 
610   loadOffloadInfoMetadata();
611 }
612 
613 void CGOpenMPRuntime::clear() {
614   InternalVars.clear();
615 }
616 
617 static llvm::Function *
618 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
619                           const Expr *CombinerInitializer, const VarDecl *In,
620                           const VarDecl *Out, bool IsCombiner) {
621   // void .omp_combiner.(Ty *in, Ty *out);
622   auto &C = CGM.getContext();
623   QualType PtrTy = C.getPointerType(Ty).withRestrict();
624   FunctionArgList Args;
625   ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
626                                /*Id=*/nullptr, PtrTy);
627   ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
628                               /*Id=*/nullptr, PtrTy);
629   Args.push_back(&OmpOutParm);
630   Args.push_back(&OmpInParm);
631   auto &FnInfo =
632       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
633   auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
634   auto *Fn = llvm::Function::Create(
635       FnTy, llvm::GlobalValue::InternalLinkage,
636       IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
637   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
638   Fn->addFnAttr(llvm::Attribute::AlwaysInline);
639   CodeGenFunction CGF(CGM);
640   // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
641   // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
642   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
643   CodeGenFunction::OMPPrivateScope Scope(CGF);
644   Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
645   Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
646     return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
647         .getAddress();
648   });
649   Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
650   Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
651     return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
652         .getAddress();
653   });
654   (void)Scope.Privatize();
655   CGF.EmitIgnoredExpr(CombinerInitializer);
656   Scope.ForceCleanup();
657   CGF.FinishFunction();
658   return Fn;
659 }
660 
661 void CGOpenMPRuntime::emitUserDefinedReduction(
662     CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
663   if (UDRMap.count(D) > 0)
664     return;
665   auto &C = CGM.getContext();
666   if (!In || !Out) {
667     In = &C.Idents.get("omp_in");
668     Out = &C.Idents.get("omp_out");
669   }
670   llvm::Function *Combiner = emitCombinerOrInitializer(
671       CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
672       cast<VarDecl>(D->lookup(Out).front()),
673       /*IsCombiner=*/true);
674   llvm::Function *Initializer = nullptr;
675   if (auto *Init = D->getInitializer()) {
676     if (!Priv || !Orig) {
677       Priv = &C.Idents.get("omp_priv");
678       Orig = &C.Idents.get("omp_orig");
679     }
680     Initializer = emitCombinerOrInitializer(
681         CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
682         cast<VarDecl>(D->lookup(Priv).front()),
683         /*IsCombiner=*/false);
684   }
685   UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
686   if (CGF) {
687     auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
688     Decls.second.push_back(D);
689   }
690 }
691 
692 std::pair<llvm::Function *, llvm::Function *>
693 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
694   auto I = UDRMap.find(D);
695   if (I != UDRMap.end())
696     return I->second;
697   emitUserDefinedReduction(/*CGF=*/nullptr, D);
698   return UDRMap.lookup(D);
699 }
700 
701 // Layout information for ident_t.
702 static CharUnits getIdentAlign(CodeGenModule &CGM) {
703   return CGM.getPointerAlign();
704 }
705 static CharUnits getIdentSize(CodeGenModule &CGM) {
706   assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
707   return CharUnits::fromQuantity(16) + CGM.getPointerSize();
708 }
709 static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
710   // All the fields except the last are i32, so this works beautifully.
711   return unsigned(Field) * CharUnits::fromQuantity(4);
712 }
713 static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
714                                    IdentFieldIndex Field,
715                                    const llvm::Twine &Name = "") {
716   auto Offset = getOffsetOfIdentField(Field);
717   return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
718 }
719 
720 llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
721     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
722     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
723   assert(ThreadIDVar->getType()->isPointerType() &&
724          "thread id variable must be of type kmp_int32 *");
725   const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
726   CodeGenFunction CGF(CGM, true);
727   bool HasCancel = false;
728   if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
729     HasCancel = OPD->hasCancel();
730   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
731     HasCancel = OPSD->hasCancel();
732   else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
733     HasCancel = OPFD->hasCancel();
734   CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
735                                     HasCancel);
736   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
737   return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
738 }
739 
740 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
741     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
742     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
743   assert(!ThreadIDVar->getType()->isPointerType() &&
744          "thread id variable must be of type kmp_int32 for tasks");
745   auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
746   CodeGenFunction CGF(CGM, true);
747   CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
748                                         InnermostKind,
749                                         cast<OMPTaskDirective>(D).hasCancel());
750   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
751   return CGF.GenerateCapturedStmtFunction(*CS);
752 }
753 
754 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
755   CharUnits Align = getIdentAlign(CGM);
756   llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
757   if (!Entry) {
758     if (!DefaultOpenMPPSource) {
759       // Initialize default location for psource field of ident_t structure of
760       // all ident_t objects. Format is ";file;function;line;column;;".
761       // Taken from
762       // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
763       DefaultOpenMPPSource =
764           CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
765       DefaultOpenMPPSource =
766           llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
767     }
768     auto DefaultOpenMPLocation = new llvm::GlobalVariable(
769         CGM.getModule(), IdentTy, /*isConstant*/ true,
770         llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
771     DefaultOpenMPLocation->setUnnamedAddr(true);
772     DefaultOpenMPLocation->setAlignment(Align.getQuantity());
773 
774     llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
775     llvm::Constant *Values[] = {Zero,
776                                 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
777                                 Zero, Zero, DefaultOpenMPPSource};
778     llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
779     DefaultOpenMPLocation->setInitializer(Init);
780     OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
781   }
782   return Address(Entry, Align);
783 }
784 
785 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
786                                                  SourceLocation Loc,
787                                                  unsigned Flags) {
788   Flags |= OMP_IDENT_KMPC;
789   // If no debug info is generated - return global default location.
790   if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
791       Loc.isInvalid())
792     return getOrCreateDefaultLocation(Flags).getPointer();
793 
794   assert(CGF.CurFn && "No function in current CodeGenFunction.");
795 
796   Address LocValue = Address::invalid();
797   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
798   if (I != OpenMPLocThreadIDMap.end())
799     LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
800 
801   // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
802   // GetOpenMPThreadID was called before this routine.
803   if (!LocValue.isValid()) {
804     // Generate "ident_t .kmpc_loc.addr;"
805     Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
806                                       ".kmpc_loc.addr");
807     auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
808     Elem.second.DebugLoc = AI.getPointer();
809     LocValue = AI;
810 
811     CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
812     CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
813     CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
814                              CGM.getSize(getIdentSize(CGF.CGM)));
815   }
816 
817   // char **psource = &.kmpc_loc_<flags>.addr.psource;
818   Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
819 
820   auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
821   if (OMPDebugLoc == nullptr) {
822     SmallString<128> Buffer2;
823     llvm::raw_svector_ostream OS2(Buffer2);
824     // Build debug location
825     PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
826     OS2 << ";" << PLoc.getFilename() << ";";
827     if (const FunctionDecl *FD =
828             dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
829       OS2 << FD->getQualifiedNameAsString();
830     }
831     OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
832     OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
833     OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
834   }
835   // *psource = ";<File>;<Function>;<Line>;<Column>;;";
836   CGF.Builder.CreateStore(OMPDebugLoc, PSource);
837 
838   // Our callers always pass this to a runtime function, so for
839   // convenience, go ahead and return a naked pointer.
840   return LocValue.getPointer();
841 }
842 
843 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
844                                           SourceLocation Loc) {
845   assert(CGF.CurFn && "No function in current CodeGenFunction.");
846 
847   llvm::Value *ThreadID = nullptr;
848   // Check whether we've already cached a load of the thread id in this
849   // function.
850   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
851   if (I != OpenMPLocThreadIDMap.end()) {
852     ThreadID = I->second.ThreadID;
853     if (ThreadID != nullptr)
854       return ThreadID;
855   }
856   if (auto *OMPRegionInfo =
857           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
858     if (OMPRegionInfo->getThreadIDVariable()) {
859       // Check if this an outlined function with thread id passed as argument.
860       auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
861       ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
862       // If value loaded in entry block, cache it and use it everywhere in
863       // function.
864       if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
865         auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
866         Elem.second.ThreadID = ThreadID;
867       }
868       return ThreadID;
869     }
870   }
871 
872   // This is not an outlined function region - need to call __kmpc_int32
873   // kmpc_global_thread_num(ident_t *loc).
874   // Generate thread id value and cache this value for use across the
875   // function.
876   CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
877   CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
878   ThreadID =
879       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
880                           emitUpdateLocation(CGF, Loc));
881   auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
882   Elem.second.ThreadID = ThreadID;
883   return ThreadID;
884 }
885 
886 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
887   assert(CGF.CurFn && "No function in current CodeGenFunction.");
888   if (OpenMPLocThreadIDMap.count(CGF.CurFn))
889     OpenMPLocThreadIDMap.erase(CGF.CurFn);
890   if (FunctionUDRMap.count(CGF.CurFn) > 0) {
891     for(auto *D : FunctionUDRMap[CGF.CurFn]) {
892       UDRMap.erase(D);
893     }
894     FunctionUDRMap.erase(CGF.CurFn);
895   }
896 }
897 
898 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
899   return llvm::PointerType::getUnqual(IdentTy);
900 }
901 
902 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
903   return llvm::PointerType::getUnqual(Kmpc_MicroTy);
904 }
905 
906 llvm::Constant *
907 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
908   llvm::Constant *RTLFn = nullptr;
909   switch (static_cast<OpenMPRTLFunction>(Function)) {
910   case OMPRTL__kmpc_fork_call: {
911     // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
912     // microtask, ...);
913     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
914                                 getKmpc_MicroPointerTy()};
915     llvm::FunctionType *FnTy =
916         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
917     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
918     break;
919   }
920   case OMPRTL__kmpc_global_thread_num: {
921     // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
922     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
923     llvm::FunctionType *FnTy =
924         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
925     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
926     break;
927   }
928   case OMPRTL__kmpc_threadprivate_cached: {
929     // Build void *__kmpc_threadprivate_cached(ident_t *loc,
930     // kmp_int32 global_tid, void *data, size_t size, void ***cache);
931     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
932                                 CGM.VoidPtrTy, CGM.SizeTy,
933                                 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
934     llvm::FunctionType *FnTy =
935         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
936     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
937     break;
938   }
939   case OMPRTL__kmpc_critical: {
940     // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
941     // kmp_critical_name *crit);
942     llvm::Type *TypeParams[] = {
943         getIdentTyPointerTy(), CGM.Int32Ty,
944         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
945     llvm::FunctionType *FnTy =
946         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
947     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
948     break;
949   }
950   case OMPRTL__kmpc_critical_with_hint: {
951     // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
952     // kmp_critical_name *crit, uintptr_t hint);
953     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
954                                 llvm::PointerType::getUnqual(KmpCriticalNameTy),
955                                 CGM.IntPtrTy};
956     llvm::FunctionType *FnTy =
957         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
958     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
959     break;
960   }
961   case OMPRTL__kmpc_threadprivate_register: {
962     // Build void __kmpc_threadprivate_register(ident_t *, void *data,
963     // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
964     // typedef void *(*kmpc_ctor)(void *);
965     auto KmpcCtorTy =
966         llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
967                                 /*isVarArg*/ false)->getPointerTo();
968     // typedef void *(*kmpc_cctor)(void *, void *);
969     llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
970     auto KmpcCopyCtorTy =
971         llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
972                                 /*isVarArg*/ false)->getPointerTo();
973     // typedef void (*kmpc_dtor)(void *);
974     auto KmpcDtorTy =
975         llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
976             ->getPointerTo();
977     llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
978                               KmpcCopyCtorTy, KmpcDtorTy};
979     auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
980                                         /*isVarArg*/ false);
981     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
982     break;
983   }
984   case OMPRTL__kmpc_end_critical: {
985     // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
986     // kmp_critical_name *crit);
987     llvm::Type *TypeParams[] = {
988         getIdentTyPointerTy(), CGM.Int32Ty,
989         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
990     llvm::FunctionType *FnTy =
991         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
992     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
993     break;
994   }
995   case OMPRTL__kmpc_cancel_barrier: {
996     // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
997     // global_tid);
998     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
999     llvm::FunctionType *FnTy =
1000         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1001     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1002     break;
1003   }
1004   case OMPRTL__kmpc_barrier: {
1005     // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1006     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1007     llvm::FunctionType *FnTy =
1008         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1009     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1010     break;
1011   }
1012   case OMPRTL__kmpc_for_static_fini: {
1013     // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1014     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1015     llvm::FunctionType *FnTy =
1016         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1017     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1018     break;
1019   }
1020   case OMPRTL__kmpc_push_num_threads: {
1021     // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1022     // kmp_int32 num_threads)
1023     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1024                                 CGM.Int32Ty};
1025     llvm::FunctionType *FnTy =
1026         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1027     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1028     break;
1029   }
1030   case OMPRTL__kmpc_serialized_parallel: {
1031     // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1032     // global_tid);
1033     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1034     llvm::FunctionType *FnTy =
1035         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1036     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1037     break;
1038   }
1039   case OMPRTL__kmpc_end_serialized_parallel: {
1040     // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1041     // global_tid);
1042     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1043     llvm::FunctionType *FnTy =
1044         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1045     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1046     break;
1047   }
1048   case OMPRTL__kmpc_flush: {
1049     // Build void __kmpc_flush(ident_t *loc);
1050     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1051     llvm::FunctionType *FnTy =
1052         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1053     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1054     break;
1055   }
1056   case OMPRTL__kmpc_master: {
1057     // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1058     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1059     llvm::FunctionType *FnTy =
1060         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1061     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1062     break;
1063   }
1064   case OMPRTL__kmpc_end_master: {
1065     // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1066     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1067     llvm::FunctionType *FnTy =
1068         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1069     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1070     break;
1071   }
1072   case OMPRTL__kmpc_omp_taskyield: {
1073     // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1074     // int end_part);
1075     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1076     llvm::FunctionType *FnTy =
1077         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1078     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1079     break;
1080   }
1081   case OMPRTL__kmpc_single: {
1082     // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1083     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1084     llvm::FunctionType *FnTy =
1085         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1086     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1087     break;
1088   }
1089   case OMPRTL__kmpc_end_single: {
1090     // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1091     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1092     llvm::FunctionType *FnTy =
1093         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1094     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1095     break;
1096   }
1097   case OMPRTL__kmpc_omp_task_alloc: {
1098     // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1099     // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1100     // kmp_routine_entry_t *task_entry);
1101     assert(KmpRoutineEntryPtrTy != nullptr &&
1102            "Type kmp_routine_entry_t must be created.");
1103     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1104                                 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1105     // Return void * and then cast to particular kmp_task_t type.
1106     llvm::FunctionType *FnTy =
1107         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1108     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1109     break;
1110   }
1111   case OMPRTL__kmpc_omp_task: {
1112     // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1113     // *new_task);
1114     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1115                                 CGM.VoidPtrTy};
1116     llvm::FunctionType *FnTy =
1117         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1118     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1119     break;
1120   }
1121   case OMPRTL__kmpc_copyprivate: {
1122     // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1123     // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1124     // kmp_int32 didit);
1125     llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1126     auto *CpyFnTy =
1127         llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1128     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1129                                 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1130                                 CGM.Int32Ty};
1131     llvm::FunctionType *FnTy =
1132         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1133     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1134     break;
1135   }
1136   case OMPRTL__kmpc_reduce: {
1137     // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1138     // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1139     // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1140     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1141     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1142                                                /*isVarArg=*/false);
1143     llvm::Type *TypeParams[] = {
1144         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1145         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1146         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1147     llvm::FunctionType *FnTy =
1148         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1149     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1150     break;
1151   }
1152   case OMPRTL__kmpc_reduce_nowait: {
1153     // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1154     // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1155     // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1156     // *lck);
1157     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1158     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1159                                                /*isVarArg=*/false);
1160     llvm::Type *TypeParams[] = {
1161         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1162         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1163         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1164     llvm::FunctionType *FnTy =
1165         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1166     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1167     break;
1168   }
1169   case OMPRTL__kmpc_end_reduce: {
1170     // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1171     // kmp_critical_name *lck);
1172     llvm::Type *TypeParams[] = {
1173         getIdentTyPointerTy(), CGM.Int32Ty,
1174         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1175     llvm::FunctionType *FnTy =
1176         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1177     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1178     break;
1179   }
1180   case OMPRTL__kmpc_end_reduce_nowait: {
1181     // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1182     // kmp_critical_name *lck);
1183     llvm::Type *TypeParams[] = {
1184         getIdentTyPointerTy(), CGM.Int32Ty,
1185         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1186     llvm::FunctionType *FnTy =
1187         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1188     RTLFn =
1189         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1190     break;
1191   }
1192   case OMPRTL__kmpc_omp_task_begin_if0: {
1193     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1194     // *new_task);
1195     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1196                                 CGM.VoidPtrTy};
1197     llvm::FunctionType *FnTy =
1198         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1199     RTLFn =
1200         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1201     break;
1202   }
1203   case OMPRTL__kmpc_omp_task_complete_if0: {
1204     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1205     // *new_task);
1206     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1207                                 CGM.VoidPtrTy};
1208     llvm::FunctionType *FnTy =
1209         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1210     RTLFn = CGM.CreateRuntimeFunction(FnTy,
1211                                       /*Name=*/"__kmpc_omp_task_complete_if0");
1212     break;
1213   }
1214   case OMPRTL__kmpc_ordered: {
1215     // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1216     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1217     llvm::FunctionType *FnTy =
1218         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1219     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1220     break;
1221   }
1222   case OMPRTL__kmpc_end_ordered: {
1223     // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1224     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1225     llvm::FunctionType *FnTy =
1226         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1227     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1228     break;
1229   }
1230   case OMPRTL__kmpc_omp_taskwait: {
1231     // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1232     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1233     llvm::FunctionType *FnTy =
1234         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1235     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1236     break;
1237   }
1238   case OMPRTL__kmpc_taskgroup: {
1239     // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1240     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1241     llvm::FunctionType *FnTy =
1242         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1243     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1244     break;
1245   }
1246   case OMPRTL__kmpc_end_taskgroup: {
1247     // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1248     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1249     llvm::FunctionType *FnTy =
1250         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1251     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1252     break;
1253   }
1254   case OMPRTL__kmpc_push_proc_bind: {
1255     // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1256     // int proc_bind)
1257     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1258     llvm::FunctionType *FnTy =
1259         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1260     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1261     break;
1262   }
1263   case OMPRTL__kmpc_omp_task_with_deps: {
1264     // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1265     // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1266     // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1267     llvm::Type *TypeParams[] = {
1268         getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1269         CGM.VoidPtrTy,         CGM.Int32Ty, CGM.VoidPtrTy};
1270     llvm::FunctionType *FnTy =
1271         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1272     RTLFn =
1273         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1274     break;
1275   }
1276   case OMPRTL__kmpc_omp_wait_deps: {
1277     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1278     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1279     // kmp_depend_info_t *noalias_dep_list);
1280     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1281                                 CGM.Int32Ty,           CGM.VoidPtrTy,
1282                                 CGM.Int32Ty,           CGM.VoidPtrTy};
1283     llvm::FunctionType *FnTy =
1284         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1285     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1286     break;
1287   }
1288   case OMPRTL__kmpc_cancellationpoint: {
1289     // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1290     // global_tid, kmp_int32 cncl_kind)
1291     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1292     llvm::FunctionType *FnTy =
1293         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1294     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1295     break;
1296   }
1297   case OMPRTL__kmpc_cancel: {
1298     // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1299     // kmp_int32 cncl_kind)
1300     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1301     llvm::FunctionType *FnTy =
1302         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1303     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1304     break;
1305   }
1306   case OMPRTL__kmpc_push_num_teams: {
1307     // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1308     // kmp_int32 num_teams, kmp_int32 num_threads)
1309     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1310         CGM.Int32Ty};
1311     llvm::FunctionType *FnTy =
1312         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1313     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1314     break;
1315   }
1316   case OMPRTL__kmpc_fork_teams: {
1317     // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1318     // microtask, ...);
1319     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1320                                 getKmpc_MicroPointerTy()};
1321     llvm::FunctionType *FnTy =
1322         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1323     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1324     break;
1325   }
1326   case OMPRTL__tgt_target: {
1327     // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1328     // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1329     // *arg_types);
1330     llvm::Type *TypeParams[] = {CGM.Int32Ty,
1331                                 CGM.VoidPtrTy,
1332                                 CGM.Int32Ty,
1333                                 CGM.VoidPtrPtrTy,
1334                                 CGM.VoidPtrPtrTy,
1335                                 CGM.SizeTy->getPointerTo(),
1336                                 CGM.Int32Ty->getPointerTo()};
1337     llvm::FunctionType *FnTy =
1338         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1339     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1340     break;
1341   }
1342   case OMPRTL__tgt_target_teams: {
1343     // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1344     // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1345     // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1346     llvm::Type *TypeParams[] = {CGM.Int32Ty,
1347                                 CGM.VoidPtrTy,
1348                                 CGM.Int32Ty,
1349                                 CGM.VoidPtrPtrTy,
1350                                 CGM.VoidPtrPtrTy,
1351                                 CGM.SizeTy->getPointerTo(),
1352                                 CGM.Int32Ty->getPointerTo(),
1353                                 CGM.Int32Ty,
1354                                 CGM.Int32Ty};
1355     llvm::FunctionType *FnTy =
1356         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1357     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1358     break;
1359   }
1360   case OMPRTL__tgt_register_lib: {
1361     // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1362     QualType ParamTy =
1363         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1364     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1365     llvm::FunctionType *FnTy =
1366         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1367     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1368     break;
1369   }
1370   case OMPRTL__tgt_unregister_lib: {
1371     // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1372     QualType ParamTy =
1373         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1374     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1375     llvm::FunctionType *FnTy =
1376         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1377     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1378     break;
1379   }
1380   }
1381   assert(RTLFn && "Unable to find OpenMP runtime function");
1382   return RTLFn;
1383 }
1384 
1385 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1386                                                              bool IVSigned) {
1387   assert((IVSize == 32 || IVSize == 64) &&
1388          "IV size is not compatible with the omp runtime");
1389   auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1390                                        : "__kmpc_for_static_init_4u")
1391                            : (IVSigned ? "__kmpc_for_static_init_8"
1392                                        : "__kmpc_for_static_init_8u");
1393   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1394   auto PtrTy = llvm::PointerType::getUnqual(ITy);
1395   llvm::Type *TypeParams[] = {
1396     getIdentTyPointerTy(),                     // loc
1397     CGM.Int32Ty,                               // tid
1398     CGM.Int32Ty,                               // schedtype
1399     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1400     PtrTy,                                     // p_lower
1401     PtrTy,                                     // p_upper
1402     PtrTy,                                     // p_stride
1403     ITy,                                       // incr
1404     ITy                                        // chunk
1405   };
1406   llvm::FunctionType *FnTy =
1407       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1408   return CGM.CreateRuntimeFunction(FnTy, Name);
1409 }
1410 
1411 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1412                                                             bool IVSigned) {
1413   assert((IVSize == 32 || IVSize == 64) &&
1414          "IV size is not compatible with the omp runtime");
1415   auto Name =
1416       IVSize == 32
1417           ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1418           : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1419   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1420   llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1421                                CGM.Int32Ty,           // tid
1422                                CGM.Int32Ty,           // schedtype
1423                                ITy,                   // lower
1424                                ITy,                   // upper
1425                                ITy,                   // stride
1426                                ITy                    // chunk
1427   };
1428   llvm::FunctionType *FnTy =
1429       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1430   return CGM.CreateRuntimeFunction(FnTy, Name);
1431 }
1432 
1433 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1434                                                             bool IVSigned) {
1435   assert((IVSize == 32 || IVSize == 64) &&
1436          "IV size is not compatible with the omp runtime");
1437   auto Name =
1438       IVSize == 32
1439           ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1440           : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1441   llvm::Type *TypeParams[] = {
1442       getIdentTyPointerTy(), // loc
1443       CGM.Int32Ty,           // tid
1444   };
1445   llvm::FunctionType *FnTy =
1446       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1447   return CGM.CreateRuntimeFunction(FnTy, Name);
1448 }
1449 
1450 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1451                                                             bool IVSigned) {
1452   assert((IVSize == 32 || IVSize == 64) &&
1453          "IV size is not compatible with the omp runtime");
1454   auto Name =
1455       IVSize == 32
1456           ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1457           : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1458   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1459   auto PtrTy = llvm::PointerType::getUnqual(ITy);
1460   llvm::Type *TypeParams[] = {
1461     getIdentTyPointerTy(),                     // loc
1462     CGM.Int32Ty,                               // tid
1463     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1464     PtrTy,                                     // p_lower
1465     PtrTy,                                     // p_upper
1466     PtrTy                                      // p_stride
1467   };
1468   llvm::FunctionType *FnTy =
1469       llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1470   return CGM.CreateRuntimeFunction(FnTy, Name);
1471 }
1472 
1473 llvm::Constant *
1474 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1475   assert(!CGM.getLangOpts().OpenMPUseTLS ||
1476          !CGM.getContext().getTargetInfo().isTLSSupported());
1477   // Lookup the entry, lazily creating it if necessary.
1478   return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
1479                                      Twine(CGM.getMangledName(VD)) + ".cache.");
1480 }
1481 
1482 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1483                                                 const VarDecl *VD,
1484                                                 Address VDAddr,
1485                                                 SourceLocation Loc) {
1486   if (CGM.getLangOpts().OpenMPUseTLS &&
1487       CGM.getContext().getTargetInfo().isTLSSupported())
1488     return VDAddr;
1489 
1490   auto VarTy = VDAddr.getElementType();
1491   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1492                          CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1493                                                        CGM.Int8PtrTy),
1494                          CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1495                          getOrCreateThreadPrivateCache(VD)};
1496   return Address(CGF.EmitRuntimeCall(
1497       createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1498                  VDAddr.getAlignment());
1499 }
1500 
1501 void CGOpenMPRuntime::emitThreadPrivateVarInit(
1502     CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1503     llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1504   // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1505   // library.
1506   auto OMPLoc = emitUpdateLocation(CGF, Loc);
1507   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1508                       OMPLoc);
1509   // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1510   // to register constructor/destructor for variable.
1511   llvm::Value *Args[] = {OMPLoc,
1512                          CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1513                                                        CGM.VoidPtrTy),
1514                          Ctor, CopyCtor, Dtor};
1515   CGF.EmitRuntimeCall(
1516       createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
1517 }
1518 
1519 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1520     const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1521     bool PerformInit, CodeGenFunction *CGF) {
1522   if (CGM.getLangOpts().OpenMPUseTLS &&
1523       CGM.getContext().getTargetInfo().isTLSSupported())
1524     return nullptr;
1525 
1526   VD = VD->getDefinition(CGM.getContext());
1527   if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1528     ThreadPrivateWithDefinition.insert(VD);
1529     QualType ASTTy = VD->getType();
1530 
1531     llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1532     auto Init = VD->getAnyInitializer();
1533     if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1534       // Generate function that re-emits the declaration's initializer into the
1535       // threadprivate copy of the variable VD
1536       CodeGenFunction CtorCGF(CGM);
1537       FunctionArgList Args;
1538       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1539                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1540       Args.push_back(&Dst);
1541 
1542       auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1543           CGM.getContext().VoidPtrTy, Args);
1544       auto FTy = CGM.getTypes().GetFunctionType(FI);
1545       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1546           FTy, ".__kmpc_global_ctor_.", FI, Loc);
1547       CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1548                             Args, SourceLocation());
1549       auto ArgVal = CtorCGF.EmitLoadOfScalar(
1550           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1551           CGM.getContext().VoidPtrTy, Dst.getLocation());
1552       Address Arg = Address(ArgVal, VDAddr.getAlignment());
1553       Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1554                                              CtorCGF.ConvertTypeForMem(ASTTy));
1555       CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1556                                /*IsInitializer=*/true);
1557       ArgVal = CtorCGF.EmitLoadOfScalar(
1558           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1559           CGM.getContext().VoidPtrTy, Dst.getLocation());
1560       CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1561       CtorCGF.FinishFunction();
1562       Ctor = Fn;
1563     }
1564     if (VD->getType().isDestructedType() != QualType::DK_none) {
1565       // Generate function that emits destructor call for the threadprivate copy
1566       // of the variable VD
1567       CodeGenFunction DtorCGF(CGM);
1568       FunctionArgList Args;
1569       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1570                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1571       Args.push_back(&Dst);
1572 
1573       auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1574           CGM.getContext().VoidTy, Args);
1575       auto FTy = CGM.getTypes().GetFunctionType(FI);
1576       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
1577           FTy, ".__kmpc_global_dtor_.", FI, Loc);
1578       DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1579                             SourceLocation());
1580       auto ArgVal = DtorCGF.EmitLoadOfScalar(
1581           DtorCGF.GetAddrOfLocalVar(&Dst),
1582           /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1583       DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
1584                           DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1585                           DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1586       DtorCGF.FinishFunction();
1587       Dtor = Fn;
1588     }
1589     // Do not emit init function if it is not required.
1590     if (!Ctor && !Dtor)
1591       return nullptr;
1592 
1593     llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1594     auto CopyCtorTy =
1595         llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1596                                 /*isVarArg=*/false)->getPointerTo();
1597     // Copying constructor for the threadprivate variable.
1598     // Must be NULL - reserved by runtime, but currently it requires that this
1599     // parameter is always NULL. Otherwise it fires assertion.
1600     CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1601     if (Ctor == nullptr) {
1602       auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1603                                             /*isVarArg=*/false)->getPointerTo();
1604       Ctor = llvm::Constant::getNullValue(CtorTy);
1605     }
1606     if (Dtor == nullptr) {
1607       auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1608                                             /*isVarArg=*/false)->getPointerTo();
1609       Dtor = llvm::Constant::getNullValue(DtorTy);
1610     }
1611     if (!CGF) {
1612       auto InitFunctionTy =
1613           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1614       auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
1615           InitFunctionTy, ".__omp_threadprivate_init_.",
1616           CGM.getTypes().arrangeNullaryFunction());
1617       CodeGenFunction InitCGF(CGM);
1618       FunctionArgList ArgList;
1619       InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1620                             CGM.getTypes().arrangeNullaryFunction(), ArgList,
1621                             Loc);
1622       emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1623       InitCGF.FinishFunction();
1624       return InitFunction;
1625     }
1626     emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1627   }
1628   return nullptr;
1629 }
1630 
1631 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1632 /// function. Here is the logic:
1633 /// if (Cond) {
1634 ///   ThenGen();
1635 /// } else {
1636 ///   ElseGen();
1637 /// }
1638 static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1639                             const RegionCodeGenTy &ThenGen,
1640                             const RegionCodeGenTy &ElseGen) {
1641   CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1642 
1643   // If the condition constant folds and can be elided, try to avoid emitting
1644   // the condition and the dead arm of the if/else.
1645   bool CondConstant;
1646   if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
1647     CodeGenFunction::RunCleanupsScope Scope(CGF);
1648     if (CondConstant) {
1649       ThenGen(CGF);
1650     } else {
1651       ElseGen(CGF);
1652     }
1653     return;
1654   }
1655 
1656   // Otherwise, the condition did not fold, or we couldn't elide it.  Just
1657   // emit the conditional branch.
1658   auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1659   auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1660   auto ContBlock = CGF.createBasicBlock("omp_if.end");
1661   CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1662 
1663   // Emit the 'then' code.
1664   CGF.EmitBlock(ThenBlock);
1665   {
1666     CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1667     ThenGen(CGF);
1668   }
1669   CGF.EmitBranch(ContBlock);
1670   // Emit the 'else' code if present.
1671   {
1672     // There is no need to emit line number for unconditional branch.
1673     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1674     CGF.EmitBlock(ElseBlock);
1675   }
1676   {
1677     CodeGenFunction::RunCleanupsScope ThenScope(CGF);
1678     ElseGen(CGF);
1679   }
1680   {
1681     // There is no need to emit line number for unconditional branch.
1682     auto NL = ApplyDebugLocation::CreateEmpty(CGF);
1683     CGF.EmitBranch(ContBlock);
1684   }
1685   // Emit the continuation block for code after the if.
1686   CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
1687 }
1688 
1689 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1690                                        llvm::Value *OutlinedFn,
1691                                        ArrayRef<llvm::Value *> CapturedVars,
1692                                        const Expr *IfCond) {
1693   if (!CGF.HaveInsertPoint())
1694     return;
1695   auto *RTLoc = emitUpdateLocation(CGF, Loc);
1696   auto &&ThenGen = [this, OutlinedFn, CapturedVars,
1697                     RTLoc](CodeGenFunction &CGF) {
1698     // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
1699     llvm::Value *Args[] = {
1700         RTLoc,
1701         CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
1702         CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
1703     llvm::SmallVector<llvm::Value *, 16> RealArgs;
1704     RealArgs.append(std::begin(Args), std::end(Args));
1705     RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1706 
1707     auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
1708     CGF.EmitRuntimeCall(RTLFn, RealArgs);
1709   };
1710   auto &&ElseGen = [this, OutlinedFn, CapturedVars, RTLoc,
1711                     Loc](CodeGenFunction &CGF) {
1712     auto ThreadID = getThreadID(CGF, Loc);
1713     // Build calls:
1714     // __kmpc_serialized_parallel(&Loc, GTid);
1715     llvm::Value *Args[] = {RTLoc, ThreadID};
1716     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
1717                         Args);
1718 
1719     // OutlinedFn(&GTid, &zero, CapturedStruct);
1720     auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
1721     Address ZeroAddr =
1722       CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1723                            /*Name*/ ".zero.addr");
1724     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1725     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1726     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1727     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1728     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1729     CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
1730 
1731     // __kmpc_end_serialized_parallel(&Loc, GTid);
1732     llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
1733     CGF.EmitRuntimeCall(
1734         createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
1735   };
1736   if (IfCond) {
1737     emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
1738   } else {
1739     CodeGenFunction::RunCleanupsScope Scope(CGF);
1740     ThenGen(CGF);
1741   }
1742 }
1743 
1744 // If we're inside an (outlined) parallel region, use the region info's
1745 // thread-ID variable (it is passed in a first argument of the outlined function
1746 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1747 // regular serial code region, get thread ID by calling kmp_int32
1748 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1749 // return the address of that temp.
1750 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1751                                              SourceLocation Loc) {
1752   if (auto *OMPRegionInfo =
1753           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
1754     if (OMPRegionInfo->getThreadIDVariable())
1755       return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
1756 
1757   auto ThreadID = getThreadID(CGF, Loc);
1758   auto Int32Ty =
1759       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1760   auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1761   CGF.EmitStoreOfScalar(ThreadID,
1762                         CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
1763 
1764   return ThreadIDTemp;
1765 }
1766 
1767 llvm::Constant *
1768 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
1769                                              const llvm::Twine &Name) {
1770   SmallString<256> Buffer;
1771   llvm::raw_svector_ostream Out(Buffer);
1772   Out << Name;
1773   auto RuntimeName = Out.str();
1774   auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1775   if (Elem.second) {
1776     assert(Elem.second->getType()->getPointerElementType() == Ty &&
1777            "OMP internal variable has different type than requested");
1778     return &*Elem.second;
1779   }
1780 
1781   return Elem.second = new llvm::GlobalVariable(
1782              CGM.getModule(), Ty, /*IsConstant*/ false,
1783              llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1784              Elem.first());
1785 }
1786 
1787 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
1788   llvm::Twine Name(".gomp_critical_user_", CriticalName);
1789   return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
1790 }
1791 
1792 namespace {
1793 template <size_t N> class CallEndCleanup final : public EHScopeStack::Cleanup {
1794   llvm::Value *Callee;
1795   llvm::Value *Args[N];
1796 
1797 public:
1798   CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
1799       : Callee(Callee) {
1800     assert(CleanupArgs.size() == N);
1801     std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
1802   }
1803 
1804   void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
1805     if (!CGF.HaveInsertPoint())
1806       return;
1807     CGF.EmitRuntimeCall(Callee, Args);
1808   }
1809 };
1810 } // anonymous namespace
1811 
1812 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1813                                          StringRef CriticalName,
1814                                          const RegionCodeGenTy &CriticalOpGen,
1815                                          SourceLocation Loc, const Expr *Hint) {
1816   // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
1817   // CriticalOpGen();
1818   // __kmpc_end_critical(ident_t *, gtid, Lock);
1819   // Prepare arguments and build a call to __kmpc_critical
1820   if (!CGF.HaveInsertPoint())
1821     return;
1822   CodeGenFunction::RunCleanupsScope Scope(CGF);
1823   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1824                          getCriticalRegionLock(CriticalName)};
1825   if (Hint) {
1826     llvm::SmallVector<llvm::Value *, 8> ArgsWithHint(std::begin(Args),
1827                                                      std::end(Args));
1828     auto *HintVal = CGF.EmitScalarExpr(Hint);
1829     ArgsWithHint.push_back(
1830         CGF.Builder.CreateIntCast(HintVal, CGM.IntPtrTy, /*isSigned=*/false));
1831     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical_with_hint),
1832                         ArgsWithHint);
1833   } else
1834     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
1835   // Build a call to __kmpc_end_critical
1836   CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1837       NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
1838       llvm::makeArrayRef(Args));
1839   emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
1840 }
1841 
1842 static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
1843                        OpenMPDirectiveKind Kind, SourceLocation Loc,
1844                        const RegionCodeGenTy &BodyOpGen) {
1845   llvm::Value *CallBool = CGF.EmitScalarConversion(
1846       IfCond,
1847       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
1848       CGF.getContext().BoolTy, Loc);
1849 
1850   auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1851   auto *ContBlock = CGF.createBasicBlock("omp_if.end");
1852   // Generate the branch (If-stmt)
1853   CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1854   CGF.EmitBlock(ThenBlock);
1855   CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
1856   // Emit the rest of bblocks/branches
1857   CGF.EmitBranch(ContBlock);
1858   CGF.EmitBlock(ContBlock, true);
1859 }
1860 
1861 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
1862                                        const RegionCodeGenTy &MasterOpGen,
1863                                        SourceLocation Loc) {
1864   if (!CGF.HaveInsertPoint())
1865     return;
1866   // if(__kmpc_master(ident_t *, gtid)) {
1867   //   MasterOpGen();
1868   //   __kmpc_end_master(ident_t *, gtid);
1869   // }
1870   // Prepare arguments and build a call to __kmpc_master
1871   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1872   auto *IsMaster =
1873       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
1874   typedef CallEndCleanup<std::extent<decltype(Args)>::value>
1875       MasterCallEndCleanup;
1876   emitIfStmt(
1877       CGF, IsMaster, OMPD_master, Loc, [&](CodeGenFunction &CGF) -> void {
1878         CodeGenFunction::RunCleanupsScope Scope(CGF);
1879         CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
1880             NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
1881             llvm::makeArrayRef(Args));
1882         MasterOpGen(CGF);
1883       });
1884 }
1885 
1886 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
1887                                         SourceLocation Loc) {
1888   if (!CGF.HaveInsertPoint())
1889     return;
1890   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
1891   llvm::Value *Args[] = {
1892       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1893       llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
1894   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
1895 }
1896 
1897 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
1898                                           const RegionCodeGenTy &TaskgroupOpGen,
1899                                           SourceLocation Loc) {
1900   if (!CGF.HaveInsertPoint())
1901     return;
1902   // __kmpc_taskgroup(ident_t *, gtid);
1903   // TaskgroupOpGen();
1904   // __kmpc_end_taskgroup(ident_t *, gtid);
1905   // Prepare arguments and build a call to __kmpc_taskgroup
1906   {
1907     CodeGenFunction::RunCleanupsScope Scope(CGF);
1908     llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
1909     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
1910     // Build a call to __kmpc_end_taskgroup
1911     CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
1912         NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
1913         llvm::makeArrayRef(Args));
1914     emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
1915   }
1916 }
1917 
1918 /// Given an array of pointers to variables, project the address of a
1919 /// given variable.
1920 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
1921                                       unsigned Index, const VarDecl *Var) {
1922   // Pull out the pointer to the variable.
1923   Address PtrAddr =
1924       CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
1925   llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
1926 
1927   Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
1928   Addr = CGF.Builder.CreateElementBitCast(
1929       Addr, CGF.ConvertTypeForMem(Var->getType()));
1930   return Addr;
1931 }
1932 
1933 static llvm::Value *emitCopyprivateCopyFunction(
1934     CodeGenModule &CGM, llvm::Type *ArgsType,
1935     ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
1936     ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
1937   auto &C = CGM.getContext();
1938   // void copy_func(void *LHSArg, void *RHSArg);
1939   FunctionArgList Args;
1940   ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1941                            C.VoidPtrTy);
1942   ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
1943                            C.VoidPtrTy);
1944   Args.push_back(&LHSArg);
1945   Args.push_back(&RHSArg);
1946   auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1947   auto *Fn = llvm::Function::Create(
1948       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
1949       ".omp.copyprivate.copy_func", &CGM.getModule());
1950   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
1951   CodeGenFunction CGF(CGM);
1952   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
1953   // Dest = (void*[n])(LHSArg);
1954   // Src = (void*[n])(RHSArg);
1955   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1956       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
1957       ArgsType), CGF.getPointerAlign());
1958   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1959       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
1960       ArgsType), CGF.getPointerAlign());
1961   // *(Type0*)Dst[0] = *(Type0*)Src[0];
1962   // *(Type1*)Dst[1] = *(Type1*)Src[1];
1963   // ...
1964   // *(Typen*)Dst[n] = *(Typen*)Src[n];
1965   for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
1966     auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
1967     Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
1968 
1969     auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
1970     Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
1971 
1972     auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
1973     QualType Type = VD->getType();
1974     CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
1975   }
1976   CGF.FinishFunction();
1977   return Fn;
1978 }
1979 
1980 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
1981                                        const RegionCodeGenTy &SingleOpGen,
1982                                        SourceLocation Loc,
1983                                        ArrayRef<const Expr *> CopyprivateVars,
1984                                        ArrayRef<const Expr *> SrcExprs,
1985                                        ArrayRef<const Expr *> DstExprs,
1986                                        ArrayRef<const Expr *> AssignmentOps) {
1987   if (!CGF.HaveInsertPoint())
1988     return;
1989   assert(CopyprivateVars.size() == SrcExprs.size() &&
1990          CopyprivateVars.size() == DstExprs.size() &&
1991          CopyprivateVars.size() == AssignmentOps.size());
1992   auto &C = CGM.getContext();
1993   // int32 did_it = 0;
1994   // if(__kmpc_single(ident_t *, gtid)) {
1995   //   SingleOpGen();
1996   //   __kmpc_end_single(ident_t *, gtid);
1997   //   did_it = 1;
1998   // }
1999   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2000   // <copy_func>, did_it);
2001 
2002   Address DidIt = Address::invalid();
2003   if (!CopyprivateVars.empty()) {
2004     // int32 did_it = 0;
2005     auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2006     DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2007     CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2008   }
2009   // Prepare arguments and build a call to __kmpc_single
2010   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2011   auto *IsSingle =
2012       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
2013   typedef CallEndCleanup<std::extent<decltype(Args)>::value>
2014       SingleCallEndCleanup;
2015   emitIfStmt(
2016       CGF, IsSingle, OMPD_single, Loc, [&](CodeGenFunction &CGF) -> void {
2017         CodeGenFunction::RunCleanupsScope Scope(CGF);
2018         CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
2019             NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
2020             llvm::makeArrayRef(Args));
2021         SingleOpGen(CGF);
2022         if (DidIt.isValid()) {
2023           // did_it = 1;
2024           CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2025         }
2026       });
2027   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2028   // <copy_func>, did_it);
2029   if (DidIt.isValid()) {
2030     llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2031     auto CopyprivateArrayTy =
2032         C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2033                                /*IndexTypeQuals=*/0);
2034     // Create a list of all private variables for copyprivate.
2035     Address CopyprivateList =
2036         CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2037     for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2038       Address Elem = CGF.Builder.CreateConstArrayGEP(
2039           CopyprivateList, I, CGF.getPointerSize());
2040       CGF.Builder.CreateStore(
2041           CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2042               CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2043           Elem);
2044     }
2045     // Build function that copies private values from single region to all other
2046     // threads in the corresponding parallel region.
2047     auto *CpyFn = emitCopyprivateCopyFunction(
2048         CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2049         CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
2050     auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2051     Address CL =
2052       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2053                                                       CGF.VoidPtrTy);
2054     auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
2055     llvm::Value *Args[] = {
2056         emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2057         getThreadID(CGF, Loc),        // i32 <gtid>
2058         BufSize,                      // size_t <buf_size>
2059         CL.getPointer(),              // void *<copyprivate list>
2060         CpyFn,                        // void (*) (void *, void *) <copy_func>
2061         DidItVal                      // i32 did_it
2062     };
2063     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2064   }
2065 }
2066 
2067 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2068                                         const RegionCodeGenTy &OrderedOpGen,
2069                                         SourceLocation Loc, bool IsThreads) {
2070   if (!CGF.HaveInsertPoint())
2071     return;
2072   // __kmpc_ordered(ident_t *, gtid);
2073   // OrderedOpGen();
2074   // __kmpc_end_ordered(ident_t *, gtid);
2075   // Prepare arguments and build a call to __kmpc_ordered
2076   CodeGenFunction::RunCleanupsScope Scope(CGF);
2077   if (IsThreads) {
2078     llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2079     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
2080     // Build a call to __kmpc_end_ordered
2081     CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
2082         NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2083         llvm::makeArrayRef(Args));
2084   }
2085   emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2086 }
2087 
2088 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2089                                       OpenMPDirectiveKind Kind, bool EmitChecks,
2090                                       bool ForceSimpleCall) {
2091   if (!CGF.HaveInsertPoint())
2092     return;
2093   // Build call __kmpc_cancel_barrier(loc, thread_id);
2094   // Build call __kmpc_barrier(loc, thread_id);
2095   unsigned Flags;
2096   if (Kind == OMPD_for)
2097     Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2098   else if (Kind == OMPD_sections)
2099     Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2100   else if (Kind == OMPD_single)
2101     Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2102   else if (Kind == OMPD_barrier)
2103     Flags = OMP_IDENT_BARRIER_EXPL;
2104   else
2105     Flags = OMP_IDENT_BARRIER_IMPL;
2106   // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2107   // thread_id);
2108   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2109                          getThreadID(CGF, Loc)};
2110   if (auto *OMPRegionInfo =
2111           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2112     if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2113       auto *Result = CGF.EmitRuntimeCall(
2114           createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
2115       if (EmitChecks) {
2116         // if (__kmpc_cancel_barrier()) {
2117         //   exit from construct;
2118         // }
2119         auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2120         auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2121         auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2122         CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2123         CGF.EmitBlock(ExitBB);
2124         //   exit from construct;
2125         auto CancelDestination =
2126             CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2127         CGF.EmitBranchThroughCleanup(CancelDestination);
2128         CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2129       }
2130       return;
2131     }
2132   }
2133   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2134 }
2135 
2136 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
2137 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2138                                           bool Chunked, bool Ordered) {
2139   switch (ScheduleKind) {
2140   case OMPC_SCHEDULE_static:
2141     return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2142                    : (Ordered ? OMP_ord_static : OMP_sch_static);
2143   case OMPC_SCHEDULE_dynamic:
2144     return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2145   case OMPC_SCHEDULE_guided:
2146     return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2147   case OMPC_SCHEDULE_runtime:
2148     return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2149   case OMPC_SCHEDULE_auto:
2150     return Ordered ? OMP_ord_auto : OMP_sch_auto;
2151   case OMPC_SCHEDULE_unknown:
2152     assert(!Chunked && "chunk was specified but schedule kind not known");
2153     return Ordered ? OMP_ord_static : OMP_sch_static;
2154   }
2155   llvm_unreachable("Unexpected runtime schedule");
2156 }
2157 
2158 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2159 static OpenMPSchedType
2160 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2161   // only static is allowed for dist_schedule
2162   return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2163 }
2164 
2165 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2166                                          bool Chunked) const {
2167   auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2168   return Schedule == OMP_sch_static;
2169 }
2170 
2171 bool CGOpenMPRuntime::isStaticNonchunked(
2172     OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2173   auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2174   return Schedule == OMP_dist_sch_static;
2175 }
2176 
2177 
2178 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2179   auto Schedule =
2180       getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2181   assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2182   return Schedule != OMP_sch_static;
2183 }
2184 
2185 void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2186                                           SourceLocation Loc,
2187                                           OpenMPScheduleClauseKind ScheduleKind,
2188                                           unsigned IVSize, bool IVSigned,
2189                                           bool Ordered, llvm::Value *UB,
2190                                           llvm::Value *Chunk) {
2191   if (!CGF.HaveInsertPoint())
2192     return;
2193   OpenMPSchedType Schedule =
2194       getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
2195   assert(Ordered ||
2196          (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2197           Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2198   // Call __kmpc_dispatch_init(
2199   //          ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2200   //          kmp_int[32|64] lower, kmp_int[32|64] upper,
2201   //          kmp_int[32|64] stride, kmp_int[32|64] chunk);
2202 
2203   // If the Chunk was not specified in the clause - use default value 1.
2204   if (Chunk == nullptr)
2205     Chunk = CGF.Builder.getIntN(IVSize, 1);
2206   llvm::Value *Args[] = {
2207       emitUpdateLocation(CGF, Loc),
2208       getThreadID(CGF, Loc),
2209       CGF.Builder.getInt32(Schedule), // Schedule type
2210       CGF.Builder.getIntN(IVSize, 0), // Lower
2211       UB,                             // Upper
2212       CGF.Builder.getIntN(IVSize, 1), // Stride
2213       Chunk                           // Chunk
2214   };
2215   CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2216 }
2217 
2218 static void emitForStaticInitCall(CodeGenFunction &CGF,
2219                                   SourceLocation Loc,
2220                                   llvm::Value * UpdateLocation,
2221                                   llvm::Value * ThreadId,
2222                                   llvm::Constant * ForStaticInitFunction,
2223                                   OpenMPSchedType Schedule,
2224                                   unsigned IVSize, bool IVSigned, bool Ordered,
2225                                   Address IL, Address LB, Address UB,
2226                                   Address ST, llvm::Value *Chunk) {
2227   if (!CGF.HaveInsertPoint())
2228      return;
2229 
2230    assert(!Ordered);
2231    assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2232           Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2233           Schedule == OMP_dist_sch_static ||
2234           Schedule == OMP_dist_sch_static_chunked);
2235 
2236    // Call __kmpc_for_static_init(
2237    //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2238    //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2239    //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2240    //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
2241    if (Chunk == nullptr) {
2242      assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2243              Schedule == OMP_dist_sch_static) &&
2244             "expected static non-chunked schedule");
2245      // If the Chunk was not specified in the clause - use default value 1.
2246        Chunk = CGF.Builder.getIntN(IVSize, 1);
2247    } else {
2248      assert((Schedule == OMP_sch_static_chunked ||
2249              Schedule == OMP_ord_static_chunked ||
2250              Schedule == OMP_dist_sch_static_chunked) &&
2251             "expected static chunked schedule");
2252    }
2253    llvm::Value *Args[] = {
2254      UpdateLocation,
2255      ThreadId,
2256      CGF.Builder.getInt32(Schedule), // Schedule type
2257      IL.getPointer(),                // &isLastIter
2258      LB.getPointer(),                // &LB
2259      UB.getPointer(),                // &UB
2260      ST.getPointer(),                // &Stride
2261      CGF.Builder.getIntN(IVSize, 1), // Incr
2262      Chunk                           // Chunk
2263    };
2264    CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2265 }
2266 
2267 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2268                                         SourceLocation Loc,
2269                                         OpenMPScheduleClauseKind ScheduleKind,
2270                                         unsigned IVSize, bool IVSigned,
2271                                         bool Ordered, Address IL, Address LB,
2272                                         Address UB, Address ST,
2273                                         llvm::Value *Chunk) {
2274   OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2275                                                    Ordered);
2276   auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2277   auto *ThreadId = getThreadID(CGF, Loc);
2278   auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2279   emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2280       ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2281 }
2282 
2283 void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2284     SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2285     unsigned IVSize, bool IVSigned,
2286     bool Ordered, Address IL, Address LB,
2287     Address UB, Address ST,
2288     llvm::Value *Chunk) {
2289   OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2290   auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2291   auto *ThreadId = getThreadID(CGF, Loc);
2292   auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2293   emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2294       ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2295 }
2296 
2297 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2298                                           SourceLocation Loc) {
2299   if (!CGF.HaveInsertPoint())
2300     return;
2301   // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2302   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2303   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2304                       Args);
2305 }
2306 
2307 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2308                                                  SourceLocation Loc,
2309                                                  unsigned IVSize,
2310                                                  bool IVSigned) {
2311   if (!CGF.HaveInsertPoint())
2312     return;
2313   // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2314   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2315   CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2316 }
2317 
2318 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2319                                           SourceLocation Loc, unsigned IVSize,
2320                                           bool IVSigned, Address IL,
2321                                           Address LB, Address UB,
2322                                           Address ST) {
2323   // Call __kmpc_dispatch_next(
2324   //          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2325   //          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2326   //          kmp_int[32|64] *p_stride);
2327   llvm::Value *Args[] = {
2328       emitUpdateLocation(CGF, Loc),
2329       getThreadID(CGF, Loc),
2330       IL.getPointer(), // &isLastIter
2331       LB.getPointer(), // &Lower
2332       UB.getPointer(), // &Upper
2333       ST.getPointer()  // &Stride
2334   };
2335   llvm::Value *Call =
2336       CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2337   return CGF.EmitScalarConversion(
2338       Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
2339       CGF.getContext().BoolTy, Loc);
2340 }
2341 
2342 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2343                                            llvm::Value *NumThreads,
2344                                            SourceLocation Loc) {
2345   if (!CGF.HaveInsertPoint())
2346     return;
2347   // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2348   llvm::Value *Args[] = {
2349       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2350       CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2351   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2352                       Args);
2353 }
2354 
2355 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2356                                          OpenMPProcBindClauseKind ProcBind,
2357                                          SourceLocation Loc) {
2358   if (!CGF.HaveInsertPoint())
2359     return;
2360   // Constants for proc bind value accepted by the runtime.
2361   enum ProcBindTy {
2362     ProcBindFalse = 0,
2363     ProcBindTrue,
2364     ProcBindMaster,
2365     ProcBindClose,
2366     ProcBindSpread,
2367     ProcBindIntel,
2368     ProcBindDefault
2369   } RuntimeProcBind;
2370   switch (ProcBind) {
2371   case OMPC_PROC_BIND_master:
2372     RuntimeProcBind = ProcBindMaster;
2373     break;
2374   case OMPC_PROC_BIND_close:
2375     RuntimeProcBind = ProcBindClose;
2376     break;
2377   case OMPC_PROC_BIND_spread:
2378     RuntimeProcBind = ProcBindSpread;
2379     break;
2380   case OMPC_PROC_BIND_unknown:
2381     llvm_unreachable("Unsupported proc_bind value.");
2382   }
2383   // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2384   llvm::Value *Args[] = {
2385       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2386       llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2387   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2388 }
2389 
2390 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2391                                 SourceLocation Loc) {
2392   if (!CGF.HaveInsertPoint())
2393     return;
2394   // Build call void __kmpc_flush(ident_t *loc)
2395   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2396                       emitUpdateLocation(CGF, Loc));
2397 }
2398 
2399 namespace {
2400 /// \brief Indexes of fields for type kmp_task_t.
2401 enum KmpTaskTFields {
2402   /// \brief List of shared variables.
2403   KmpTaskTShareds,
2404   /// \brief Task routine.
2405   KmpTaskTRoutine,
2406   /// \brief Partition id for the untied tasks.
2407   KmpTaskTPartId,
2408   /// \brief Function with call of destructors for private variables.
2409   KmpTaskTDestructors,
2410 };
2411 } // anonymous namespace
2412 
2413 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2414   // FIXME: Add other entries type when they become supported.
2415   return OffloadEntriesTargetRegion.empty();
2416 }
2417 
2418 /// \brief Initialize target region entry.
2419 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2420     initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2421                                     StringRef ParentName, unsigned LineNum,
2422                                     unsigned Order) {
2423   assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2424                                              "only required for the device "
2425                                              "code generation.");
2426   OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
2427       OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2428   ++OffloadingEntriesNum;
2429 }
2430 
2431 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2432     registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2433                                   StringRef ParentName, unsigned LineNum,
2434                                   llvm::Constant *Addr, llvm::Constant *ID) {
2435   // If we are emitting code for a target, the entry is already initialized,
2436   // only has to be registered.
2437   if (CGM.getLangOpts().OpenMPIsDevice) {
2438     assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
2439            "Entry must exist.");
2440     auto &Entry =
2441         OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
2442     assert(Entry.isValid() && "Entry not initialized!");
2443     Entry.setAddress(Addr);
2444     Entry.setID(ID);
2445     return;
2446   } else {
2447     OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
2448     OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
2449   }
2450 }
2451 
2452 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
2453     unsigned DeviceID, unsigned FileID, StringRef ParentName,
2454     unsigned LineNum) const {
2455   auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2456   if (PerDevice == OffloadEntriesTargetRegion.end())
2457     return false;
2458   auto PerFile = PerDevice->second.find(FileID);
2459   if (PerFile == PerDevice->second.end())
2460     return false;
2461   auto PerParentName = PerFile->second.find(ParentName);
2462   if (PerParentName == PerFile->second.end())
2463     return false;
2464   auto PerLine = PerParentName->second.find(LineNum);
2465   if (PerLine == PerParentName->second.end())
2466     return false;
2467   // Fail if this entry is already registered.
2468   if (PerLine->second.getAddress() || PerLine->second.getID())
2469     return false;
2470   return true;
2471 }
2472 
2473 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2474     const OffloadTargetRegionEntryInfoActTy &Action) {
2475   // Scan all target region entries and perform the provided action.
2476   for (auto &D : OffloadEntriesTargetRegion)
2477     for (auto &F : D.second)
2478       for (auto &P : F.second)
2479         for (auto &L : P.second)
2480           Action(D.first, F.first, P.first(), L.first, L.second);
2481 }
2482 
2483 /// \brief Create a Ctor/Dtor-like function whose body is emitted through
2484 /// \a Codegen. This is used to emit the two functions that register and
2485 /// unregister the descriptor of the current compilation unit.
2486 static llvm::Function *
2487 createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2488                                          const RegionCodeGenTy &Codegen) {
2489   auto &C = CGM.getContext();
2490   FunctionArgList Args;
2491   ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2492                              /*Id=*/nullptr, C.VoidPtrTy);
2493   Args.push_back(&DummyPtr);
2494 
2495   CodeGenFunction CGF(CGM);
2496   GlobalDecl();
2497   auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2498   auto FTy = CGM.getTypes().GetFunctionType(FI);
2499   auto *Fn =
2500       CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2501   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2502   Codegen(CGF);
2503   CGF.FinishFunction();
2504   return Fn;
2505 }
2506 
2507 llvm::Function *
2508 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2509 
2510   // If we don't have entries or if we are emitting code for the device, we
2511   // don't need to do anything.
2512   if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2513     return nullptr;
2514 
2515   auto &M = CGM.getModule();
2516   auto &C = CGM.getContext();
2517 
2518   // Get list of devices we care about
2519   auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2520 
2521   // We should be creating an offloading descriptor only if there are devices
2522   // specified.
2523   assert(!Devices.empty() && "No OpenMP offloading devices??");
2524 
2525   // Create the external variables that will point to the begin and end of the
2526   // host entries section. These will be defined by the linker.
2527   auto *OffloadEntryTy =
2528       CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2529   llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2530       M, OffloadEntryTy, /*isConstant=*/true,
2531       llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2532       ".omp_offloading.entries_begin");
2533   llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2534       M, OffloadEntryTy, /*isConstant=*/true,
2535       llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
2536       ".omp_offloading.entries_end");
2537 
2538   // Create all device images
2539   llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2540   auto *DeviceImageTy = cast<llvm::StructType>(
2541       CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2542 
2543   for (unsigned i = 0; i < Devices.size(); ++i) {
2544     StringRef T = Devices[i].getTriple();
2545     auto *ImgBegin = new llvm::GlobalVariable(
2546         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2547         /*Initializer=*/nullptr,
2548         Twine(".omp_offloading.img_start.") + Twine(T));
2549     auto *ImgEnd = new llvm::GlobalVariable(
2550         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
2551         /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
2552 
2553     llvm::Constant *Dev =
2554         llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2555                                   HostEntriesBegin, HostEntriesEnd, nullptr);
2556     DeviceImagesEntires.push_back(Dev);
2557   }
2558 
2559   // Create device images global array.
2560   llvm::ArrayType *DeviceImagesInitTy =
2561       llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2562   llvm::Constant *DeviceImagesInit =
2563       llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2564 
2565   llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2566       M, DeviceImagesInitTy, /*isConstant=*/true,
2567       llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2568       ".omp_offloading.device_images");
2569   DeviceImages->setUnnamedAddr(true);
2570 
2571   // This is a Zero array to be used in the creation of the constant expressions
2572   llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2573                              llvm::Constant::getNullValue(CGM.Int32Ty)};
2574 
2575   // Create the target region descriptor.
2576   auto *BinaryDescriptorTy = cast<llvm::StructType>(
2577       CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2578   llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2579       BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2580       llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2581                                            Index),
2582       HostEntriesBegin, HostEntriesEnd, nullptr);
2583 
2584   auto *Desc = new llvm::GlobalVariable(
2585       M, BinaryDescriptorTy, /*isConstant=*/true,
2586       llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2587       ".omp_offloading.descriptor");
2588 
2589   // Emit code to register or unregister the descriptor at execution
2590   // startup or closing, respectively.
2591 
2592   // Create a variable to drive the registration and unregistration of the
2593   // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2594   auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2595   ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2596                                 IdentInfo, C.CharTy);
2597 
2598   auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
2599       CGM, ".omp_offloading.descriptor_unreg", [&](CodeGenFunction &CGF) {
2600         CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2601                              Desc);
2602       });
2603   auto *RegFn = createOffloadingBinaryDescriptorFunction(
2604       CGM, ".omp_offloading.descriptor_reg", [&](CodeGenFunction &CGF) {
2605         CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2606                              Desc);
2607         CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2608       });
2609   return RegFn;
2610 }
2611 
2612 void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2613                                          llvm::Constant *Addr, uint64_t Size) {
2614   StringRef Name = Addr->getName();
2615   auto *TgtOffloadEntryType = cast<llvm::StructType>(
2616       CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2617   llvm::LLVMContext &C = CGM.getModule().getContext();
2618   llvm::Module &M = CGM.getModule();
2619 
2620   // Make sure the address has the right type.
2621   llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
2622 
2623   // Create constant string with the name.
2624   llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2625 
2626   llvm::GlobalVariable *Str =
2627       new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2628                                llvm::GlobalValue::InternalLinkage, StrPtrInit,
2629                                ".omp_offloading.entry_name");
2630   Str->setUnnamedAddr(true);
2631   llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2632 
2633   // Create the entry struct.
2634   llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2635       TgtOffloadEntryType, AddrPtr, StrPtr,
2636       llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2637   llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2638       M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2639       EntryInit, ".omp_offloading.entry");
2640 
2641   // The entry has to be created in the section the linker expects it to be.
2642   Entry->setSection(".omp_offloading.entries");
2643   // We can't have any padding between symbols, so we need to have 1-byte
2644   // alignment.
2645   Entry->setAlignment(1);
2646 }
2647 
2648 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2649   // Emit the offloading entries and metadata so that the device codegen side
2650   // can
2651   // easily figure out what to emit. The produced metadata looks like this:
2652   //
2653   // !omp_offload.info = !{!1, ...}
2654   //
2655   // Right now we only generate metadata for function that contain target
2656   // regions.
2657 
2658   // If we do not have entries, we dont need to do anything.
2659   if (OffloadEntriesInfoManager.empty())
2660     return;
2661 
2662   llvm::Module &M = CGM.getModule();
2663   llvm::LLVMContext &C = M.getContext();
2664   SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2665       OrderedEntries(OffloadEntriesInfoManager.size());
2666 
2667   // Create the offloading info metadata node.
2668   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2669 
2670   // Auxiliar methods to create metadata values and strings.
2671   auto getMDInt = [&](unsigned v) {
2672     return llvm::ConstantAsMetadata::get(
2673         llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2674   };
2675 
2676   auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2677 
2678   // Create function that emits metadata for each target region entry;
2679   auto &&TargetRegionMetadataEmitter = [&](
2680       unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
2681       OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2682     llvm::SmallVector<llvm::Metadata *, 32> Ops;
2683     // Generate metadata for target regions. Each entry of this metadata
2684     // contains:
2685     // - Entry 0 -> Kind of this type of metadata (0).
2686     // - Entry 1 -> Device ID of the file where the entry was identified.
2687     // - Entry 2 -> File ID of the file where the entry was identified.
2688     // - Entry 3 -> Mangled name of the function where the entry was identified.
2689     // - Entry 4 -> Line in the file where the entry was identified.
2690     // - Entry 5 -> Order the entry was created.
2691     // The first element of the metadata node is the kind.
2692     Ops.push_back(getMDInt(E.getKind()));
2693     Ops.push_back(getMDInt(DeviceID));
2694     Ops.push_back(getMDInt(FileID));
2695     Ops.push_back(getMDString(ParentName));
2696     Ops.push_back(getMDInt(Line));
2697     Ops.push_back(getMDInt(E.getOrder()));
2698 
2699     // Save this entry in the right position of the ordered entries array.
2700     OrderedEntries[E.getOrder()] = &E;
2701 
2702     // Add metadata to the named metadata node.
2703     MD->addOperand(llvm::MDNode::get(C, Ops));
2704   };
2705 
2706   OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2707       TargetRegionMetadataEmitter);
2708 
2709   for (auto *E : OrderedEntries) {
2710     assert(E && "All ordered entries must exist!");
2711     if (auto *CE =
2712             dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2713                 E)) {
2714       assert(CE->getID() && CE->getAddress() &&
2715              "Entry ID and Addr are invalid!");
2716       createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
2717     } else
2718       llvm_unreachable("Unsupported entry kind.");
2719   }
2720 }
2721 
2722 /// \brief Loads all the offload entries information from the host IR
2723 /// metadata.
2724 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2725   // If we are in target mode, load the metadata from the host IR. This code has
2726   // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2727 
2728   if (!CGM.getLangOpts().OpenMPIsDevice)
2729     return;
2730 
2731   if (CGM.getLangOpts().OMPHostIRFile.empty())
2732     return;
2733 
2734   auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2735   if (Buf.getError())
2736     return;
2737 
2738   llvm::LLVMContext C;
2739   auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2740 
2741   if (ME.getError())
2742     return;
2743 
2744   llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2745   if (!MD)
2746     return;
2747 
2748   for (auto I : MD->operands()) {
2749     llvm::MDNode *MN = cast<llvm::MDNode>(I);
2750 
2751     auto getMDInt = [&](unsigned Idx) {
2752       llvm::ConstantAsMetadata *V =
2753           cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2754       return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2755     };
2756 
2757     auto getMDString = [&](unsigned Idx) {
2758       llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2759       return V->getString();
2760     };
2761 
2762     switch (getMDInt(0)) {
2763     default:
2764       llvm_unreachable("Unexpected metadata!");
2765       break;
2766     case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2767         OFFLOAD_ENTRY_INFO_TARGET_REGION:
2768       OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2769           /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2770           /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
2771           /*Order=*/getMDInt(5));
2772       break;
2773     }
2774   }
2775 }
2776 
2777 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2778   if (!KmpRoutineEntryPtrTy) {
2779     // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2780     auto &C = CGM.getContext();
2781     QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2782     FunctionProtoType::ExtProtoInfo EPI;
2783     KmpRoutineEntryPtrQTy = C.getPointerType(
2784         C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2785     KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2786   }
2787 }
2788 
2789 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2790                                        QualType FieldTy) {
2791   auto *Field = FieldDecl::Create(
2792       C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2793       C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2794       /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2795   Field->setAccess(AS_public);
2796   DC->addDecl(Field);
2797   return Field;
2798 }
2799 
2800 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2801 
2802   // Make sure the type of the entry is already created. This is the type we
2803   // have to create:
2804   // struct __tgt_offload_entry{
2805   //   void      *addr;       // Pointer to the offload entry info.
2806   //                          // (function or global)
2807   //   char      *name;       // Name of the function or global.
2808   //   size_t     size;       // Size of the entry info (0 if it a function).
2809   // };
2810   if (TgtOffloadEntryQTy.isNull()) {
2811     ASTContext &C = CGM.getContext();
2812     auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2813     RD->startDefinition();
2814     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2815     addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2816     addFieldToRecordDecl(C, RD, C.getSizeType());
2817     RD->completeDefinition();
2818     TgtOffloadEntryQTy = C.getRecordType(RD);
2819   }
2820   return TgtOffloadEntryQTy;
2821 }
2822 
2823 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2824   // These are the types we need to build:
2825   // struct __tgt_device_image{
2826   // void   *ImageStart;       // Pointer to the target code start.
2827   // void   *ImageEnd;         // Pointer to the target code end.
2828   // // We also add the host entries to the device image, as it may be useful
2829   // // for the target runtime to have access to that information.
2830   // __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all
2831   //                                       // the entries.
2832   // __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
2833   //                                       // entries (non inclusive).
2834   // };
2835   if (TgtDeviceImageQTy.isNull()) {
2836     ASTContext &C = CGM.getContext();
2837     auto *RD = C.buildImplicitRecord("__tgt_device_image");
2838     RD->startDefinition();
2839     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2840     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2841     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2842     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2843     RD->completeDefinition();
2844     TgtDeviceImageQTy = C.getRecordType(RD);
2845   }
2846   return TgtDeviceImageQTy;
2847 }
2848 
2849 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2850   // struct __tgt_bin_desc{
2851   //   int32_t              NumDevices;      // Number of devices supported.
2852   //   __tgt_device_image   *DeviceImages;   // Arrays of device images
2853   //                                         // (one per device).
2854   //   __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all the
2855   //                                         // entries.
2856   //   __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
2857   //                                         // entries (non inclusive).
2858   // };
2859   if (TgtBinaryDescriptorQTy.isNull()) {
2860     ASTContext &C = CGM.getContext();
2861     auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2862     RD->startDefinition();
2863     addFieldToRecordDecl(
2864         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2865     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2866     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2867     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2868     RD->completeDefinition();
2869     TgtBinaryDescriptorQTy = C.getRecordType(RD);
2870   }
2871   return TgtBinaryDescriptorQTy;
2872 }
2873 
2874 namespace {
2875 struct PrivateHelpersTy {
2876   PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
2877                    const VarDecl *PrivateElemInit)
2878       : Original(Original), PrivateCopy(PrivateCopy),
2879         PrivateElemInit(PrivateElemInit) {}
2880   const VarDecl *Original;
2881   const VarDecl *PrivateCopy;
2882   const VarDecl *PrivateElemInit;
2883 };
2884 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
2885 } // anonymous namespace
2886 
2887 static RecordDecl *
2888 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
2889   if (!Privates.empty()) {
2890     auto &C = CGM.getContext();
2891     // Build struct .kmp_privates_t. {
2892     //         /*  private vars  */
2893     //       };
2894     auto *RD = C.buildImplicitRecord(".kmp_privates.t");
2895     RD->startDefinition();
2896     for (auto &&Pair : Privates) {
2897       auto *VD = Pair.second.Original;
2898       auto Type = VD->getType();
2899       Type = Type.getNonReferenceType();
2900       auto *FD = addFieldToRecordDecl(C, RD, Type);
2901       if (VD->hasAttrs()) {
2902         for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
2903              E(VD->getAttrs().end());
2904              I != E; ++I)
2905           FD->addAttr(*I);
2906       }
2907     }
2908     RD->completeDefinition();
2909     return RD;
2910   }
2911   return nullptr;
2912 }
2913 
2914 static RecordDecl *
2915 createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
2916                          QualType KmpRoutineEntryPointerQTy) {
2917   auto &C = CGM.getContext();
2918   // Build struct kmp_task_t {
2919   //         void *              shareds;
2920   //         kmp_routine_entry_t routine;
2921   //         kmp_int32           part_id;
2922   //         kmp_routine_entry_t destructors;
2923   //       };
2924   auto *RD = C.buildImplicitRecord("kmp_task_t");
2925   RD->startDefinition();
2926   addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2927   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2928   addFieldToRecordDecl(C, RD, KmpInt32Ty);
2929   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
2930   RD->completeDefinition();
2931   return RD;
2932 }
2933 
2934 static RecordDecl *
2935 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
2936                                      ArrayRef<PrivateDataTy> Privates) {
2937   auto &C = CGM.getContext();
2938   // Build struct kmp_task_t_with_privates {
2939   //         kmp_task_t task_data;
2940   //         .kmp_privates_t. privates;
2941   //       };
2942   auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
2943   RD->startDefinition();
2944   addFieldToRecordDecl(C, RD, KmpTaskTQTy);
2945   if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
2946     addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
2947   }
2948   RD->completeDefinition();
2949   return RD;
2950 }
2951 
2952 /// \brief Emit a proxy function which accepts kmp_task_t as the second
2953 /// argument.
2954 /// \code
2955 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
2956 ///   TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
2957 ///   tt->shareds);
2958 ///   return 0;
2959 /// }
2960 /// \endcode
2961 static llvm::Value *
2962 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
2963                       QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
2964                       QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
2965                       QualType SharedsPtrTy, llvm::Value *TaskFunction,
2966                       llvm::Value *TaskPrivatesMap) {
2967   auto &C = CGM.getContext();
2968   FunctionArgList Args;
2969   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
2970   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
2971                                 /*Id=*/nullptr,
2972                                 KmpTaskTWithPrivatesPtrQTy.withRestrict());
2973   Args.push_back(&GtidArg);
2974   Args.push_back(&TaskTypeArg);
2975   auto &TaskEntryFnInfo =
2976       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
2977   auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
2978   auto *TaskEntry =
2979       llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
2980                              ".omp_task_entry.", &CGM.getModule());
2981   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
2982   CodeGenFunction CGF(CGM);
2983   CGF.disableDebugInfo();
2984   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
2985 
2986   // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
2987   // tt->task_data.shareds);
2988   auto *GtidParam = CGF.EmitLoadOfScalar(
2989       CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
2990   LValue TDBase = CGF.EmitLoadOfPointerLValue(
2991       CGF.GetAddrOfLocalVar(&TaskTypeArg),
2992       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
2993   auto *KmpTaskTWithPrivatesQTyRD =
2994       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
2995   LValue Base =
2996       CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
2997   auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
2998   auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
2999   auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3000   auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
3001 
3002   auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3003   auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3004   auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3005       CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
3006       CGF.ConvertTypeForMem(SharedsPtrTy));
3007 
3008   auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3009   llvm::Value *PrivatesParam;
3010   if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3011     auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3012     PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3013         PrivatesLVal.getPointer(), CGF.VoidPtrTy);
3014   } else {
3015     PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3016   }
3017 
3018   llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
3019                              TaskPrivatesMap, SharedsParam};
3020   CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3021   CGF.EmitStoreThroughLValue(
3022       RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3023       CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3024   CGF.FinishFunction();
3025   return TaskEntry;
3026 }
3027 
3028 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3029                                             SourceLocation Loc,
3030                                             QualType KmpInt32Ty,
3031                                             QualType KmpTaskTWithPrivatesPtrQTy,
3032                                             QualType KmpTaskTWithPrivatesQTy) {
3033   auto &C = CGM.getContext();
3034   FunctionArgList Args;
3035   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3036   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
3037                                 /*Id=*/nullptr,
3038                                 KmpTaskTWithPrivatesPtrQTy.withRestrict());
3039   Args.push_back(&GtidArg);
3040   Args.push_back(&TaskTypeArg);
3041   FunctionType::ExtInfo Info;
3042   auto &DestructorFnInfo =
3043       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3044   auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3045   auto *DestructorFn =
3046       llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3047                              ".omp_task_destructor.", &CGM.getModule());
3048   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3049                                     DestructorFnInfo);
3050   CodeGenFunction CGF(CGM);
3051   CGF.disableDebugInfo();
3052   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3053                     Args);
3054 
3055   LValue Base = CGF.EmitLoadOfPointerLValue(
3056       CGF.GetAddrOfLocalVar(&TaskTypeArg),
3057       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3058   auto *KmpTaskTWithPrivatesQTyRD =
3059       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3060   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3061   Base = CGF.EmitLValueForField(Base, *FI);
3062   for (auto *Field :
3063        cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3064     if (auto DtorKind = Field->getType().isDestructedType()) {
3065       auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3066       CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3067     }
3068   }
3069   CGF.FinishFunction();
3070   return DestructorFn;
3071 }
3072 
3073 /// \brief Emit a privates mapping function for correct handling of private and
3074 /// firstprivate variables.
3075 /// \code
3076 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3077 /// **noalias priv1,...,  <tyn> **noalias privn) {
3078 ///   *priv1 = &.privates.priv1;
3079 ///   ...;
3080 ///   *privn = &.privates.privn;
3081 /// }
3082 /// \endcode
3083 static llvm::Value *
3084 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3085                                ArrayRef<const Expr *> PrivateVars,
3086                                ArrayRef<const Expr *> FirstprivateVars,
3087                                QualType PrivatesQTy,
3088                                ArrayRef<PrivateDataTy> Privates) {
3089   auto &C = CGM.getContext();
3090   FunctionArgList Args;
3091   ImplicitParamDecl TaskPrivatesArg(
3092       C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3093       C.getPointerType(PrivatesQTy).withConst().withRestrict());
3094   Args.push_back(&TaskPrivatesArg);
3095   llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3096   unsigned Counter = 1;
3097   for (auto *E: PrivateVars) {
3098     Args.push_back(ImplicitParamDecl::Create(
3099         C, /*DC=*/nullptr, Loc,
3100         /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3101                             .withConst()
3102                             .withRestrict()));
3103     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3104     PrivateVarsPos[VD] = Counter;
3105     ++Counter;
3106   }
3107   for (auto *E : FirstprivateVars) {
3108     Args.push_back(ImplicitParamDecl::Create(
3109         C, /*DC=*/nullptr, Loc,
3110         /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3111                             .withConst()
3112                             .withRestrict()));
3113     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3114     PrivateVarsPos[VD] = Counter;
3115     ++Counter;
3116   }
3117   auto &TaskPrivatesMapFnInfo =
3118       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3119   auto *TaskPrivatesMapTy =
3120       CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3121   auto *TaskPrivatesMap = llvm::Function::Create(
3122       TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3123       ".omp_task_privates_map.", &CGM.getModule());
3124   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3125                                     TaskPrivatesMapFnInfo);
3126   TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3127   CodeGenFunction CGF(CGM);
3128   CGF.disableDebugInfo();
3129   CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3130                     TaskPrivatesMapFnInfo, Args);
3131 
3132   // *privi = &.privates.privi;
3133   LValue Base = CGF.EmitLoadOfPointerLValue(
3134       CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3135       TaskPrivatesArg.getType()->castAs<PointerType>());
3136   auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3137   Counter = 0;
3138   for (auto *Field : PrivatesQTyRD->fields()) {
3139     auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3140     auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3141     auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3142     auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3143         RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
3144     CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
3145     ++Counter;
3146   }
3147   CGF.FinishFunction();
3148   return TaskPrivatesMap;
3149 }
3150 
3151 static int array_pod_sort_comparator(const PrivateDataTy *P1,
3152                                      const PrivateDataTy *P2) {
3153   return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3154 }
3155 
3156 void CGOpenMPRuntime::emitTaskCall(
3157     CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3158     bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
3159     llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
3160     const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3161     ArrayRef<const Expr *> PrivateCopies,
3162     ArrayRef<const Expr *> FirstprivateVars,
3163     ArrayRef<const Expr *> FirstprivateCopies,
3164     ArrayRef<const Expr *> FirstprivateInits,
3165     ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
3166   if (!CGF.HaveInsertPoint())
3167     return;
3168   auto &C = CGM.getContext();
3169   llvm::SmallVector<PrivateDataTy, 8> Privates;
3170   // Aggregate privates and sort them by the alignment.
3171   auto I = PrivateCopies.begin();
3172   for (auto *E : PrivateVars) {
3173     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3174     Privates.push_back(std::make_pair(
3175         C.getDeclAlign(VD),
3176         PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3177                          /*PrivateElemInit=*/nullptr)));
3178     ++I;
3179   }
3180   I = FirstprivateCopies.begin();
3181   auto IElemInitRef = FirstprivateInits.begin();
3182   for (auto *E : FirstprivateVars) {
3183     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3184     Privates.push_back(std::make_pair(
3185         C.getDeclAlign(VD),
3186         PrivateHelpersTy(
3187             VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3188             cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
3189     ++I;
3190     ++IElemInitRef;
3191   }
3192   llvm::array_pod_sort(Privates.begin(), Privates.end(),
3193                        array_pod_sort_comparator);
3194   auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3195   // Build type kmp_routine_entry_t (if not built yet).
3196   emitKmpRoutineEntryT(KmpInt32Ty);
3197   // Build type kmp_task_t (if not built yet).
3198   if (KmpTaskTQTy.isNull()) {
3199     KmpTaskTQTy = C.getRecordType(
3200         createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
3201   }
3202   auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3203   // Build particular struct kmp_task_t for the given task.
3204   auto *KmpTaskTWithPrivatesQTyRD =
3205       createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3206   auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3207   QualType KmpTaskTWithPrivatesPtrQTy =
3208       C.getPointerType(KmpTaskTWithPrivatesQTy);
3209   auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3210   auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
3211   auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
3212   QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3213 
3214   // Emit initial values for private copies (if any).
3215   llvm::Value *TaskPrivatesMap = nullptr;
3216   auto *TaskPrivatesMapTy =
3217       std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3218                 3)
3219           ->getType();
3220   if (!Privates.empty()) {
3221     auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3222     TaskPrivatesMap = emitTaskPrivateMappingFunction(
3223         CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3224     TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3225         TaskPrivatesMap, TaskPrivatesMapTy);
3226   } else {
3227     TaskPrivatesMap = llvm::ConstantPointerNull::get(
3228         cast<llvm::PointerType>(TaskPrivatesMapTy));
3229   }
3230   // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3231   // kmp_task_t *tt);
3232   auto *TaskEntry = emitProxyTaskFunction(
3233       CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
3234       KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
3235 
3236   // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3237   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3238   // kmp_routine_entry_t *task_entry);
3239   // Task flags. Format is taken from
3240   // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3241   // description of kmp_tasking_flags struct.
3242   const unsigned TiedFlag = 0x1;
3243   const unsigned FinalFlag = 0x2;
3244   unsigned Flags = Tied ? TiedFlag : 0;
3245   auto *TaskFlags =
3246       Final.getPointer()
3247           ? CGF.Builder.CreateSelect(Final.getPointer(),
3248                                      CGF.Builder.getInt32(FinalFlag),
3249                                      CGF.Builder.getInt32(/*C=*/0))
3250           : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3251   TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
3252   auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
3253   llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3254                               getThreadID(CGF, Loc), TaskFlags,
3255                               KmpTaskTWithPrivatesTySize, SharedsSize,
3256                               CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3257                                   TaskEntry, KmpRoutineEntryPtrTy)};
3258   auto *NewTask = CGF.EmitRuntimeCall(
3259       createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
3260   auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3261       NewTask, KmpTaskTWithPrivatesPtrTy);
3262   LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3263                                                KmpTaskTWithPrivatesQTy);
3264   LValue TDBase =
3265       CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
3266   // Fill the data in the resulting kmp_task_t record.
3267   // Copy shareds if there are any.
3268   Address KmpTaskSharedsPtr = Address::invalid();
3269   if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
3270     KmpTaskSharedsPtr =
3271         Address(CGF.EmitLoadOfScalar(
3272                     CGF.EmitLValueForField(
3273                         TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3274                                            KmpTaskTShareds)),
3275                     Loc),
3276                 CGF.getNaturalTypeAlignment(SharedsTy));
3277     CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
3278   }
3279   // Emit initial values for private copies (if any).
3280   bool NeedsCleanup = false;
3281   if (!Privates.empty()) {
3282     auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3283     auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
3284     FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3285     LValue SharedsBase;
3286     if (!FirstprivateVars.empty()) {
3287       SharedsBase = CGF.MakeAddrLValue(
3288           CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3289               KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3290           SharedsTy);
3291     }
3292     CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3293         cast<CapturedStmt>(*D.getAssociatedStmt()));
3294     for (auto &&Pair : Privates) {
3295       auto *VD = Pair.second.PrivateCopy;
3296       auto *Init = VD->getAnyInitializer();
3297       LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3298       if (Init) {
3299         if (auto *Elem = Pair.second.PrivateElemInit) {
3300           auto *OriginalVD = Pair.second.Original;
3301           auto *SharedField = CapturesInfo.lookup(OriginalVD);
3302           auto SharedRefLValue =
3303               CGF.EmitLValueForField(SharedsBase, SharedField);
3304           SharedRefLValue = CGF.MakeAddrLValue(
3305               Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3306               SharedRefLValue.getType(), AlignmentSource::Decl);
3307           QualType Type = OriginalVD->getType();
3308           if (Type->isArrayType()) {
3309             // Initialize firstprivate array.
3310             if (!isa<CXXConstructExpr>(Init) ||
3311                 CGF.isTrivialInitializer(Init)) {
3312               // Perform simple memcpy.
3313               CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3314                                       SharedRefLValue.getAddress(), Type);
3315             } else {
3316               // Initialize firstprivate array using element-by-element
3317               // intialization.
3318               CGF.EmitOMPAggregateAssign(
3319                   PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
3320                   Type, [&CGF, Elem, Init, &CapturesInfo](
3321                             Address DestElement, Address SrcElement) {
3322                     // Clean up any temporaries needed by the initialization.
3323                     CodeGenFunction::OMPPrivateScope InitScope(CGF);
3324                     InitScope.addPrivate(Elem, [SrcElement]() -> Address {
3325                       return SrcElement;
3326                     });
3327                     (void)InitScope.Privatize();
3328                     // Emit initialization for single element.
3329                     CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3330                         CGF, &CapturesInfo);
3331                     CGF.EmitAnyExprToMem(Init, DestElement,
3332                                          Init->getType().getQualifiers(),
3333                                          /*IsInitializer=*/false);
3334                   });
3335             }
3336           } else {
3337             CodeGenFunction::OMPPrivateScope InitScope(CGF);
3338             InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3339               return SharedRefLValue.getAddress();
3340             });
3341             (void)InitScope.Privatize();
3342             CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3343             CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3344                                /*capturedByInit=*/false);
3345           }
3346         } else {
3347           CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3348         }
3349       }
3350       NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
3351       ++FI;
3352     }
3353   }
3354   // Provide pointer to function with destructors for privates.
3355   llvm::Value *DestructorFn =
3356       NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3357                                              KmpTaskTWithPrivatesPtrQTy,
3358                                              KmpTaskTWithPrivatesQTy)
3359                    : llvm::ConstantPointerNull::get(
3360                          cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3361   LValue Destructor = CGF.EmitLValueForField(
3362       TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3363   CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3364                             DestructorFn, KmpRoutineEntryPtrTy),
3365                         Destructor);
3366 
3367   // Process list of dependences.
3368   Address DependenciesArray = Address::invalid();
3369   unsigned NumDependencies = Dependences.size();
3370   if (NumDependencies) {
3371     // Dependence kind for RTL.
3372     enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
3373     enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3374     RecordDecl *KmpDependInfoRD;
3375     QualType FlagsTy =
3376         C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
3377     llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3378     if (KmpDependInfoTy.isNull()) {
3379       KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3380       KmpDependInfoRD->startDefinition();
3381       addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3382       addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3383       addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3384       KmpDependInfoRD->completeDefinition();
3385       KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3386     } else {
3387       KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3388     }
3389     CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
3390     // Define type kmp_depend_info[<Dependences.size()>];
3391     QualType KmpDependInfoArrayTy = C.getConstantArrayType(
3392         KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
3393         ArrayType::Normal, /*IndexTypeQuals=*/0);
3394     // kmp_depend_info[<Dependences.size()>] deps;
3395     DependenciesArray = CGF.CreateMemTemp(KmpDependInfoArrayTy);
3396     for (unsigned i = 0; i < NumDependencies; ++i) {
3397       const Expr *E = Dependences[i].second;
3398       auto Addr = CGF.EmitLValue(E);
3399       llvm::Value *Size;
3400       QualType Ty = E->getType();
3401       if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3402         LValue UpAddrLVal =
3403             CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3404         llvm::Value *UpAddr =
3405             CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
3406         llvm::Value *LowIntPtr =
3407             CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
3408         llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3409         Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
3410       } else
3411         Size = CGF.getTypeSize(Ty);
3412       auto Base = CGF.MakeAddrLValue(
3413           CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
3414           KmpDependInfoTy);
3415       // deps[i].base_addr = &<Dependences[i].second>;
3416       auto BaseAddrLVal = CGF.EmitLValueForField(
3417           Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
3418       CGF.EmitStoreOfScalar(
3419           CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3420           BaseAddrLVal);
3421       // deps[i].len = sizeof(<Dependences[i].second>);
3422       auto LenLVal = CGF.EmitLValueForField(
3423           Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3424       CGF.EmitStoreOfScalar(Size, LenLVal);
3425       // deps[i].flags = <Dependences[i].first>;
3426       RTLDependenceKindTy DepKind;
3427       switch (Dependences[i].first) {
3428       case OMPC_DEPEND_in:
3429         DepKind = DepIn;
3430         break;
3431       // Out and InOut dependencies must use the same code.
3432       case OMPC_DEPEND_out:
3433       case OMPC_DEPEND_inout:
3434         DepKind = DepInOut;
3435         break;
3436       case OMPC_DEPEND_source:
3437       case OMPC_DEPEND_sink:
3438       case OMPC_DEPEND_unknown:
3439         llvm_unreachable("Unknown task dependence type");
3440       }
3441       auto FlagsLVal = CGF.EmitLValueForField(
3442           Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3443       CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3444                             FlagsLVal);
3445     }
3446     DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3447         CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
3448         CGF.VoidPtrTy);
3449   }
3450 
3451   // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3452   // libcall.
3453   // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
3454   // *new_task);
3455   // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3456   // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3457   // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3458   // list is not empty
3459   auto *ThreadID = getThreadID(CGF, Loc);
3460   auto *UpLoc = emitUpdateLocation(CGF, Loc);
3461   llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3462   llvm::Value *DepTaskArgs[7];
3463   if (NumDependencies) {
3464     DepTaskArgs[0] = UpLoc;
3465     DepTaskArgs[1] = ThreadID;
3466     DepTaskArgs[2] = NewTask;
3467     DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3468     DepTaskArgs[4] = DependenciesArray.getPointer();
3469     DepTaskArgs[5] = CGF.Builder.getInt32(0);
3470     DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3471   }
3472   auto &&ThenCodeGen = [this, NumDependencies,
3473                         &TaskArgs, &DepTaskArgs](CodeGenFunction &CGF) {
3474     // TODO: add check for untied tasks.
3475     if (NumDependencies) {
3476       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps),
3477                           DepTaskArgs);
3478     } else {
3479       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
3480                           TaskArgs);
3481     }
3482   };
3483   typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
3484       IfCallEndCleanup;
3485 
3486   llvm::Value *DepWaitTaskArgs[6];
3487   if (NumDependencies) {
3488     DepWaitTaskArgs[0] = UpLoc;
3489     DepWaitTaskArgs[1] = ThreadID;
3490     DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3491     DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3492     DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3493     DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3494   }
3495   auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
3496                         NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF) {
3497     CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3498     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3499     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3500     // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3501     // is specified.
3502     if (NumDependencies)
3503       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
3504                           DepWaitTaskArgs);
3505     // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3506     // kmp_task_t *new_task);
3507     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
3508                         TaskArgs);
3509     // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3510     // kmp_task_t *new_task);
3511     CGF.EHStack.pushCleanup<IfCallEndCleanup>(
3512         NormalAndEHCleanup,
3513         createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
3514         llvm::makeArrayRef(TaskArgs));
3515 
3516     // Call proxy_task_entry(gtid, new_task);
3517     llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3518     CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3519   };
3520 
3521   if (IfCond) {
3522     emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
3523   } else {
3524     CodeGenFunction::RunCleanupsScope Scope(CGF);
3525     ThenCodeGen(CGF);
3526   }
3527 }
3528 
3529 /// \brief Emit reduction operation for each element of array (required for
3530 /// array sections) LHS op = RHS.
3531 /// \param Type Type of array.
3532 /// \param LHSVar Variable on the left side of the reduction operation
3533 /// (references element of array in original variable).
3534 /// \param RHSVar Variable on the right side of the reduction operation
3535 /// (references element of array in original variable).
3536 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
3537 /// RHSVar.
3538 static void EmitOMPAggregateReduction(
3539     CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3540     const VarDecl *RHSVar,
3541     const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3542                                   const Expr *, const Expr *)> &RedOpGen,
3543     const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3544     const Expr *UpExpr = nullptr) {
3545   // Perform element-by-element initialization.
3546   QualType ElementTy;
3547   Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3548   Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3549 
3550   // Drill down to the base element type on both arrays.
3551   auto ArrayTy = Type->getAsArrayTypeUnsafe();
3552   auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3553 
3554   auto RHSBegin = RHSAddr.getPointer();
3555   auto LHSBegin = LHSAddr.getPointer();
3556   // Cast from pointer to array type to pointer to single element.
3557   auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3558   // The basic structure here is a while-do loop.
3559   auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3560   auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3561   auto IsEmpty =
3562       CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3563   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3564 
3565   // Enter the loop body, making that address the current address.
3566   auto EntryBB = CGF.Builder.GetInsertBlock();
3567   CGF.EmitBlock(BodyBB);
3568 
3569   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3570 
3571   llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3572       RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3573   RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3574   Address RHSElementCurrent =
3575       Address(RHSElementPHI,
3576               RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3577 
3578   llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3579       LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3580   LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3581   Address LHSElementCurrent =
3582       Address(LHSElementPHI,
3583               LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3584 
3585   // Emit copy.
3586   CodeGenFunction::OMPPrivateScope Scope(CGF);
3587   Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3588   Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3589   Scope.Privatize();
3590   RedOpGen(CGF, XExpr, EExpr, UpExpr);
3591   Scope.ForceCleanup();
3592 
3593   // Shift the address forward by one element.
3594   auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3595       LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3596   auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3597       RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3598   // Check whether we've reached the end.
3599   auto Done =
3600       CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3601   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3602   LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3603   RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3604 
3605   // Done.
3606   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3607 }
3608 
3609 /// Emit reduction combiner. If the combiner is a simple expression emit it as
3610 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
3611 /// UDR combiner function.
3612 static void emitReductionCombiner(CodeGenFunction &CGF,
3613                                   const Expr *ReductionOp) {
3614   if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
3615     if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
3616       if (auto *DRE =
3617               dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
3618         if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
3619           std::pair<llvm::Function *, llvm::Function *> Reduction =
3620               CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
3621           RValue Func = RValue::get(Reduction.first);
3622           CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
3623           CGF.EmitIgnoredExpr(ReductionOp);
3624           return;
3625         }
3626   CGF.EmitIgnoredExpr(ReductionOp);
3627 }
3628 
3629 static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3630                                           llvm::Type *ArgsType,
3631                                           ArrayRef<const Expr *> Privates,
3632                                           ArrayRef<const Expr *> LHSExprs,
3633                                           ArrayRef<const Expr *> RHSExprs,
3634                                           ArrayRef<const Expr *> ReductionOps) {
3635   auto &C = CGM.getContext();
3636 
3637   // void reduction_func(void *LHSArg, void *RHSArg);
3638   FunctionArgList Args;
3639   ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3640                            C.VoidPtrTy);
3641   ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3642                            C.VoidPtrTy);
3643   Args.push_back(&LHSArg);
3644   Args.push_back(&RHSArg);
3645   auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3646   auto *Fn = llvm::Function::Create(
3647       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3648       ".omp.reduction.reduction_func", &CGM.getModule());
3649   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
3650   CodeGenFunction CGF(CGM);
3651   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3652 
3653   // Dst = (void*[n])(LHSArg);
3654   // Src = (void*[n])(RHSArg);
3655   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3656       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3657       ArgsType), CGF.getPointerAlign());
3658   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3659       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3660       ArgsType), CGF.getPointerAlign());
3661 
3662   //  ...
3663   //  *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3664   //  ...
3665   CodeGenFunction::OMPPrivateScope Scope(CGF);
3666   auto IPriv = Privates.begin();
3667   unsigned Idx = 0;
3668   for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
3669     auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3670     Scope.addPrivate(RHSVar, [&]() -> Address {
3671       return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
3672     });
3673     auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3674     Scope.addPrivate(LHSVar, [&]() -> Address {
3675       return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
3676     });
3677     QualType PrivTy = (*IPriv)->getType();
3678     if (PrivTy->isVariablyModifiedType()) {
3679       // Get array size and emit VLA type.
3680       ++Idx;
3681       Address Elem =
3682           CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3683       llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
3684       auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3685       auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
3686       CodeGenFunction::OpaqueValueMapping OpaqueMap(
3687           CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
3688       CGF.EmitVariablyModifiedType(PrivTy);
3689     }
3690   }
3691   Scope.Privatize();
3692   IPriv = Privates.begin();
3693   auto ILHS = LHSExprs.begin();
3694   auto IRHS = RHSExprs.begin();
3695   for (auto *E : ReductionOps) {
3696     if ((*IPriv)->getType()->isArrayType()) {
3697       // Emit reduction for array section.
3698       auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3699       auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3700       EmitOMPAggregateReduction(
3701           CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3702           [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
3703             emitReductionCombiner(CGF, E);
3704           });
3705     } else
3706       // Emit reduction for array subscript or single variable.
3707       emitReductionCombiner(CGF, E);
3708     ++IPriv;
3709     ++ILHS;
3710     ++IRHS;
3711   }
3712   Scope.ForceCleanup();
3713   CGF.FinishFunction();
3714   return Fn;
3715 }
3716 
3717 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
3718                                     ArrayRef<const Expr *> Privates,
3719                                     ArrayRef<const Expr *> LHSExprs,
3720                                     ArrayRef<const Expr *> RHSExprs,
3721                                     ArrayRef<const Expr *> ReductionOps,
3722                                     bool WithNowait, bool SimpleReduction) {
3723   if (!CGF.HaveInsertPoint())
3724     return;
3725   // Next code should be emitted for reduction:
3726   //
3727   // static kmp_critical_name lock = { 0 };
3728   //
3729   // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
3730   //  *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
3731   //  ...
3732   //  *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
3733   //  *(Type<n>-1*)rhs[<n>-1]);
3734   // }
3735   //
3736   // ...
3737   // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
3738   // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3739   // RedList, reduce_func, &<lock>)) {
3740   // case 1:
3741   //  ...
3742   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3743   //  ...
3744   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3745   // break;
3746   // case 2:
3747   //  ...
3748   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3749   //  ...
3750   // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
3751   // break;
3752   // default:;
3753   // }
3754   //
3755   // if SimpleReduction is true, only the next code is generated:
3756   //  ...
3757   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3758   //  ...
3759 
3760   auto &C = CGM.getContext();
3761 
3762   if (SimpleReduction) {
3763     CodeGenFunction::RunCleanupsScope Scope(CGF);
3764     auto IPriv = Privates.begin();
3765     auto ILHS = LHSExprs.begin();
3766     auto IRHS = RHSExprs.begin();
3767     for (auto *E : ReductionOps) {
3768       if ((*IPriv)->getType()->isArrayType()) {
3769         auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3770         auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3771         EmitOMPAggregateReduction(
3772             CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3773             [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3774                 const Expr *) { emitReductionCombiner(CGF, E); });
3775       } else
3776         emitReductionCombiner(CGF, E);
3777       ++IPriv;
3778       ++ILHS;
3779       ++IRHS;
3780     }
3781     return;
3782   }
3783 
3784   // 1. Build a list of reduction variables.
3785   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3786   auto Size = RHSExprs.size();
3787   for (auto *E : Privates) {
3788     if (E->getType()->isVariablyModifiedType())
3789       // Reserve place for array size.
3790       ++Size;
3791   }
3792   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3793   QualType ReductionArrayTy =
3794       C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3795                              /*IndexTypeQuals=*/0);
3796   Address ReductionList =
3797       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3798   auto IPriv = Privates.begin();
3799   unsigned Idx = 0;
3800   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3801     Address Elem =
3802       CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
3803     CGF.Builder.CreateStore(
3804         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3805             CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3806         Elem);
3807     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3808       // Store array size.
3809       ++Idx;
3810       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3811                                              CGF.getPointerSize());
3812       llvm::Value *Size = CGF.Builder.CreateIntCast(
3813           CGF.getVLASize(
3814                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3815               .first,
3816           CGF.SizeTy, /*isSigned=*/false);
3817       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3818                               Elem);
3819     }
3820   }
3821 
3822   // 2. Emit reduce_func().
3823   auto *ReductionFn = emitReductionFunction(
3824       CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3825       LHSExprs, RHSExprs, ReductionOps);
3826 
3827   // 3. Create static kmp_critical_name lock = { 0 };
3828   auto *Lock = getCriticalRegionLock(".reduction");
3829 
3830   // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
3831   // RedList, reduce_func, &<lock>);
3832   auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
3833   auto *ThreadId = getThreadID(CGF, Loc);
3834   auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3835   auto *RL =
3836     CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
3837                                                     CGF.VoidPtrTy);
3838   llvm::Value *Args[] = {
3839       IdentTLoc,                             // ident_t *<loc>
3840       ThreadId,                              // i32 <gtid>
3841       CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
3842       ReductionArrayTySize,                  // size_type sizeof(RedList)
3843       RL,                                    // void *RedList
3844       ReductionFn, // void (*) (void *, void *) <reduce_func>
3845       Lock         // kmp_critical_name *&<lock>
3846   };
3847   auto Res = CGF.EmitRuntimeCall(
3848       createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
3849                                        : OMPRTL__kmpc_reduce),
3850       Args);
3851 
3852   // 5. Build switch(res)
3853   auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
3854   auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
3855 
3856   // 6. Build case 1:
3857   //  ...
3858   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
3859   //  ...
3860   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3861   // break;
3862   auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
3863   SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
3864   CGF.EmitBlock(Case1BB);
3865 
3866   {
3867     CodeGenFunction::RunCleanupsScope Scope(CGF);
3868     // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
3869     llvm::Value *EndArgs[] = {
3870         IdentTLoc, // ident_t *<loc>
3871         ThreadId,  // i32 <gtid>
3872         Lock       // kmp_critical_name *&<lock>
3873     };
3874     CGF.EHStack
3875         .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3876             NormalAndEHCleanup,
3877             createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
3878                                              : OMPRTL__kmpc_end_reduce),
3879             llvm::makeArrayRef(EndArgs));
3880     auto IPriv = Privates.begin();
3881     auto ILHS = LHSExprs.begin();
3882     auto IRHS = RHSExprs.begin();
3883     for (auto *E : ReductionOps) {
3884       if ((*IPriv)->getType()->isArrayType()) {
3885         // Emit reduction for array section.
3886         auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3887         auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3888         EmitOMPAggregateReduction(
3889             CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3890             [=](CodeGenFunction &CGF, const Expr *, const Expr *,
3891                 const Expr *) { emitReductionCombiner(CGF, E); });
3892       } else
3893         // Emit reduction for array subscript or single variable.
3894         emitReductionCombiner(CGF, E);
3895       ++IPriv;
3896       ++ILHS;
3897       ++IRHS;
3898     }
3899   }
3900 
3901   CGF.EmitBranch(DefaultBB);
3902 
3903   // 7. Build case 2:
3904   //  ...
3905   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
3906   //  ...
3907   // break;
3908   auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
3909   SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
3910   CGF.EmitBlock(Case2BB);
3911 
3912   {
3913     CodeGenFunction::RunCleanupsScope Scope(CGF);
3914     if (!WithNowait) {
3915       // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
3916       llvm::Value *EndArgs[] = {
3917           IdentTLoc, // ident_t *<loc>
3918           ThreadId,  // i32 <gtid>
3919           Lock       // kmp_critical_name *&<lock>
3920       };
3921       CGF.EHStack
3922           .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
3923               NormalAndEHCleanup,
3924               createRuntimeFunction(OMPRTL__kmpc_end_reduce),
3925               llvm::makeArrayRef(EndArgs));
3926     }
3927     auto ILHS = LHSExprs.begin();
3928     auto IRHS = RHSExprs.begin();
3929     auto IPriv = Privates.begin();
3930     for (auto *E : ReductionOps) {
3931         const Expr *XExpr = nullptr;
3932         const Expr *EExpr = nullptr;
3933         const Expr *UpExpr = nullptr;
3934         BinaryOperatorKind BO = BO_Comma;
3935         if (auto *BO = dyn_cast<BinaryOperator>(E)) {
3936           if (BO->getOpcode() == BO_Assign) {
3937             XExpr = BO->getLHS();
3938             UpExpr = BO->getRHS();
3939           }
3940         }
3941         // Try to emit update expression as a simple atomic.
3942         auto *RHSExpr = UpExpr;
3943         if (RHSExpr) {
3944           // Analyze RHS part of the whole expression.
3945           if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
3946                   RHSExpr->IgnoreParenImpCasts())) {
3947             // If this is a conditional operator, analyze its condition for
3948             // min/max reduction operator.
3949             RHSExpr = ACO->getCond();
3950           }
3951           if (auto *BORHS =
3952                   dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
3953             EExpr = BORHS->getRHS();
3954             BO = BORHS->getOpcode();
3955           }
3956         }
3957         if (XExpr) {
3958           auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3959           auto &&AtomicRedGen = [this, BO, VD, IPriv,
3960                                  Loc](CodeGenFunction &CGF, const Expr *XExpr,
3961                                       const Expr *EExpr, const Expr *UpExpr) {
3962             LValue X = CGF.EmitLValue(XExpr);
3963             RValue E;
3964             if (EExpr)
3965               E = CGF.EmitAnyExpr(EExpr);
3966             CGF.EmitOMPAtomicSimpleUpdateExpr(
3967                 X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
3968                 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
3969                   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
3970                   PrivateScope.addPrivate(
3971                       VD, [&CGF, VD, XRValue, Loc]() -> Address {
3972                         Address LHSTemp = CGF.CreateMemTemp(VD->getType());
3973                         CGF.emitOMPSimpleStore(
3974                             CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
3975                             VD->getType().getNonReferenceType(), Loc);
3976                         return LHSTemp;
3977                       });
3978                   (void)PrivateScope.Privatize();
3979                   return CGF.EmitAnyExpr(UpExpr);
3980                 });
3981           };
3982           if ((*IPriv)->getType()->isArrayType()) {
3983             // Emit atomic reduction for array section.
3984             auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3985             EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
3986                                       AtomicRedGen, XExpr, EExpr, UpExpr);
3987           } else
3988             // Emit atomic reduction for array subscript or single variable.
3989             AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
3990         } else {
3991           // Emit as a critical region.
3992           auto &&CritRedGen = [this, E, Loc](CodeGenFunction &CGF, const Expr *,
3993                                              const Expr *, const Expr *) {
3994             emitCriticalRegion(
3995                 CGF, ".atomic_reduction",
3996                 [=](CodeGenFunction &CGF) { emitReductionCombiner(CGF, E); },
3997                 Loc);
3998           };
3999           if ((*IPriv)->getType()->isArrayType()) {
4000             auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4001             auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4002             EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4003                                       CritRedGen);
4004           } else
4005             CritRedGen(CGF, nullptr, nullptr, nullptr);
4006         }
4007       ++ILHS;
4008       ++IRHS;
4009       ++IPriv;
4010     }
4011   }
4012 
4013   CGF.EmitBranch(DefaultBB);
4014   CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4015 }
4016 
4017 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4018                                        SourceLocation Loc) {
4019   if (!CGF.HaveInsertPoint())
4020     return;
4021   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4022   // global_tid);
4023   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4024   // Ignore return result until untied tasks are supported.
4025   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
4026 }
4027 
4028 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
4029                                            OpenMPDirectiveKind InnerKind,
4030                                            const RegionCodeGenTy &CodeGen,
4031                                            bool HasCancel) {
4032   if (!CGF.HaveInsertPoint())
4033     return;
4034   InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
4035   CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
4036 }
4037 
4038 namespace {
4039 enum RTCancelKind {
4040   CancelNoreq = 0,
4041   CancelParallel = 1,
4042   CancelLoop = 2,
4043   CancelSections = 3,
4044   CancelTaskgroup = 4
4045 };
4046 } // anonymous namespace
4047 
4048 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4049   RTCancelKind CancelKind = CancelNoreq;
4050   if (CancelRegion == OMPD_parallel)
4051     CancelKind = CancelParallel;
4052   else if (CancelRegion == OMPD_for)
4053     CancelKind = CancelLoop;
4054   else if (CancelRegion == OMPD_sections)
4055     CancelKind = CancelSections;
4056   else {
4057     assert(CancelRegion == OMPD_taskgroup);
4058     CancelKind = CancelTaskgroup;
4059   }
4060   return CancelKind;
4061 }
4062 
4063 void CGOpenMPRuntime::emitCancellationPointCall(
4064     CodeGenFunction &CGF, SourceLocation Loc,
4065     OpenMPDirectiveKind CancelRegion) {
4066   if (!CGF.HaveInsertPoint())
4067     return;
4068   // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4069   // global_tid, kmp_int32 cncl_kind);
4070   if (auto *OMPRegionInfo =
4071           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4072     if (OMPRegionInfo->hasCancel()) {
4073       llvm::Value *Args[] = {
4074           emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4075           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4076       // Ignore return result until untied tasks are supported.
4077       auto *Result = CGF.EmitRuntimeCall(
4078           createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4079       // if (__kmpc_cancellationpoint()) {
4080       //  __kmpc_cancel_barrier();
4081       //   exit from construct;
4082       // }
4083       auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4084       auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4085       auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4086       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4087       CGF.EmitBlock(ExitBB);
4088       // __kmpc_cancel_barrier();
4089       emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4090       // exit from construct;
4091       auto CancelDest =
4092           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4093       CGF.EmitBranchThroughCleanup(CancelDest);
4094       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4095     }
4096   }
4097 }
4098 
4099 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
4100                                      const Expr *IfCond,
4101                                      OpenMPDirectiveKind CancelRegion) {
4102   if (!CGF.HaveInsertPoint())
4103     return;
4104   // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4105   // kmp_int32 cncl_kind);
4106   if (auto *OMPRegionInfo =
4107           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
4108     auto &&ThenGen = [this, Loc, CancelRegion,
4109                       OMPRegionInfo](CodeGenFunction &CGF) {
4110       llvm::Value *Args[] = {
4111           emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4112           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4113       // Ignore return result until untied tasks are supported.
4114       auto *Result =
4115           CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
4116       // if (__kmpc_cancel()) {
4117       //  __kmpc_cancel_barrier();
4118       //   exit from construct;
4119       // }
4120       auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4121       auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4122       auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4123       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4124       CGF.EmitBlock(ExitBB);
4125       // __kmpc_cancel_barrier();
4126       emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
4127       // exit from construct;
4128       auto CancelDest =
4129           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4130       CGF.EmitBranchThroughCleanup(CancelDest);
4131       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4132     };
4133     if (IfCond)
4134       emitOMPIfClause(CGF, IfCond, ThenGen, [](CodeGenFunction &) {});
4135     else
4136       ThenGen(CGF);
4137   }
4138 }
4139 
4140 /// \brief Obtain information that uniquely identifies a target entry. This
4141 /// consists of the file and device IDs as well as line number associated with
4142 /// the relevant entry source location.
4143 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4144                                      unsigned &DeviceID, unsigned &FileID,
4145                                      unsigned &LineNum) {
4146 
4147   auto &SM = C.getSourceManager();
4148 
4149   // The loc should be always valid and have a file ID (the user cannot use
4150   // #pragma directives in macros)
4151 
4152   assert(Loc.isValid() && "Source location is expected to be always valid.");
4153   assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4154 
4155   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4156   assert(PLoc.isValid() && "Source location is expected to be always valid.");
4157 
4158   llvm::sys::fs::UniqueID ID;
4159   if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4160     llvm_unreachable("Source file with target region no longer exists!");
4161 
4162   DeviceID = ID.getDevice();
4163   FileID = ID.getFile();
4164   LineNum = PLoc.getLine();
4165 }
4166 
4167 void CGOpenMPRuntime::emitTargetOutlinedFunction(
4168     const OMPExecutableDirective &D, StringRef ParentName,
4169     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4170     bool IsOffloadEntry) {
4171   assert(!ParentName.empty() && "Invalid target region parent name!");
4172 
4173   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4174 
4175   // Emit target region as a standalone region.
4176   auto &&CodeGen = [&CS, &D](CodeGenFunction &CGF) {
4177     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4178     (void)CGF.EmitOMPFirstprivateClause(D, PrivateScope);
4179     CGF.EmitOMPPrivateClause(D, PrivateScope);
4180     (void)PrivateScope.Privatize();
4181 
4182     CGF.EmitStmt(CS.getCapturedStmt());
4183   };
4184 
4185   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4186                                    IsOffloadEntry, CodeGen);
4187 }
4188 
4189 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4190     const OMPExecutableDirective &D, StringRef ParentName,
4191     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4192     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
4193   // Create a unique name for the entry function using the source location
4194   // information of the current target region. The name will be something like:
4195   //
4196   // __omp_offloading_DD_FFFF_PP_lBB
4197   //
4198   // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
4199   // mangled name of the function that encloses the target region and BB is the
4200   // line number of the target region.
4201 
4202   unsigned DeviceID;
4203   unsigned FileID;
4204   unsigned Line;
4205   getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
4206                            Line);
4207   SmallString<64> EntryFnName;
4208   {
4209     llvm::raw_svector_ostream OS(EntryFnName);
4210     OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4211        << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
4212   }
4213 
4214   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4215 
4216   CodeGenFunction CGF(CGM, true);
4217   CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
4218   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4219 
4220   OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4221 
4222   // If this target outline function is not an offload entry, we don't need to
4223   // register it.
4224   if (!IsOffloadEntry)
4225     return;
4226 
4227   // The target region ID is used by the runtime library to identify the current
4228   // target region, so it only has to be unique and not necessarily point to
4229   // anything. It could be the pointer to the outlined function that implements
4230   // the target region, but we aren't using that so that the compiler doesn't
4231   // need to keep that, and could therefore inline the host function if proven
4232   // worthwhile during optimization. In the other hand, if emitting code for the
4233   // device, the ID has to be the function address so that it can retrieved from
4234   // the offloading entry and launched by the runtime library. We also mark the
4235   // outlined function to have external linkage in case we are emitting code for
4236   // the device, because these functions will be entry points to the device.
4237 
4238   if (CGM.getLangOpts().OpenMPIsDevice) {
4239     OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4240     OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4241   } else
4242     OutlinedFnID = new llvm::GlobalVariable(
4243         CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4244         llvm::GlobalValue::PrivateLinkage,
4245         llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4246 
4247   // Register the information for the entry associated with this target region.
4248   OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
4249       DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
4250 }
4251 
4252 /// \brief Emit the num_teams clause of an enclosed teams directive at the
4253 /// target region scope. If there is no teams directive associated with the
4254 /// target directive, or if there is no num_teams clause associated with the
4255 /// enclosed teams directive, return nullptr.
4256 static llvm::Value *
4257 emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4258                                      CodeGenFunction &CGF,
4259                                      const OMPExecutableDirective &D) {
4260 
4261   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4262                                               "teams directive expected to be "
4263                                               "emitted only for the host!");
4264 
4265   // FIXME: For the moment we do not support combined directives with target and
4266   // teams, so we do not expect to get any num_teams clause in the provided
4267   // directive. Once we support that, this assertion can be replaced by the
4268   // actual emission of the clause expression.
4269   assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4270          "Not expecting clause in directive.");
4271 
4272   // If the current target region has a teams region enclosed, we need to get
4273   // the number of teams to pass to the runtime function call. This is done
4274   // by generating the expression in a inlined region. This is required because
4275   // the expression is captured in the enclosing target environment when the
4276   // teams directive is not combined with target.
4277 
4278   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4279 
4280   // FIXME: Accommodate other combined directives with teams when they become
4281   // available.
4282   if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4283     if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4284       CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4285       CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4286       llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4287       return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4288                                        /*IsSigned=*/true);
4289     }
4290 
4291     // If we have an enclosed teams directive but no num_teams clause we use
4292     // the default value 0.
4293     return CGF.Builder.getInt32(0);
4294   }
4295 
4296   // No teams associated with the directive.
4297   return nullptr;
4298 }
4299 
4300 /// \brief Emit the thread_limit clause of an enclosed teams directive at the
4301 /// target region scope. If there is no teams directive associated with the
4302 /// target directive, or if there is no thread_limit clause associated with the
4303 /// enclosed teams directive, return nullptr.
4304 static llvm::Value *
4305 emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4306                                         CodeGenFunction &CGF,
4307                                         const OMPExecutableDirective &D) {
4308 
4309   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4310                                               "teams directive expected to be "
4311                                               "emitted only for the host!");
4312 
4313   // FIXME: For the moment we do not support combined directives with target and
4314   // teams, so we do not expect to get any thread_limit clause in the provided
4315   // directive. Once we support that, this assertion can be replaced by the
4316   // actual emission of the clause expression.
4317   assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4318          "Not expecting clause in directive.");
4319 
4320   // If the current target region has a teams region enclosed, we need to get
4321   // the thread limit to pass to the runtime function call. This is done
4322   // by generating the expression in a inlined region. This is required because
4323   // the expression is captured in the enclosing target environment when the
4324   // teams directive is not combined with target.
4325 
4326   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4327 
4328   // FIXME: Accommodate other combined directives with teams when they become
4329   // available.
4330   if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4331     if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4332       CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4333       CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4334       llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4335       return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4336                                        /*IsSigned=*/true);
4337     }
4338 
4339     // If we have an enclosed teams directive but no thread_limit clause we use
4340     // the default value 0.
4341     return CGF.Builder.getInt32(0);
4342   }
4343 
4344   // No teams associated with the directive.
4345   return nullptr;
4346 }
4347 
4348 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
4349                                      const OMPExecutableDirective &D,
4350                                      llvm::Value *OutlinedFn,
4351                                      llvm::Value *OutlinedFnID,
4352                                      const Expr *IfCond, const Expr *Device,
4353                                      ArrayRef<llvm::Value *> CapturedVars) {
4354   if (!CGF.HaveInsertPoint())
4355     return;
4356   /// \brief Values for bit flags used to specify the mapping type for
4357   /// offloading.
4358   enum OpenMPOffloadMappingFlags {
4359     /// \brief Allocate memory on the device and move data from host to device.
4360     OMP_MAP_TO = 0x01,
4361     /// \brief Allocate memory on the device and move data from device to host.
4362     OMP_MAP_FROM = 0x02,
4363     /// \brief The element passed to the device is a pointer.
4364     OMP_MAP_PTR = 0x20,
4365     /// \brief Pass the element to the device by value.
4366     OMP_MAP_BYCOPY = 0x80,
4367   };
4368 
4369   enum OpenMPOffloadingReservedDeviceIDs {
4370     /// \brief Device ID if the device was not defined, runtime should get it
4371     /// from environment variables in the spec.
4372     OMP_DEVICEID_UNDEF = -1,
4373   };
4374 
4375   assert(OutlinedFn && "Invalid outlined function!");
4376 
4377   auto &Ctx = CGF.getContext();
4378 
4379   // Fill up the arrays with the all the captured variables.
4380   SmallVector<llvm::Value *, 16> BasePointers;
4381   SmallVector<llvm::Value *, 16> Pointers;
4382   SmallVector<llvm::Value *, 16> Sizes;
4383   SmallVector<unsigned, 16> MapTypes;
4384 
4385   bool hasVLACaptures = false;
4386 
4387   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4388   auto RI = CS.getCapturedRecordDecl()->field_begin();
4389   // auto II = CS.capture_init_begin();
4390   auto CV = CapturedVars.begin();
4391   for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
4392                                             CE = CS.capture_end();
4393        CI != CE; ++CI, ++RI, ++CV) {
4394     StringRef Name;
4395     QualType Ty;
4396     llvm::Value *BasePointer;
4397     llvm::Value *Pointer;
4398     llvm::Value *Size;
4399     unsigned MapType;
4400 
4401     // VLA sizes are passed to the outlined region by copy.
4402     if (CI->capturesVariableArrayType()) {
4403       BasePointer = Pointer = *CV;
4404       Size = CGF.getTypeSize(RI->getType());
4405       // Copy to the device as an argument. No need to retrieve it.
4406       MapType = OMP_MAP_BYCOPY;
4407       hasVLACaptures = true;
4408     } else if (CI->capturesThis()) {
4409       BasePointer = Pointer = *CV;
4410       const PointerType *PtrTy = cast<PointerType>(RI->getType().getTypePtr());
4411       Size = CGF.getTypeSize(PtrTy->getPointeeType());
4412       // Default map type.
4413       MapType = OMP_MAP_TO | OMP_MAP_FROM;
4414     } else if (CI->capturesVariableByCopy()) {
4415       MapType = OMP_MAP_BYCOPY;
4416       if (!RI->getType()->isAnyPointerType()) {
4417         // If the field is not a pointer, we need to save the actual value and
4418         // load it as a void pointer.
4419         auto DstAddr = CGF.CreateMemTemp(
4420             Ctx.getUIntPtrType(),
4421             Twine(CI->getCapturedVar()->getName()) + ".casted");
4422         LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
4423 
4424         auto *SrcAddrVal = CGF.EmitScalarConversion(
4425             DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
4426             Ctx.getPointerType(RI->getType()), SourceLocation());
4427         LValue SrcLV =
4428             CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
4429 
4430         // Store the value using the source type pointer.
4431         CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
4432 
4433         // Load the value using the destination type pointer.
4434         BasePointer = Pointer =
4435             CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
4436       } else {
4437         MapType |= OMP_MAP_PTR;
4438         BasePointer = Pointer = *CV;
4439       }
4440       Size = CGF.getTypeSize(RI->getType());
4441     } else {
4442       assert(CI->capturesVariable() && "Expected captured reference.");
4443       BasePointer = Pointer = *CV;
4444 
4445       const ReferenceType *PtrTy =
4446           cast<ReferenceType>(RI->getType().getTypePtr());
4447       QualType ElementType = PtrTy->getPointeeType();
4448       Size = CGF.getTypeSize(ElementType);
4449       // The default map type for a scalar/complex type is 'to' because by
4450       // default the value doesn't have to be retrieved. For an aggregate type,
4451       // the default is 'tofrom'.
4452       MapType = ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
4453                                                : OMP_MAP_TO;
4454       if (ElementType->isAnyPointerType())
4455         MapType |= OMP_MAP_PTR;
4456     }
4457 
4458     BasePointers.push_back(BasePointer);
4459     Pointers.push_back(Pointer);
4460     Sizes.push_back(Size);
4461     MapTypes.push_back(MapType);
4462   }
4463 
4464   // Keep track on whether the host function has to be executed.
4465   auto OffloadErrorQType =
4466       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
4467   auto OffloadError = CGF.MakeAddrLValue(
4468       CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
4469       OffloadErrorQType);
4470   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
4471                         OffloadError);
4472 
4473   // Fill up the pointer arrays and transfer execution to the device.
4474   auto &&ThenGen = [this, &Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
4475                     hasVLACaptures, Device, OutlinedFnID, OffloadError,
4476                     OffloadErrorQType, &D](CodeGenFunction &CGF) {
4477     unsigned PointerNumVal = BasePointers.size();
4478     llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
4479     llvm::Value *BasePointersArray;
4480     llvm::Value *PointersArray;
4481     llvm::Value *SizesArray;
4482     llvm::Value *MapTypesArray;
4483 
4484     if (PointerNumVal) {
4485       llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
4486       QualType PointerArrayType = Ctx.getConstantArrayType(
4487           Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
4488           /*IndexTypeQuals=*/0);
4489 
4490       BasePointersArray =
4491           CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
4492       PointersArray =
4493           CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
4494 
4495       // If we don't have any VLA types, we can use a constant array for the map
4496       // sizes, otherwise we need to fill up the arrays as we do for the
4497       // pointers.
4498       if (hasVLACaptures) {
4499         QualType SizeArrayType = Ctx.getConstantArrayType(
4500             Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
4501             /*IndexTypeQuals=*/0);
4502         SizesArray =
4503             CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
4504       } else {
4505         // We expect all the sizes to be constant, so we collect them to create
4506         // a constant array.
4507         SmallVector<llvm::Constant *, 16> ConstSizes;
4508         for (auto S : Sizes)
4509           ConstSizes.push_back(cast<llvm::Constant>(S));
4510 
4511         auto *SizesArrayInit = llvm::ConstantArray::get(
4512             llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
4513         auto *SizesArrayGbl = new llvm::GlobalVariable(
4514             CGM.getModule(), SizesArrayInit->getType(),
4515             /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4516             SizesArrayInit, ".offload_sizes");
4517         SizesArrayGbl->setUnnamedAddr(true);
4518         SizesArray = SizesArrayGbl;
4519       }
4520 
4521       // The map types are always constant so we don't need to generate code to
4522       // fill arrays. Instead, we create an array constant.
4523       llvm::Constant *MapTypesArrayInit =
4524           llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
4525       auto *MapTypesArrayGbl = new llvm::GlobalVariable(
4526           CGM.getModule(), MapTypesArrayInit->getType(),
4527           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
4528           MapTypesArrayInit, ".offload_maptypes");
4529       MapTypesArrayGbl->setUnnamedAddr(true);
4530       MapTypesArray = MapTypesArrayGbl;
4531 
4532       for (unsigned i = 0; i < PointerNumVal; ++i) {
4533         llvm::Value *BPVal = BasePointers[i];
4534         if (BPVal->getType()->isPointerTy())
4535           BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
4536         else {
4537           assert(BPVal->getType()->isIntegerTy() &&
4538                  "If not a pointer, the value type must be an integer.");
4539           BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
4540         }
4541         llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
4542             llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal),
4543             BasePointersArray, 0, i);
4544         Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4545         CGF.Builder.CreateStore(BPVal, BPAddr);
4546 
4547         llvm::Value *PVal = Pointers[i];
4548         if (PVal->getType()->isPointerTy())
4549           PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
4550         else {
4551           assert(PVal->getType()->isIntegerTy() &&
4552                  "If not a pointer, the value type must be an integer.");
4553           PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
4554         }
4555         llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
4556             llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4557             0, i);
4558         Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
4559         CGF.Builder.CreateStore(PVal, PAddr);
4560 
4561         if (hasVLACaptures) {
4562           llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
4563               llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4564               /*Idx0=*/0,
4565               /*Idx1=*/i);
4566           Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
4567           CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
4568                                       Sizes[i], CGM.SizeTy, /*isSigned=*/true),
4569                                   SAddr);
4570         }
4571       }
4572 
4573       BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4574           llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), BasePointersArray,
4575           /*Idx0=*/0, /*Idx1=*/0);
4576       PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4577           llvm::ArrayType::get(CGM.VoidPtrTy, PointerNumVal), PointersArray,
4578           /*Idx0=*/0,
4579           /*Idx1=*/0);
4580       SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4581           llvm::ArrayType::get(CGM.SizeTy, PointerNumVal), SizesArray,
4582           /*Idx0=*/0, /*Idx1=*/0);
4583       MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
4584           llvm::ArrayType::get(CGM.Int32Ty, PointerNumVal), MapTypesArray,
4585           /*Idx0=*/0,
4586           /*Idx1=*/0);
4587 
4588     } else {
4589       BasePointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4590       PointersArray = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
4591       SizesArray = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
4592       MapTypesArray =
4593           llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
4594     }
4595 
4596     // On top of the arrays that were filled up, the target offloading call
4597     // takes as arguments the device id as well as the host pointer. The host
4598     // pointer is used by the runtime library to identify the current target
4599     // region, so it only has to be unique and not necessarily point to
4600     // anything. It could be the pointer to the outlined function that
4601     // implements the target region, but we aren't using that so that the
4602     // compiler doesn't need to keep that, and could therefore inline the host
4603     // function if proven worthwhile during optimization.
4604 
4605     // From this point on, we need to have an ID of the target region defined.
4606     assert(OutlinedFnID && "Invalid outlined function ID!");
4607 
4608     // Emit device ID if any.
4609     llvm::Value *DeviceID;
4610     if (Device)
4611       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4612                                            CGM.Int32Ty, /*isSigned=*/true);
4613     else
4614       DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
4615 
4616     // Return value of the runtime offloading call.
4617     llvm::Value *Return;
4618 
4619     auto *NumTeams = emitNumTeamsClauseForTargetDirective(*this, CGF, D);
4620     auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(*this, CGF, D);
4621 
4622     // If we have NumTeams defined this means that we have an enclosed teams
4623     // region. Therefore we also expect to have ThreadLimit defined. These two
4624     // values should be defined in the presence of a teams directive, regardless
4625     // of having any clauses associated. If the user is using teams but no
4626     // clauses, these two values will be the default that should be passed to
4627     // the runtime library - a 32-bit integer with the value zero.
4628     if (NumTeams) {
4629       assert(ThreadLimit && "Thread limit expression should be available along "
4630                             "with number of teams.");
4631       llvm::Value *OffloadingArgs[] = {
4632           DeviceID,          OutlinedFnID,  PointerNum,
4633           BasePointersArray, PointersArray, SizesArray,
4634           MapTypesArray,     NumTeams,      ThreadLimit};
4635       Return = CGF.EmitRuntimeCall(
4636           createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
4637     } else {
4638       llvm::Value *OffloadingArgs[] = {
4639           DeviceID,      OutlinedFnID, PointerNum,   BasePointersArray,
4640           PointersArray, SizesArray,   MapTypesArray};
4641       Return = CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target),
4642                                    OffloadingArgs);
4643     }
4644 
4645     CGF.EmitStoreOfScalar(Return, OffloadError);
4646   };
4647 
4648   // Notify that the host version must be executed.
4649   auto &&ElseGen = [this, OffloadError,
4650                     OffloadErrorQType](CodeGenFunction &CGF) {
4651     CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/-1u),
4652                           OffloadError);
4653   };
4654 
4655   // If we have a target function ID it means that we need to support
4656   // offloading, otherwise, just execute on the host. We need to execute on host
4657   // regardless of the conditional in the if clause if, e.g., the user do not
4658   // specify target triples.
4659   if (OutlinedFnID) {
4660     if (IfCond) {
4661       emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
4662     } else {
4663       CodeGenFunction::RunCleanupsScope Scope(CGF);
4664       ThenGen(CGF);
4665     }
4666   } else {
4667     CodeGenFunction::RunCleanupsScope Scope(CGF);
4668     ElseGen(CGF);
4669   }
4670 
4671   // Check the error code and execute the host version if required.
4672   auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
4673   auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
4674   auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
4675   auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
4676   CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
4677 
4678   CGF.EmitBlock(OffloadFailedBlock);
4679   CGF.Builder.CreateCall(OutlinedFn, BasePointers);
4680   CGF.EmitBranch(OffloadContBlock);
4681 
4682   CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
4683 }
4684 
4685 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
4686                                                     StringRef ParentName) {
4687   if (!S)
4688     return;
4689 
4690   // If we find a OMP target directive, codegen the outline function and
4691   // register the result.
4692   // FIXME: Add other directives with target when they become supported.
4693   bool isTargetDirective = isa<OMPTargetDirective>(S);
4694 
4695   if (isTargetDirective) {
4696     auto *E = cast<OMPExecutableDirective>(S);
4697     unsigned DeviceID;
4698     unsigned FileID;
4699     unsigned Line;
4700     getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
4701                              FileID, Line);
4702 
4703     // Is this a target region that should not be emitted as an entry point? If
4704     // so just signal we are done with this target region.
4705     if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
4706                                                             ParentName, Line))
4707       return;
4708 
4709     llvm::Function *Fn;
4710     llvm::Constant *Addr;
4711     emitTargetOutlinedFunction(*E, ParentName, Fn, Addr,
4712                                /*isOffloadEntry=*/true);
4713     assert(Fn && Addr && "Target region emission failed.");
4714     return;
4715   }
4716 
4717   if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
4718     if (!E->getAssociatedStmt())
4719       return;
4720 
4721     scanForTargetRegionsFunctions(
4722         cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
4723         ParentName);
4724     return;
4725   }
4726 
4727   // If this is a lambda function, look into its body.
4728   if (auto *L = dyn_cast<LambdaExpr>(S))
4729     S = L->getBody();
4730 
4731   // Keep looking for target regions recursively.
4732   for (auto *II : S->children())
4733     scanForTargetRegionsFunctions(II, ParentName);
4734 }
4735 
4736 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
4737   auto &FD = *cast<FunctionDecl>(GD.getDecl());
4738 
4739   // If emitting code for the host, we do not process FD here. Instead we do
4740   // the normal code generation.
4741   if (!CGM.getLangOpts().OpenMPIsDevice)
4742     return false;
4743 
4744   // Try to detect target regions in the function.
4745   scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
4746 
4747   // We should not emit any function othen that the ones created during the
4748   // scanning. Therefore, we signal that this function is completely dealt
4749   // with.
4750   return true;
4751 }
4752 
4753 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
4754   if (!CGM.getLangOpts().OpenMPIsDevice)
4755     return false;
4756 
4757   // Check if there are Ctors/Dtors in this declaration and look for target
4758   // regions in it. We use the complete variant to produce the kernel name
4759   // mangling.
4760   QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
4761   if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
4762     for (auto *Ctor : RD->ctors()) {
4763       StringRef ParentName =
4764           CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
4765       scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
4766     }
4767     auto *Dtor = RD->getDestructor();
4768     if (Dtor) {
4769       StringRef ParentName =
4770           CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
4771       scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
4772     }
4773   }
4774 
4775   // If we are in target mode we do not emit any global (declare target is not
4776   // implemented yet). Therefore we signal that GD was processed in this case.
4777   return true;
4778 }
4779 
4780 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
4781   auto *VD = GD.getDecl();
4782   if (isa<FunctionDecl>(VD))
4783     return emitTargetFunctions(GD);
4784 
4785   return emitTargetGlobalVariable(GD);
4786 }
4787 
4788 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
4789   // If we have offloading in the current module, we need to emit the entries
4790   // now and register the offloading descriptor.
4791   createOffloadEntriesAndInfoMetadata();
4792 
4793   // Create and register the offloading binary descriptors. This is the main
4794   // entity that captures all the information about offloading in the current
4795   // compilation unit.
4796   return createOffloadingBinaryDescriptorRegistration();
4797 }
4798 
4799 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
4800                                     const OMPExecutableDirective &D,
4801                                     SourceLocation Loc,
4802                                     llvm::Value *OutlinedFn,
4803                                     ArrayRef<llvm::Value *> CapturedVars) {
4804   if (!CGF.HaveInsertPoint())
4805     return;
4806 
4807   auto *RTLoc = emitUpdateLocation(CGF, Loc);
4808   CodeGenFunction::RunCleanupsScope Scope(CGF);
4809 
4810   // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
4811   llvm::Value *Args[] = {
4812       RTLoc,
4813       CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
4814       CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
4815   llvm::SmallVector<llvm::Value *, 16> RealArgs;
4816   RealArgs.append(std::begin(Args), std::end(Args));
4817   RealArgs.append(CapturedVars.begin(), CapturedVars.end());
4818 
4819   auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
4820   CGF.EmitRuntimeCall(RTLFn, RealArgs);
4821 }
4822 
4823 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
4824                                          llvm::Value *NumTeams,
4825                                          llvm::Value *ThreadLimit,
4826                                          SourceLocation Loc) {
4827   if (!CGF.HaveInsertPoint())
4828     return;
4829 
4830   auto *RTLoc = emitUpdateLocation(CGF, Loc);
4831 
4832   // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
4833   llvm::Value *PushNumTeamsArgs[] = {
4834       RTLoc, getThreadID(CGF, Loc), NumTeams, ThreadLimit};
4835   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
4836                       PushNumTeamsArgs);
4837 }
4838