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/CodeGen/ConstantInitBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitmaskEnum.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/Value.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <cassert>
31 
32 using namespace clang;
33 using namespace CodeGen;
34 
35 namespace {
36 /// \brief Base class for handling code generation inside OpenMP regions.
37 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38 public:
39   /// \brief Kinds of OpenMP regions used in codegen.
40   enum CGOpenMPRegionKind {
41     /// \brief Region with outlined function for standalone 'parallel'
42     /// directive.
43     ParallelOutlinedRegion,
44     /// \brief Region with outlined function for standalone 'task' directive.
45     TaskOutlinedRegion,
46     /// \brief Region for constructs that do not require function outlining,
47     /// like 'for', 'sections', 'atomic' etc. directives.
48     InlinedRegion,
49     /// \brief Region with outlined function for standalone 'target' directive.
50     TargetRegion,
51   };
52 
53   CGOpenMPRegionInfo(const CapturedStmt &CS,
54                      const CGOpenMPRegionKind RegionKind,
55                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56                      bool HasCancel)
57       : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
58         CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
59 
60   CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
61                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62                      bool HasCancel)
63       : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
64         Kind(Kind), HasCancel(HasCancel) {}
65 
66   /// \brief Get a variable or parameter for storing global thread id
67   /// inside OpenMP construct.
68   virtual const VarDecl *getThreadIDVariable() const = 0;
69 
70   /// \brief Emit the captured statement body.
71   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
72 
73   /// \brief Get an LValue for the current ThreadID variable.
74   /// \return LValue for thread id variable. This LValue always has type int32*.
75   virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
76 
77   virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78 
79   CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
80 
81   OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82 
83   bool hasCancel() const { return HasCancel; }
84 
85   static bool classof(const CGCapturedStmtInfo *Info) {
86     return Info->getKind() == CR_OpenMP;
87   }
88 
89   ~CGOpenMPRegionInfo() override = default;
90 
91 protected:
92   CGOpenMPRegionKind RegionKind;
93   RegionCodeGenTy CodeGen;
94   OpenMPDirectiveKind Kind;
95   bool HasCancel;
96 };
97 
98 /// \brief API for captured statement code generation in OpenMP constructs.
99 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
100 public:
101   CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
102                              const RegionCodeGenTy &CodeGen,
103                              OpenMPDirectiveKind Kind, bool HasCancel,
104                              StringRef HelperName)
105       : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106                            HasCancel),
107         ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
108     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109   }
110 
111   /// \brief Get a variable or parameter for storing global thread id
112   /// inside OpenMP construct.
113   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
114 
115   /// \brief Get the name of the capture helper.
116   StringRef getHelperName() const override { return HelperName; }
117 
118   static bool classof(const CGCapturedStmtInfo *Info) {
119     return CGOpenMPRegionInfo::classof(Info) &&
120            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121                ParallelOutlinedRegion;
122   }
123 
124 private:
125   /// \brief A variable or parameter storing global thread id for OpenMP
126   /// constructs.
127   const VarDecl *ThreadIDVar;
128   StringRef HelperName;
129 };
130 
131 /// \brief API for captured statement code generation in OpenMP constructs.
132 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
133 public:
134   class UntiedTaskActionTy final : public PrePostActionTy {
135     bool Untied;
136     const VarDecl *PartIDVar;
137     const RegionCodeGenTy UntiedCodeGen;
138     llvm::SwitchInst *UntiedSwitch = nullptr;
139 
140   public:
141     UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142                        const RegionCodeGenTy &UntiedCodeGen)
143         : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144     void Enter(CodeGenFunction &CGF) override {
145       if (Untied) {
146         // Emit task switching point.
147         auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148             CGF.GetAddrOfLocalVar(PartIDVar),
149             PartIDVar->getType()->castAs<PointerType>());
150         auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151         auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152         UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153         CGF.EmitBlock(DoneBB);
154         CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155         CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156         UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157                               CGF.Builder.GetInsertBlock());
158         emitUntiedSwitch(CGF);
159       }
160     }
161     void emitUntiedSwitch(CodeGenFunction &CGF) const {
162       if (Untied) {
163         auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164             CGF.GetAddrOfLocalVar(PartIDVar),
165             PartIDVar->getType()->castAs<PointerType>());
166         CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167                               PartIdLVal);
168         UntiedCodeGen(CGF);
169         CodeGenFunction::JumpDest CurPoint =
170             CGF.getJumpDestInCurrentScope(".untied.next.");
171         CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172         CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173         UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174                               CGF.Builder.GetInsertBlock());
175         CGF.EmitBranchThroughCleanup(CurPoint);
176         CGF.EmitBlock(CurPoint.getBlock());
177       }
178     }
179     unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180   };
181   CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
182                                  const VarDecl *ThreadIDVar,
183                                  const RegionCodeGenTy &CodeGen,
184                                  OpenMPDirectiveKind Kind, bool HasCancel,
185                                  const UntiedTaskActionTy &Action)
186       : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
187         ThreadIDVar(ThreadIDVar), Action(Action) {
188     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189   }
190 
191   /// \brief Get a variable or parameter for storing global thread id
192   /// inside OpenMP construct.
193   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
194 
195   /// \brief Get an LValue for the current ThreadID variable.
196   LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
197 
198   /// \brief Get the name of the capture helper.
199   StringRef getHelperName() const override { return ".omp_outlined."; }
200 
201   void emitUntiedSwitch(CodeGenFunction &CGF) override {
202     Action.emitUntiedSwitch(CGF);
203   }
204 
205   static bool classof(const CGCapturedStmtInfo *Info) {
206     return CGOpenMPRegionInfo::classof(Info) &&
207            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208                TaskOutlinedRegion;
209   }
210 
211 private:
212   /// \brief A variable or parameter storing global thread id for OpenMP
213   /// constructs.
214   const VarDecl *ThreadIDVar;
215   /// Action for emitting code for untied tasks.
216   const UntiedTaskActionTy &Action;
217 };
218 
219 /// \brief API for inlined captured statement code generation in OpenMP
220 /// constructs.
221 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222 public:
223   CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
224                             const RegionCodeGenTy &CodeGen,
225                             OpenMPDirectiveKind Kind, bool HasCancel)
226       : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227         OldCSI(OldCSI),
228         OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
229 
230   // \brief Retrieve the value of the context parameter.
231   llvm::Value *getContextValue() const override {
232     if (OuterRegionInfo)
233       return OuterRegionInfo->getContextValue();
234     llvm_unreachable("No context value for inlined OpenMP region");
235   }
236 
237   void setContextValue(llvm::Value *V) override {
238     if (OuterRegionInfo) {
239       OuterRegionInfo->setContextValue(V);
240       return;
241     }
242     llvm_unreachable("No context value for inlined OpenMP region");
243   }
244 
245   /// \brief Lookup the captured field decl for a variable.
246   const FieldDecl *lookup(const VarDecl *VD) const override {
247     if (OuterRegionInfo)
248       return OuterRegionInfo->lookup(VD);
249     // If there is no outer outlined region,no need to lookup in a list of
250     // captured variables, we can use the original one.
251     return nullptr;
252   }
253 
254   FieldDecl *getThisFieldDecl() const override {
255     if (OuterRegionInfo)
256       return OuterRegionInfo->getThisFieldDecl();
257     return nullptr;
258   }
259 
260   /// \brief Get a variable or parameter for storing global thread id
261   /// inside OpenMP construct.
262   const VarDecl *getThreadIDVariable() const override {
263     if (OuterRegionInfo)
264       return OuterRegionInfo->getThreadIDVariable();
265     return nullptr;
266   }
267 
268   /// \brief Get the name of the capture helper.
269   StringRef getHelperName() const override {
270     if (auto *OuterRegionInfo = getOldCSI())
271       return OuterRegionInfo->getHelperName();
272     llvm_unreachable("No helper name for inlined OpenMP construct");
273   }
274 
275   void emitUntiedSwitch(CodeGenFunction &CGF) override {
276     if (OuterRegionInfo)
277       OuterRegionInfo->emitUntiedSwitch(CGF);
278   }
279 
280   CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281 
282   static bool classof(const CGCapturedStmtInfo *Info) {
283     return CGOpenMPRegionInfo::classof(Info) &&
284            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
285   }
286 
287   ~CGOpenMPInlinedRegionInfo() override = default;
288 
289 private:
290   /// \brief CodeGen info about outer OpenMP region.
291   CodeGenFunction::CGCapturedStmtInfo *OldCSI;
292   CGOpenMPRegionInfo *OuterRegionInfo;
293 };
294 
295 /// \brief API for captured statement code generation in OpenMP target
296 /// constructs. For this captures, implicit parameters are used instead of the
297 /// captured fields. The name of the target region has to be unique in a given
298 /// application so it is provided by the client, because only the client has
299 /// the information to generate that.
300 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
301 public:
302   CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
303                            const RegionCodeGenTy &CodeGen, StringRef HelperName)
304       : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
305                            /*HasCancel=*/false),
306         HelperName(HelperName) {}
307 
308   /// \brief This is unused for target regions because each starts executing
309   /// with a single thread.
310   const VarDecl *getThreadIDVariable() const override { return nullptr; }
311 
312   /// \brief Get the name of the capture helper.
313   StringRef getHelperName() const override { return HelperName; }
314 
315   static bool classof(const CGCapturedStmtInfo *Info) {
316     return CGOpenMPRegionInfo::classof(Info) &&
317            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
318   }
319 
320 private:
321   StringRef HelperName;
322 };
323 
324 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
325   llvm_unreachable("No codegen for expressions");
326 }
327 /// \brief API for generation of expressions captured in a innermost OpenMP
328 /// region.
329 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
330 public:
331   CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
332       : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333                                   OMPD_unknown,
334                                   /*HasCancel=*/false),
335         PrivScope(CGF) {
336     // Make sure the globals captured in the provided statement are local by
337     // using the privatization logic. We assume the same variable is not
338     // captured more than once.
339     for (auto &C : CS.captures()) {
340       if (!C.capturesVariable() && !C.capturesVariableByCopy())
341         continue;
342 
343       const VarDecl *VD = C.getCapturedVar();
344       if (VD->isLocalVarDeclOrParm())
345         continue;
346 
347       DeclRefExpr DRE(const_cast<VarDecl *>(VD),
348                       /*RefersToEnclosingVariableOrCapture=*/false,
349                       VD->getType().getNonReferenceType(), VK_LValue,
350                       SourceLocation());
351       PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
352         return CGF.EmitLValue(&DRE).getAddress();
353       });
354     }
355     (void)PrivScope.Privatize();
356   }
357 
358   /// \brief Lookup the captured field decl for a variable.
359   const FieldDecl *lookup(const VarDecl *VD) const override {
360     if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
361       return FD;
362     return nullptr;
363   }
364 
365   /// \brief Emit the captured statement body.
366   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
367     llvm_unreachable("No body for expressions");
368   }
369 
370   /// \brief Get a variable or parameter for storing global thread id
371   /// inside OpenMP construct.
372   const VarDecl *getThreadIDVariable() const override {
373     llvm_unreachable("No thread id for expressions");
374   }
375 
376   /// \brief Get the name of the capture helper.
377   StringRef getHelperName() const override {
378     llvm_unreachable("No helper name for expressions");
379   }
380 
381   static bool classof(const CGCapturedStmtInfo *Info) { return false; }
382 
383 private:
384   /// Private scope to capture global variables.
385   CodeGenFunction::OMPPrivateScope PrivScope;
386 };
387 
388 /// \brief RAII for emitting code of OpenMP constructs.
389 class InlinedOpenMPRegionRAII {
390   CodeGenFunction &CGF;
391   llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
392   FieldDecl *LambdaThisCaptureField = nullptr;
393 
394 public:
395   /// \brief Constructs region for combined constructs.
396   /// \param CodeGen Code generation sequence for combined directives. Includes
397   /// a list of functions used for code generation of implicitly inlined
398   /// regions.
399   InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
400                           OpenMPDirectiveKind Kind, bool HasCancel)
401       : CGF(CGF) {
402     // Start emission for the construct.
403     CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
404         CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
405     std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
406     LambdaThisCaptureField = CGF.LambdaThisCaptureField;
407     CGF.LambdaThisCaptureField = nullptr;
408   }
409 
410   ~InlinedOpenMPRegionRAII() {
411     // Restore original CapturedStmtInfo only if we're done with code emission.
412     auto *OldCSI =
413         cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
414     delete CGF.CapturedStmtInfo;
415     CGF.CapturedStmtInfo = OldCSI;
416     std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
417     CGF.LambdaThisCaptureField = LambdaThisCaptureField;
418   }
419 };
420 
421 /// \brief Values for bit flags used in the ident_t to describe the fields.
422 /// All enumeric elements are named and described in accordance with the code
423 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
424 enum OpenMPLocationFlags : unsigned {
425   /// \brief Use trampoline for internal microtask.
426   OMP_IDENT_IMD = 0x01,
427   /// \brief Use c-style ident structure.
428   OMP_IDENT_KMPC = 0x02,
429   /// \brief Atomic reduction option for kmpc_reduce.
430   OMP_ATOMIC_REDUCE = 0x10,
431   /// \brief Explicit 'barrier' directive.
432   OMP_IDENT_BARRIER_EXPL = 0x20,
433   /// \brief Implicit barrier in code.
434   OMP_IDENT_BARRIER_IMPL = 0x40,
435   /// \brief Implicit barrier in 'for' directive.
436   OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
437   /// \brief Implicit barrier in 'sections' directive.
438   OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
439   /// \brief Implicit barrier in 'single' directive.
440   OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
441   /// Call of __kmp_for_static_init for static loop.
442   OMP_IDENT_WORK_LOOP = 0x200,
443   /// Call of __kmp_for_static_init for sections.
444   OMP_IDENT_WORK_SECTIONS = 0x400,
445   /// Call of __kmp_for_static_init for distribute.
446   OMP_IDENT_WORK_DISTRIBUTE = 0x800,
447   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
448 };
449 
450 /// \brief Describes ident structure that describes a source location.
451 /// All descriptions are taken from
452 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
453 /// Original structure:
454 /// typedef struct ident {
455 ///    kmp_int32 reserved_1;   /**<  might be used in Fortran;
456 ///                                  see above  */
457 ///    kmp_int32 flags;        /**<  also f.flags; KMP_IDENT_xxx flags;
458 ///                                  KMP_IDENT_KMPC identifies this union
459 ///                                  member  */
460 ///    kmp_int32 reserved_2;   /**<  not really used in Fortran any more;
461 ///                                  see above */
462 ///#if USE_ITT_BUILD
463 ///                            /*  but currently used for storing
464 ///                                region-specific ITT */
465 ///                            /*  contextual information. */
466 ///#endif /* USE_ITT_BUILD */
467 ///    kmp_int32 reserved_3;   /**< source[4] in Fortran, do not use for
468 ///                                 C++  */
469 ///    char const *psource;    /**< String describing the source location.
470 ///                            The string is composed of semi-colon separated
471 //                             fields which describe the source file,
472 ///                            the function and a pair of line numbers that
473 ///                            delimit the construct.
474 ///                             */
475 /// } ident_t;
476 enum IdentFieldIndex {
477   /// \brief might be used in Fortran
478   IdentField_Reserved_1,
479   /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
480   IdentField_Flags,
481   /// \brief Not really used in Fortran any more
482   IdentField_Reserved_2,
483   /// \brief Source[4] in Fortran, do not use for C++
484   IdentField_Reserved_3,
485   /// \brief String describing the source location. The string is composed of
486   /// semi-colon separated fields which describe the source file, the function
487   /// and a pair of line numbers that delimit the construct.
488   IdentField_PSource
489 };
490 
491 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
492 /// the enum sched_type in kmp.h).
493 enum OpenMPSchedType {
494   /// \brief Lower bound for default (unordered) versions.
495   OMP_sch_lower = 32,
496   OMP_sch_static_chunked = 33,
497   OMP_sch_static = 34,
498   OMP_sch_dynamic_chunked = 35,
499   OMP_sch_guided_chunked = 36,
500   OMP_sch_runtime = 37,
501   OMP_sch_auto = 38,
502   /// static with chunk adjustment (e.g., simd)
503   OMP_sch_static_balanced_chunked = 45,
504   /// \brief Lower bound for 'ordered' versions.
505   OMP_ord_lower = 64,
506   OMP_ord_static_chunked = 65,
507   OMP_ord_static = 66,
508   OMP_ord_dynamic_chunked = 67,
509   OMP_ord_guided_chunked = 68,
510   OMP_ord_runtime = 69,
511   OMP_ord_auto = 70,
512   OMP_sch_default = OMP_sch_static,
513   /// \brief dist_schedule types
514   OMP_dist_sch_static_chunked = 91,
515   OMP_dist_sch_static = 92,
516   /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
517   /// Set if the monotonic schedule modifier was present.
518   OMP_sch_modifier_monotonic = (1 << 29),
519   /// Set if the nonmonotonic schedule modifier was present.
520   OMP_sch_modifier_nonmonotonic = (1 << 30),
521 };
522 
523 enum OpenMPRTLFunction {
524   /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
525   /// kmpc_micro microtask, ...);
526   OMPRTL__kmpc_fork_call,
527   /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
528   /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
529   OMPRTL__kmpc_threadprivate_cached,
530   /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
531   /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
532   OMPRTL__kmpc_threadprivate_register,
533   // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
534   OMPRTL__kmpc_global_thread_num,
535   // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
536   // kmp_critical_name *crit);
537   OMPRTL__kmpc_critical,
538   // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
539   // global_tid, kmp_critical_name *crit, uintptr_t hint);
540   OMPRTL__kmpc_critical_with_hint,
541   // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
542   // kmp_critical_name *crit);
543   OMPRTL__kmpc_end_critical,
544   // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
545   // global_tid);
546   OMPRTL__kmpc_cancel_barrier,
547   // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
548   OMPRTL__kmpc_barrier,
549   // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
550   OMPRTL__kmpc_for_static_fini,
551   // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
552   // global_tid);
553   OMPRTL__kmpc_serialized_parallel,
554   // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
555   // global_tid);
556   OMPRTL__kmpc_end_serialized_parallel,
557   // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
558   // kmp_int32 num_threads);
559   OMPRTL__kmpc_push_num_threads,
560   // Call to void __kmpc_flush(ident_t *loc);
561   OMPRTL__kmpc_flush,
562   // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
563   OMPRTL__kmpc_master,
564   // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
565   OMPRTL__kmpc_end_master,
566   // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
567   // int end_part);
568   OMPRTL__kmpc_omp_taskyield,
569   // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
570   OMPRTL__kmpc_single,
571   // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
572   OMPRTL__kmpc_end_single,
573   // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
574   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
575   // kmp_routine_entry_t *task_entry);
576   OMPRTL__kmpc_omp_task_alloc,
577   // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
578   // new_task);
579   OMPRTL__kmpc_omp_task,
580   // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
581   // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
582   // kmp_int32 didit);
583   OMPRTL__kmpc_copyprivate,
584   // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
585   // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
586   // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
587   OMPRTL__kmpc_reduce,
588   // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
589   // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
590   // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
591   // *lck);
592   OMPRTL__kmpc_reduce_nowait,
593   // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
594   // kmp_critical_name *lck);
595   OMPRTL__kmpc_end_reduce,
596   // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
597   // kmp_critical_name *lck);
598   OMPRTL__kmpc_end_reduce_nowait,
599   // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
600   // kmp_task_t * new_task);
601   OMPRTL__kmpc_omp_task_begin_if0,
602   // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
603   // kmp_task_t * new_task);
604   OMPRTL__kmpc_omp_task_complete_if0,
605   // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
606   OMPRTL__kmpc_ordered,
607   // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
608   OMPRTL__kmpc_end_ordered,
609   // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
610   // global_tid);
611   OMPRTL__kmpc_omp_taskwait,
612   // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
613   OMPRTL__kmpc_taskgroup,
614   // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
615   OMPRTL__kmpc_end_taskgroup,
616   // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
617   // int proc_bind);
618   OMPRTL__kmpc_push_proc_bind,
619   // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
620   // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
621   // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
622   OMPRTL__kmpc_omp_task_with_deps,
623   // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
624   // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
625   // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
626   OMPRTL__kmpc_omp_wait_deps,
627   // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
628   // global_tid, kmp_int32 cncl_kind);
629   OMPRTL__kmpc_cancellationpoint,
630   // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
631   // kmp_int32 cncl_kind);
632   OMPRTL__kmpc_cancel,
633   // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
634   // kmp_int32 num_teams, kmp_int32 thread_limit);
635   OMPRTL__kmpc_push_num_teams,
636   // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
637   // microtask, ...);
638   OMPRTL__kmpc_fork_teams,
639   // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
640   // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
641   // sched, kmp_uint64 grainsize, void *task_dup);
642   OMPRTL__kmpc_taskloop,
643   // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
644   // num_dims, struct kmp_dim *dims);
645   OMPRTL__kmpc_doacross_init,
646   // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
647   OMPRTL__kmpc_doacross_fini,
648   // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
649   // *vec);
650   OMPRTL__kmpc_doacross_post,
651   // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
652   // *vec);
653   OMPRTL__kmpc_doacross_wait,
654   // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
655   // *data);
656   OMPRTL__kmpc_task_reduction_init,
657   // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
658   // *d);
659   OMPRTL__kmpc_task_reduction_get_th_data,
660 
661   //
662   // Offloading related calls
663   //
664   // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
665   // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
666   // *arg_types);
667   OMPRTL__tgt_target,
668   // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
669   // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
670   // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
671   OMPRTL__tgt_target_teams,
672   // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
673   OMPRTL__tgt_register_lib,
674   // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
675   OMPRTL__tgt_unregister_lib,
676   // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
677   // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
678   OMPRTL__tgt_target_data_begin,
679   // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
680   // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
681   OMPRTL__tgt_target_data_end,
682   // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
683   // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
684   OMPRTL__tgt_target_data_update,
685 };
686 
687 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
688 /// region.
689 class CleanupTy final : public EHScopeStack::Cleanup {
690   PrePostActionTy *Action;
691 
692 public:
693   explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
694   void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
695     if (!CGF.HaveInsertPoint())
696       return;
697     Action->Exit(CGF);
698   }
699 };
700 
701 } // anonymous namespace
702 
703 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
704   CodeGenFunction::RunCleanupsScope Scope(CGF);
705   if (PrePostAction) {
706     CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
707     Callback(CodeGen, CGF, *PrePostAction);
708   } else {
709     PrePostActionTy Action;
710     Callback(CodeGen, CGF, Action);
711   }
712 }
713 
714 /// Check if the combiner is a call to UDR combiner and if it is so return the
715 /// UDR decl used for reduction.
716 static const OMPDeclareReductionDecl *
717 getReductionInit(const Expr *ReductionOp) {
718   if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
719     if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
720       if (auto *DRE =
721               dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
722         if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
723           return DRD;
724   return nullptr;
725 }
726 
727 static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
728                                              const OMPDeclareReductionDecl *DRD,
729                                              const Expr *InitOp,
730                                              Address Private, Address Original,
731                                              QualType Ty) {
732   if (DRD->getInitializer()) {
733     std::pair<llvm::Function *, llvm::Function *> Reduction =
734         CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
735     auto *CE = cast<CallExpr>(InitOp);
736     auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
737     const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
738     const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
739     auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
740     auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
741     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
742     PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
743                             [=]() -> Address { return Private; });
744     PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
745                             [=]() -> Address { return Original; });
746     (void)PrivateScope.Privatize();
747     RValue Func = RValue::get(Reduction.second);
748     CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
749     CGF.EmitIgnoredExpr(InitOp);
750   } else {
751     llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
752     auto *GV = new llvm::GlobalVariable(
753         CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
754         llvm::GlobalValue::PrivateLinkage, Init, ".init");
755     LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
756     RValue InitRVal;
757     switch (CGF.getEvaluationKind(Ty)) {
758     case TEK_Scalar:
759       InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
760       break;
761     case TEK_Complex:
762       InitRVal =
763           RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
764       break;
765     case TEK_Aggregate:
766       InitRVal = RValue::getAggregate(LV.getAddress());
767       break;
768     }
769     OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
770     CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
771     CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
772                          /*IsInitializer=*/false);
773   }
774 }
775 
776 /// \brief Emit initialization of arrays of complex types.
777 /// \param DestAddr Address of the array.
778 /// \param Type Type of array.
779 /// \param Init Initial expression of array.
780 /// \param SrcAddr Address of the original array.
781 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
782                                  QualType Type, const Expr *Init,
783                                  const OMPDeclareReductionDecl *DRD,
784                                  Address SrcAddr = Address::invalid()) {
785   // Perform element-by-element initialization.
786   QualType ElementTy;
787 
788   // Drill down to the base element type on both arrays.
789   auto ArrayTy = Type->getAsArrayTypeUnsafe();
790   auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
791   DestAddr =
792       CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
793   if (DRD)
794     SrcAddr =
795         CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
796 
797   llvm::Value *SrcBegin = nullptr;
798   if (DRD)
799     SrcBegin = SrcAddr.getPointer();
800   auto DestBegin = DestAddr.getPointer();
801   // Cast from pointer to array type to pointer to single element.
802   auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
803   // The basic structure here is a while-do loop.
804   auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
805   auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
806   auto IsEmpty =
807       CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
808   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
809 
810   // Enter the loop body, making that address the current address.
811   auto EntryBB = CGF.Builder.GetInsertBlock();
812   CGF.EmitBlock(BodyBB);
813 
814   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
815 
816   llvm::PHINode *SrcElementPHI = nullptr;
817   Address SrcElementCurrent = Address::invalid();
818   if (DRD) {
819     SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
820                                           "omp.arraycpy.srcElementPast");
821     SrcElementPHI->addIncoming(SrcBegin, EntryBB);
822     SrcElementCurrent =
823         Address(SrcElementPHI,
824                 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
825   }
826   llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
827       DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
828   DestElementPHI->addIncoming(DestBegin, EntryBB);
829   Address DestElementCurrent =
830       Address(DestElementPHI,
831               DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
832 
833   // Emit copy.
834   {
835     CodeGenFunction::RunCleanupsScope InitScope(CGF);
836     if (DRD && (DRD->getInitializer() || !Init)) {
837       emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
838                                        SrcElementCurrent, ElementTy);
839     } else
840       CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
841                            /*IsInitializer=*/false);
842   }
843 
844   if (DRD) {
845     // Shift the address forward by one element.
846     auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
847         SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
848     SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
849   }
850 
851   // Shift the address forward by one element.
852   auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
853       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
854   // Check whether we've reached the end.
855   auto Done =
856       CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
857   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
858   DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
859 
860   // Done.
861   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
862 }
863 
864 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
865   if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
866     return CGF.EmitOMPArraySectionExpr(OASE);
867   if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
868     return CGF.EmitLValue(ASE);
869   auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
870   DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
871                   CGF.CapturedStmtInfo &&
872                       CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
873                   E->getType(), VK_LValue, E->getExprLoc());
874   // Store the address of the original variable associated with the LHS
875   // implicit variable.
876   return CGF.EmitLValue(&DRE);
877 }
878 
879 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
880                                             const Expr *E) {
881   if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
882     return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
883   return LValue();
884 }
885 
886 void ReductionCodeGen::emitAggregateInitialization(
887     CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
888     const OMPDeclareReductionDecl *DRD) {
889   // Emit VarDecl with copy init for arrays.
890   // Get the address of the original variable captured in current
891   // captured region.
892   auto *PrivateVD =
893       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
894   EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
895                        DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
896                        DRD, SharedLVal.getAddress());
897 }
898 
899 ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
900                                    ArrayRef<const Expr *> Privates,
901                                    ArrayRef<const Expr *> ReductionOps) {
902   ClausesData.reserve(Shareds.size());
903   SharedAddresses.reserve(Shareds.size());
904   Sizes.reserve(Shareds.size());
905   BaseDecls.reserve(Shareds.size());
906   auto IPriv = Privates.begin();
907   auto IRed = ReductionOps.begin();
908   for (const auto *Ref : Shareds) {
909     ClausesData.emplace_back(Ref, *IPriv, *IRed);
910     std::advance(IPriv, 1);
911     std::advance(IRed, 1);
912   }
913 }
914 
915 void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
916   assert(SharedAddresses.size() == N &&
917          "Number of generated lvalues must be exactly N.");
918   SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
919                                emitSharedLValueUB(CGF, ClausesData[N].Ref));
920 }
921 
922 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
923   auto *PrivateVD =
924       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
925   QualType PrivateType = PrivateVD->getType();
926   bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
927   if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
928     Sizes.emplace_back(
929         CGF.getTypeSize(
930             SharedAddresses[N].first.getType().getNonReferenceType()),
931         nullptr);
932     return;
933   }
934   llvm::Value *Size;
935   llvm::Value *SizeInChars;
936   llvm::Type *ElemType =
937       cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
938           ->getElementType();
939   auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
940   if (AsArraySection) {
941     Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
942                                      SharedAddresses[N].first.getPointer());
943     Size = CGF.Builder.CreateNUWAdd(
944         Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
945     SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
946   } else {
947     SizeInChars = CGF.getTypeSize(
948         SharedAddresses[N].first.getType().getNonReferenceType());
949     Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
950   }
951   Sizes.emplace_back(SizeInChars, Size);
952   CodeGenFunction::OpaqueValueMapping OpaqueMap(
953       CGF,
954       cast<OpaqueValueExpr>(
955           CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
956       RValue::get(Size));
957   CGF.EmitVariablyModifiedType(PrivateType);
958 }
959 
960 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
961                                          llvm::Value *Size) {
962   auto *PrivateVD =
963       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
964   QualType PrivateType = PrivateVD->getType();
965   bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
966   if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
967     assert(!Size && !Sizes[N].second &&
968            "Size should be nullptr for non-variably modified redution "
969            "items.");
970     return;
971   }
972   CodeGenFunction::OpaqueValueMapping OpaqueMap(
973       CGF,
974       cast<OpaqueValueExpr>(
975           CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
976       RValue::get(Size));
977   CGF.EmitVariablyModifiedType(PrivateType);
978 }
979 
980 void ReductionCodeGen::emitInitialization(
981     CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
982     llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
983   assert(SharedAddresses.size() > N && "No variable was generated");
984   auto *PrivateVD =
985       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986   auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
987   QualType PrivateType = PrivateVD->getType();
988   PrivateAddr = CGF.Builder.CreateElementBitCast(
989       PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
990   QualType SharedType = SharedAddresses[N].first.getType();
991   SharedLVal = CGF.MakeAddrLValue(
992       CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
993                                        CGF.ConvertTypeForMem(SharedType)),
994       SharedType, SharedAddresses[N].first.getBaseInfo());
995   if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
996       CGF.getContext().getAsArrayType(PrivateVD->getType())) {
997     emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
998   } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
999     emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1000                                      PrivateAddr, SharedLVal.getAddress(),
1001                                      SharedLVal.getType());
1002   } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1003              !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1004     CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1005                          PrivateVD->getType().getQualifiers(),
1006                          /*IsInitializer=*/false);
1007   }
1008 }
1009 
1010 bool ReductionCodeGen::needCleanups(unsigned N) {
1011   auto *PrivateVD =
1012       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013   QualType PrivateType = PrivateVD->getType();
1014   QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1015   return DTorKind != QualType::DK_none;
1016 }
1017 
1018 void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1019                                     Address PrivateAddr) {
1020   auto *PrivateVD =
1021       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022   QualType PrivateType = PrivateVD->getType();
1023   QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1024   if (needCleanups(N)) {
1025     PrivateAddr = CGF.Builder.CreateElementBitCast(
1026         PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1027     CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1028   }
1029 }
1030 
1031 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1032                           LValue BaseLV) {
1033   BaseTy = BaseTy.getNonReferenceType();
1034   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1035          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1036     if (auto *PtrTy = BaseTy->getAs<PointerType>())
1037       BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1038     else {
1039       BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1040                                              BaseTy->castAs<ReferenceType>());
1041     }
1042     BaseTy = BaseTy->getPointeeType();
1043   }
1044   return CGF.MakeAddrLValue(
1045       CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1046                                        CGF.ConvertTypeForMem(ElTy)),
1047       BaseLV.getType(), BaseLV.getBaseInfo());
1048 }
1049 
1050 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1051                           llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1052                           llvm::Value *Addr) {
1053   Address Tmp = Address::invalid();
1054   Address TopTmp = Address::invalid();
1055   Address MostTopTmp = Address::invalid();
1056   BaseTy = BaseTy.getNonReferenceType();
1057   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1058          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1059     Tmp = CGF.CreateMemTemp(BaseTy);
1060     if (TopTmp.isValid())
1061       CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1062     else
1063       MostTopTmp = Tmp;
1064     TopTmp = Tmp;
1065     BaseTy = BaseTy->getPointeeType();
1066   }
1067   llvm::Type *Ty = BaseLVType;
1068   if (Tmp.isValid())
1069     Ty = Tmp.getElementType();
1070   Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1071   if (Tmp.isValid()) {
1072     CGF.Builder.CreateStore(Addr, Tmp);
1073     return MostTopTmp;
1074   }
1075   return Address(Addr, BaseLVAlignment);
1076 }
1077 
1078 Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1079                                                Address PrivateAddr) {
1080   const DeclRefExpr *DE;
1081   const VarDecl *OrigVD = nullptr;
1082   if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1083     auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1084     while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1085       Base = TempOASE->getBase()->IgnoreParenImpCasts();
1086     while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1087       Base = TempASE->getBase()->IgnoreParenImpCasts();
1088     DE = cast<DeclRefExpr>(Base);
1089     OrigVD = cast<VarDecl>(DE->getDecl());
1090   } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1091     auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1092     while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1093       Base = TempASE->getBase()->IgnoreParenImpCasts();
1094     DE = cast<DeclRefExpr>(Base);
1095     OrigVD = cast<VarDecl>(DE->getDecl());
1096   }
1097   if (OrigVD) {
1098     BaseDecls.emplace_back(OrigVD);
1099     auto OriginalBaseLValue = CGF.EmitLValue(DE);
1100     LValue BaseLValue =
1101         loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1102                     OriginalBaseLValue);
1103     llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1104         BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1105     llvm::Value *Ptr =
1106         CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1107     return castToBase(CGF, OrigVD->getType(),
1108                       SharedAddresses[N].first.getType(),
1109                       OriginalBaseLValue.getPointer()->getType(),
1110                       OriginalBaseLValue.getAlignment(), Ptr);
1111   }
1112   BaseDecls.emplace_back(
1113       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1114   return PrivateAddr;
1115 }
1116 
1117 bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1118   auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1119   return DRD && DRD->getInitializer();
1120 }
1121 
1122 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1123   return CGF.EmitLoadOfPointerLValue(
1124       CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1125       getThreadIDVariable()->getType()->castAs<PointerType>());
1126 }
1127 
1128 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
1129   if (!CGF.HaveInsertPoint())
1130     return;
1131   // 1.2.2 OpenMP Language Terminology
1132   // Structured block - An executable statement with a single entry at the
1133   // top and a single exit at the bottom.
1134   // The point of exit cannot be a branch out of the structured block.
1135   // longjmp() and throw() must not violate the entry/exit criteria.
1136   CGF.EHStack.pushTerminate();
1137   CodeGen(CGF);
1138   CGF.EHStack.popTerminate();
1139 }
1140 
1141 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1142     CodeGenFunction &CGF) {
1143   return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1144                             getThreadIDVariable()->getType(),
1145                             LValueBaseInfo(AlignmentSource::Decl, false));
1146 }
1147 
1148 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
1149     : CGM(CGM), OffloadEntriesInfoManager(CGM) {
1150   IdentTy = llvm::StructType::create(
1151       "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1152       CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
1153       CGM.Int8PtrTy /* psource */);
1154   KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1155 
1156   loadOffloadInfoMetadata();
1157 }
1158 
1159 void CGOpenMPRuntime::clear() {
1160   InternalVars.clear();
1161 }
1162 
1163 static llvm::Function *
1164 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1165                           const Expr *CombinerInitializer, const VarDecl *In,
1166                           const VarDecl *Out, bool IsCombiner) {
1167   // void .omp_combiner.(Ty *in, Ty *out);
1168   auto &C = CGM.getContext();
1169   QualType PtrTy = C.getPointerType(Ty).withRestrict();
1170   FunctionArgList Args;
1171   ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1172                                /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1173   ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1174                               /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1175   Args.push_back(&OmpOutParm);
1176   Args.push_back(&OmpInParm);
1177   auto &FnInfo =
1178       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1179   auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1180   auto *Fn = llvm::Function::Create(
1181       FnTy, llvm::GlobalValue::InternalLinkage,
1182       IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1183   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
1184   Fn->removeFnAttr(llvm::Attribute::NoInline);
1185   Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1186   Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1187   CodeGenFunction CGF(CGM);
1188   // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1189   // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1190   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1191   CodeGenFunction::OMPPrivateScope Scope(CGF);
1192   Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1193   Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1194     return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1195         .getAddress();
1196   });
1197   Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1198   Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1199     return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1200         .getAddress();
1201   });
1202   (void)Scope.Privatize();
1203   CGF.EmitIgnoredExpr(CombinerInitializer);
1204   Scope.ForceCleanup();
1205   CGF.FinishFunction();
1206   return Fn;
1207 }
1208 
1209 void CGOpenMPRuntime::emitUserDefinedReduction(
1210     CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1211   if (UDRMap.count(D) > 0)
1212     return;
1213   auto &C = CGM.getContext();
1214   if (!In || !Out) {
1215     In = &C.Idents.get("omp_in");
1216     Out = &C.Idents.get("omp_out");
1217   }
1218   llvm::Function *Combiner = emitCombinerOrInitializer(
1219       CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1220       cast<VarDecl>(D->lookup(Out).front()),
1221       /*IsCombiner=*/true);
1222   llvm::Function *Initializer = nullptr;
1223   if (auto *Init = D->getInitializer()) {
1224     if (!Priv || !Orig) {
1225       Priv = &C.Idents.get("omp_priv");
1226       Orig = &C.Idents.get("omp_orig");
1227     }
1228     Initializer = emitCombinerOrInitializer(
1229         CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
1230         cast<VarDecl>(D->lookup(Priv).front()),
1231         /*IsCombiner=*/false);
1232   }
1233   UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1234   if (CGF) {
1235     auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1236     Decls.second.push_back(D);
1237   }
1238 }
1239 
1240 std::pair<llvm::Function *, llvm::Function *>
1241 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1242   auto I = UDRMap.find(D);
1243   if (I != UDRMap.end())
1244     return I->second;
1245   emitUserDefinedReduction(/*CGF=*/nullptr, D);
1246   return UDRMap.lookup(D);
1247 }
1248 
1249 // Layout information for ident_t.
1250 static CharUnits getIdentAlign(CodeGenModule &CGM) {
1251   return CGM.getPointerAlign();
1252 }
1253 static CharUnits getIdentSize(CodeGenModule &CGM) {
1254   assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1255   return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1256 }
1257 static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
1258   // All the fields except the last are i32, so this works beautifully.
1259   return unsigned(Field) * CharUnits::fromQuantity(4);
1260 }
1261 static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
1262                                    IdentFieldIndex Field,
1263                                    const llvm::Twine &Name = "") {
1264   auto Offset = getOffsetOfIdentField(Field);
1265   return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1266 }
1267 
1268 static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1269     CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1270     const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1271     const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1272   assert(ThreadIDVar->getType()->isPointerType() &&
1273          "thread id variable must be of type kmp_int32 *");
1274   CodeGenFunction CGF(CGM, true);
1275   bool HasCancel = false;
1276   if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1277     HasCancel = OPD->hasCancel();
1278   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1279     HasCancel = OPSD->hasCancel();
1280   else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1281     HasCancel = OPFD->hasCancel();
1282   CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1283                                     HasCancel, OutlinedHelperName);
1284   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1285   return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
1286 }
1287 
1288 llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1289     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1290     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1291   const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1292   return emitParallelOrTeamsOutlinedFunction(
1293       CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1294 }
1295 
1296 llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1297     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1298     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1299   const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1300   return emitParallelOrTeamsOutlinedFunction(
1301       CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1302 }
1303 
1304 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1305     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1306     const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1307     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1308     bool Tied, unsigned &NumberOfParts) {
1309   auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1310                                               PrePostActionTy &) {
1311     auto *ThreadID = getThreadID(CGF, D.getLocStart());
1312     auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1313     llvm::Value *TaskArgs[] = {
1314         UpLoc, ThreadID,
1315         CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1316                                     TaskTVar->getType()->castAs<PointerType>())
1317             .getPointer()};
1318     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1319   };
1320   CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1321                                                             UntiedCodeGen);
1322   CodeGen.setAction(Action);
1323   assert(!ThreadIDVar->getType()->isPointerType() &&
1324          "thread id variable must be of type kmp_int32 for tasks");
1325   auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
1326   auto *TD = dyn_cast<OMPTaskDirective>(&D);
1327   CodeGenFunction CGF(CGM, true);
1328   CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1329                                         InnermostKind,
1330                                         TD ? TD->hasCancel() : false, Action);
1331   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1332   auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1333   if (!Tied)
1334     NumberOfParts = Action.getNumberOfParts();
1335   return Res;
1336 }
1337 
1338 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
1339   CharUnits Align = getIdentAlign(CGM);
1340   llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
1341   if (!Entry) {
1342     if (!DefaultOpenMPPSource) {
1343       // Initialize default location for psource field of ident_t structure of
1344       // all ident_t objects. Format is ";file;function;line;column;;".
1345       // Taken from
1346       // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1347       DefaultOpenMPPSource =
1348           CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
1349       DefaultOpenMPPSource =
1350           llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1351     }
1352 
1353     ConstantInitBuilder builder(CGM);
1354     auto fields = builder.beginStruct(IdentTy);
1355     fields.addInt(CGM.Int32Ty, 0);
1356     fields.addInt(CGM.Int32Ty, Flags);
1357     fields.addInt(CGM.Int32Ty, 0);
1358     fields.addInt(CGM.Int32Ty, 0);
1359     fields.add(DefaultOpenMPPSource);
1360     auto DefaultOpenMPLocation =
1361       fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1362                                    llvm::GlobalValue::PrivateLinkage);
1363     DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1364 
1365     OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
1366   }
1367   return Address(Entry, Align);
1368 }
1369 
1370 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1371                                                  SourceLocation Loc,
1372                                                  unsigned Flags) {
1373   Flags |= OMP_IDENT_KMPC;
1374   // If no debug info is generated - return global default location.
1375   if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1376       Loc.isInvalid())
1377     return getOrCreateDefaultLocation(Flags).getPointer();
1378 
1379   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1380 
1381   Address LocValue = Address::invalid();
1382   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1383   if (I != OpenMPLocThreadIDMap.end())
1384     LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1385 
1386   // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1387   // GetOpenMPThreadID was called before this routine.
1388   if (!LocValue.isValid()) {
1389     // Generate "ident_t .kmpc_loc.addr;"
1390     Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1391                                       ".kmpc_loc.addr");
1392     auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1393     Elem.second.DebugLoc = AI.getPointer();
1394     LocValue = AI;
1395 
1396     CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1397     CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1398     CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
1399                              CGM.getSize(getIdentSize(CGF.CGM)));
1400   }
1401 
1402   // char **psource = &.kmpc_loc_<flags>.addr.psource;
1403   Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
1404 
1405   auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1406   if (OMPDebugLoc == nullptr) {
1407     SmallString<128> Buffer2;
1408     llvm::raw_svector_ostream OS2(Buffer2);
1409     // Build debug location
1410     PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1411     OS2 << ";" << PLoc.getFilename() << ";";
1412     if (const FunctionDecl *FD =
1413             dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1414       OS2 << FD->getQualifiedNameAsString();
1415     }
1416     OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1417     OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1418     OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
1419   }
1420   // *psource = ";<File>;<Function>;<Line>;<Column>;;";
1421   CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1422 
1423   // Our callers always pass this to a runtime function, so for
1424   // convenience, go ahead and return a naked pointer.
1425   return LocValue.getPointer();
1426 }
1427 
1428 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1429                                           SourceLocation Loc) {
1430   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1431 
1432   llvm::Value *ThreadID = nullptr;
1433   // Check whether we've already cached a load of the thread id in this
1434   // function.
1435   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1436   if (I != OpenMPLocThreadIDMap.end()) {
1437     ThreadID = I->second.ThreadID;
1438     if (ThreadID != nullptr)
1439       return ThreadID;
1440   }
1441   // If exceptions are enabled, do not use parameter to avoid possible crash.
1442   if (!CGF.getInvokeDest()) {
1443     if (auto *OMPRegionInfo =
1444             dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1445       if (OMPRegionInfo->getThreadIDVariable()) {
1446         // Check if this an outlined function with thread id passed as argument.
1447         auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1448         ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1449         // If value loaded in entry block, cache it and use it everywhere in
1450         // function.
1451         if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1452           auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1453           Elem.second.ThreadID = ThreadID;
1454         }
1455         return ThreadID;
1456       }
1457     }
1458   }
1459 
1460   // This is not an outlined function region - need to call __kmpc_int32
1461   // kmpc_global_thread_num(ident_t *loc).
1462   // Generate thread id value and cache this value for use across the
1463   // function.
1464   CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1465   CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1466   ThreadID =
1467       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1468                           emitUpdateLocation(CGF, Loc));
1469   auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1470   Elem.second.ThreadID = ThreadID;
1471   return ThreadID;
1472 }
1473 
1474 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1475   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1476   if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1477     OpenMPLocThreadIDMap.erase(CGF.CurFn);
1478   if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1479     for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1480       UDRMap.erase(D);
1481     }
1482     FunctionUDRMap.erase(CGF.CurFn);
1483   }
1484 }
1485 
1486 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1487   if (!IdentTy) {
1488   }
1489   return llvm::PointerType::getUnqual(IdentTy);
1490 }
1491 
1492 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1493   if (!Kmpc_MicroTy) {
1494     // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1495     llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1496                                  llvm::PointerType::getUnqual(CGM.Int32Ty)};
1497     Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1498   }
1499   return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1500 }
1501 
1502 llvm::Constant *
1503 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1504   llvm::Constant *RTLFn = nullptr;
1505   switch (static_cast<OpenMPRTLFunction>(Function)) {
1506   case OMPRTL__kmpc_fork_call: {
1507     // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1508     // microtask, ...);
1509     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1510                                 getKmpc_MicroPointerTy()};
1511     llvm::FunctionType *FnTy =
1512         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1513     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1514     break;
1515   }
1516   case OMPRTL__kmpc_global_thread_num: {
1517     // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1518     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1519     llvm::FunctionType *FnTy =
1520         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1521     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1522     break;
1523   }
1524   case OMPRTL__kmpc_threadprivate_cached: {
1525     // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1526     // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1527     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1528                                 CGM.VoidPtrTy, CGM.SizeTy,
1529                                 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1530     llvm::FunctionType *FnTy =
1531         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1532     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1533     break;
1534   }
1535   case OMPRTL__kmpc_critical: {
1536     // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1537     // kmp_critical_name *crit);
1538     llvm::Type *TypeParams[] = {
1539         getIdentTyPointerTy(), CGM.Int32Ty,
1540         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1541     llvm::FunctionType *FnTy =
1542         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1544     break;
1545   }
1546   case OMPRTL__kmpc_critical_with_hint: {
1547     // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1548     // kmp_critical_name *crit, uintptr_t hint);
1549     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1550                                 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1551                                 CGM.IntPtrTy};
1552     llvm::FunctionType *FnTy =
1553         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1554     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1555     break;
1556   }
1557   case OMPRTL__kmpc_threadprivate_register: {
1558     // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1559     // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1560     // typedef void *(*kmpc_ctor)(void *);
1561     auto KmpcCtorTy =
1562         llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1563                                 /*isVarArg*/ false)->getPointerTo();
1564     // typedef void *(*kmpc_cctor)(void *, void *);
1565     llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1566     auto KmpcCopyCtorTy =
1567         llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1568                                 /*isVarArg*/ false)->getPointerTo();
1569     // typedef void (*kmpc_dtor)(void *);
1570     auto KmpcDtorTy =
1571         llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1572             ->getPointerTo();
1573     llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1574                               KmpcCopyCtorTy, KmpcDtorTy};
1575     auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1576                                         /*isVarArg*/ false);
1577     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1578     break;
1579   }
1580   case OMPRTL__kmpc_end_critical: {
1581     // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1582     // kmp_critical_name *crit);
1583     llvm::Type *TypeParams[] = {
1584         getIdentTyPointerTy(), CGM.Int32Ty,
1585         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1586     llvm::FunctionType *FnTy =
1587         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1588     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1589     break;
1590   }
1591   case OMPRTL__kmpc_cancel_barrier: {
1592     // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1593     // global_tid);
1594     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1595     llvm::FunctionType *FnTy =
1596         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1597     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1598     break;
1599   }
1600   case OMPRTL__kmpc_barrier: {
1601     // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1602     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1603     llvm::FunctionType *FnTy =
1604         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1605     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1606     break;
1607   }
1608   case OMPRTL__kmpc_for_static_fini: {
1609     // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1610     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1611     llvm::FunctionType *FnTy =
1612         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1614     break;
1615   }
1616   case OMPRTL__kmpc_push_num_threads: {
1617     // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1618     // kmp_int32 num_threads)
1619     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1620                                 CGM.Int32Ty};
1621     llvm::FunctionType *FnTy =
1622         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1623     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1624     break;
1625   }
1626   case OMPRTL__kmpc_serialized_parallel: {
1627     // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1628     // global_tid);
1629     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1630     llvm::FunctionType *FnTy =
1631         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1632     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1633     break;
1634   }
1635   case OMPRTL__kmpc_end_serialized_parallel: {
1636     // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1637     // global_tid);
1638     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1639     llvm::FunctionType *FnTy =
1640         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1641     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1642     break;
1643   }
1644   case OMPRTL__kmpc_flush: {
1645     // Build void __kmpc_flush(ident_t *loc);
1646     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1647     llvm::FunctionType *FnTy =
1648         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1649     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1650     break;
1651   }
1652   case OMPRTL__kmpc_master: {
1653     // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1654     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1655     llvm::FunctionType *FnTy =
1656         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1657     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1658     break;
1659   }
1660   case OMPRTL__kmpc_end_master: {
1661     // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1662     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1663     llvm::FunctionType *FnTy =
1664         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1665     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1666     break;
1667   }
1668   case OMPRTL__kmpc_omp_taskyield: {
1669     // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1670     // int end_part);
1671     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1672     llvm::FunctionType *FnTy =
1673         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1674     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1675     break;
1676   }
1677   case OMPRTL__kmpc_single: {
1678     // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1679     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1680     llvm::FunctionType *FnTy =
1681         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1682     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1683     break;
1684   }
1685   case OMPRTL__kmpc_end_single: {
1686     // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1687     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1688     llvm::FunctionType *FnTy =
1689         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1690     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1691     break;
1692   }
1693   case OMPRTL__kmpc_omp_task_alloc: {
1694     // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1695     // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1696     // kmp_routine_entry_t *task_entry);
1697     assert(KmpRoutineEntryPtrTy != nullptr &&
1698            "Type kmp_routine_entry_t must be created.");
1699     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1700                                 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1701     // Return void * and then cast to particular kmp_task_t type.
1702     llvm::FunctionType *FnTy =
1703         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1704     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1705     break;
1706   }
1707   case OMPRTL__kmpc_omp_task: {
1708     // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1709     // *new_task);
1710     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1711                                 CGM.VoidPtrTy};
1712     llvm::FunctionType *FnTy =
1713         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1714     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1715     break;
1716   }
1717   case OMPRTL__kmpc_copyprivate: {
1718     // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1719     // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1720     // kmp_int32 didit);
1721     llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1722     auto *CpyFnTy =
1723         llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1724     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1725                                 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1726                                 CGM.Int32Ty};
1727     llvm::FunctionType *FnTy =
1728         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1729     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1730     break;
1731   }
1732   case OMPRTL__kmpc_reduce: {
1733     // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1734     // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1735     // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1736     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1737     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1738                                                /*isVarArg=*/false);
1739     llvm::Type *TypeParams[] = {
1740         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1741         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1742         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1743     llvm::FunctionType *FnTy =
1744         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1745     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1746     break;
1747   }
1748   case OMPRTL__kmpc_reduce_nowait: {
1749     // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1750     // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1751     // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1752     // *lck);
1753     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1754     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1755                                                /*isVarArg=*/false);
1756     llvm::Type *TypeParams[] = {
1757         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1758         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1759         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1760     llvm::FunctionType *FnTy =
1761         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1762     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1763     break;
1764   }
1765   case OMPRTL__kmpc_end_reduce: {
1766     // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1767     // kmp_critical_name *lck);
1768     llvm::Type *TypeParams[] = {
1769         getIdentTyPointerTy(), CGM.Int32Ty,
1770         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1771     llvm::FunctionType *FnTy =
1772         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1773     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1774     break;
1775   }
1776   case OMPRTL__kmpc_end_reduce_nowait: {
1777     // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1778     // kmp_critical_name *lck);
1779     llvm::Type *TypeParams[] = {
1780         getIdentTyPointerTy(), CGM.Int32Ty,
1781         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1782     llvm::FunctionType *FnTy =
1783         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1784     RTLFn =
1785         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1786     break;
1787   }
1788   case OMPRTL__kmpc_omp_task_begin_if0: {
1789     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1790     // *new_task);
1791     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1792                                 CGM.VoidPtrTy};
1793     llvm::FunctionType *FnTy =
1794         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1795     RTLFn =
1796         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1797     break;
1798   }
1799   case OMPRTL__kmpc_omp_task_complete_if0: {
1800     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1801     // *new_task);
1802     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1803                                 CGM.VoidPtrTy};
1804     llvm::FunctionType *FnTy =
1805         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1806     RTLFn = CGM.CreateRuntimeFunction(FnTy,
1807                                       /*Name=*/"__kmpc_omp_task_complete_if0");
1808     break;
1809   }
1810   case OMPRTL__kmpc_ordered: {
1811     // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1812     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1813     llvm::FunctionType *FnTy =
1814         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1815     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1816     break;
1817   }
1818   case OMPRTL__kmpc_end_ordered: {
1819     // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1820     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1821     llvm::FunctionType *FnTy =
1822         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1823     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1824     break;
1825   }
1826   case OMPRTL__kmpc_omp_taskwait: {
1827     // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1828     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1829     llvm::FunctionType *FnTy =
1830         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1831     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1832     break;
1833   }
1834   case OMPRTL__kmpc_taskgroup: {
1835     // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1836     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1837     llvm::FunctionType *FnTy =
1838         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1839     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1840     break;
1841   }
1842   case OMPRTL__kmpc_end_taskgroup: {
1843     // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1844     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1845     llvm::FunctionType *FnTy =
1846         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1848     break;
1849   }
1850   case OMPRTL__kmpc_push_proc_bind: {
1851     // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1852     // int proc_bind)
1853     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1854     llvm::FunctionType *FnTy =
1855         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1856     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1857     break;
1858   }
1859   case OMPRTL__kmpc_omp_task_with_deps: {
1860     // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1861     // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1862     // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1863     llvm::Type *TypeParams[] = {
1864         getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1865         CGM.VoidPtrTy,         CGM.Int32Ty, CGM.VoidPtrTy};
1866     llvm::FunctionType *FnTy =
1867         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1868     RTLFn =
1869         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1870     break;
1871   }
1872   case OMPRTL__kmpc_omp_wait_deps: {
1873     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1874     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1875     // kmp_depend_info_t *noalias_dep_list);
1876     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1877                                 CGM.Int32Ty,           CGM.VoidPtrTy,
1878                                 CGM.Int32Ty,           CGM.VoidPtrTy};
1879     llvm::FunctionType *FnTy =
1880         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1881     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1882     break;
1883   }
1884   case OMPRTL__kmpc_cancellationpoint: {
1885     // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1886     // global_tid, kmp_int32 cncl_kind)
1887     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1888     llvm::FunctionType *FnTy =
1889         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1890     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1891     break;
1892   }
1893   case OMPRTL__kmpc_cancel: {
1894     // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1895     // kmp_int32 cncl_kind)
1896     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1897     llvm::FunctionType *FnTy =
1898         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1899     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1900     break;
1901   }
1902   case OMPRTL__kmpc_push_num_teams: {
1903     // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1904     // kmp_int32 num_teams, kmp_int32 num_threads)
1905     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1906         CGM.Int32Ty};
1907     llvm::FunctionType *FnTy =
1908         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1909     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1910     break;
1911   }
1912   case OMPRTL__kmpc_fork_teams: {
1913     // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1914     // microtask, ...);
1915     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1916                                 getKmpc_MicroPointerTy()};
1917     llvm::FunctionType *FnTy =
1918         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1919     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1920     break;
1921   }
1922   case OMPRTL__kmpc_taskloop: {
1923     // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1924     // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1925     // sched, kmp_uint64 grainsize, void *task_dup);
1926     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1927                                 CGM.IntTy,
1928                                 CGM.VoidPtrTy,
1929                                 CGM.IntTy,
1930                                 CGM.Int64Ty->getPointerTo(),
1931                                 CGM.Int64Ty->getPointerTo(),
1932                                 CGM.Int64Ty,
1933                                 CGM.IntTy,
1934                                 CGM.IntTy,
1935                                 CGM.Int64Ty,
1936                                 CGM.VoidPtrTy};
1937     llvm::FunctionType *FnTy =
1938         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1939     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1940     break;
1941   }
1942   case OMPRTL__kmpc_doacross_init: {
1943     // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1944     // num_dims, struct kmp_dim *dims);
1945     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1946                                 CGM.Int32Ty,
1947                                 CGM.Int32Ty,
1948                                 CGM.VoidPtrTy};
1949     llvm::FunctionType *FnTy =
1950         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1952     break;
1953   }
1954   case OMPRTL__kmpc_doacross_fini: {
1955     // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1956     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1957     llvm::FunctionType *FnTy =
1958         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1959     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1960     break;
1961   }
1962   case OMPRTL__kmpc_doacross_post: {
1963     // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1964     // *vec);
1965     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1966                                 CGM.Int64Ty->getPointerTo()};
1967     llvm::FunctionType *FnTy =
1968         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1970     break;
1971   }
1972   case OMPRTL__kmpc_doacross_wait: {
1973     // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1974     // *vec);
1975     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1976                                 CGM.Int64Ty->getPointerTo()};
1977     llvm::FunctionType *FnTy =
1978         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1979     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1980     break;
1981   }
1982   case OMPRTL__kmpc_task_reduction_init: {
1983     // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1984     // *data);
1985     llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1986     llvm::FunctionType *FnTy =
1987         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1988     RTLFn =
1989         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1990     break;
1991   }
1992   case OMPRTL__kmpc_task_reduction_get_th_data: {
1993     // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
1994     // *d);
1995     llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
1996     llvm::FunctionType *FnTy =
1997         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1998     RTLFn = CGM.CreateRuntimeFunction(
1999         FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2000     break;
2001   }
2002   case OMPRTL__tgt_target: {
2003     // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2004     // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2005     // *arg_types);
2006     llvm::Type *TypeParams[] = {CGM.Int32Ty,
2007                                 CGM.VoidPtrTy,
2008                                 CGM.Int32Ty,
2009                                 CGM.VoidPtrPtrTy,
2010                                 CGM.VoidPtrPtrTy,
2011                                 CGM.SizeTy->getPointerTo(),
2012                                 CGM.Int32Ty->getPointerTo()};
2013     llvm::FunctionType *FnTy =
2014         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2015     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2016     break;
2017   }
2018   case OMPRTL__tgt_target_teams: {
2019     // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2020     // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2021     // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2022     llvm::Type *TypeParams[] = {CGM.Int32Ty,
2023                                 CGM.VoidPtrTy,
2024                                 CGM.Int32Ty,
2025                                 CGM.VoidPtrPtrTy,
2026                                 CGM.VoidPtrPtrTy,
2027                                 CGM.SizeTy->getPointerTo(),
2028                                 CGM.Int32Ty->getPointerTo(),
2029                                 CGM.Int32Ty,
2030                                 CGM.Int32Ty};
2031     llvm::FunctionType *FnTy =
2032         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2033     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2034     break;
2035   }
2036   case OMPRTL__tgt_register_lib: {
2037     // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2038     QualType ParamTy =
2039         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2040     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2041     llvm::FunctionType *FnTy =
2042         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2043     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2044     break;
2045   }
2046   case OMPRTL__tgt_unregister_lib: {
2047     // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2048     QualType ParamTy =
2049         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2050     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2051     llvm::FunctionType *FnTy =
2052         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2053     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2054     break;
2055   }
2056   case OMPRTL__tgt_target_data_begin: {
2057     // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2058     // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2059     llvm::Type *TypeParams[] = {CGM.Int32Ty,
2060                                 CGM.Int32Ty,
2061                                 CGM.VoidPtrPtrTy,
2062                                 CGM.VoidPtrPtrTy,
2063                                 CGM.SizeTy->getPointerTo(),
2064                                 CGM.Int32Ty->getPointerTo()};
2065     llvm::FunctionType *FnTy =
2066         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2067     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2068     break;
2069   }
2070   case OMPRTL__tgt_target_data_end: {
2071     // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2072     // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2073     llvm::Type *TypeParams[] = {CGM.Int32Ty,
2074                                 CGM.Int32Ty,
2075                                 CGM.VoidPtrPtrTy,
2076                                 CGM.VoidPtrPtrTy,
2077                                 CGM.SizeTy->getPointerTo(),
2078                                 CGM.Int32Ty->getPointerTo()};
2079     llvm::FunctionType *FnTy =
2080         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2081     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2082     break;
2083   }
2084   case OMPRTL__tgt_target_data_update: {
2085     // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2086     // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2087     llvm::Type *TypeParams[] = {CGM.Int32Ty,
2088                                 CGM.Int32Ty,
2089                                 CGM.VoidPtrPtrTy,
2090                                 CGM.VoidPtrPtrTy,
2091                                 CGM.SizeTy->getPointerTo(),
2092                                 CGM.Int32Ty->getPointerTo()};
2093     llvm::FunctionType *FnTy =
2094         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2095     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2096     break;
2097   }
2098   }
2099   assert(RTLFn && "Unable to find OpenMP runtime function");
2100   return RTLFn;
2101 }
2102 
2103 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2104                                                              bool IVSigned) {
2105   assert((IVSize == 32 || IVSize == 64) &&
2106          "IV size is not compatible with the omp runtime");
2107   auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2108                                        : "__kmpc_for_static_init_4u")
2109                            : (IVSigned ? "__kmpc_for_static_init_8"
2110                                        : "__kmpc_for_static_init_8u");
2111   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2112   auto PtrTy = llvm::PointerType::getUnqual(ITy);
2113   llvm::Type *TypeParams[] = {
2114     getIdentTyPointerTy(),                     // loc
2115     CGM.Int32Ty,                               // tid
2116     CGM.Int32Ty,                               // schedtype
2117     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2118     PtrTy,                                     // p_lower
2119     PtrTy,                                     // p_upper
2120     PtrTy,                                     // p_stride
2121     ITy,                                       // incr
2122     ITy                                        // chunk
2123   };
2124   llvm::FunctionType *FnTy =
2125       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2126   return CGM.CreateRuntimeFunction(FnTy, Name);
2127 }
2128 
2129 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2130                                                             bool IVSigned) {
2131   assert((IVSize == 32 || IVSize == 64) &&
2132          "IV size is not compatible with the omp runtime");
2133   auto Name =
2134       IVSize == 32
2135           ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2136           : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2137   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2138   llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2139                                CGM.Int32Ty,           // tid
2140                                CGM.Int32Ty,           // schedtype
2141                                ITy,                   // lower
2142                                ITy,                   // upper
2143                                ITy,                   // stride
2144                                ITy                    // chunk
2145   };
2146   llvm::FunctionType *FnTy =
2147       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2148   return CGM.CreateRuntimeFunction(FnTy, Name);
2149 }
2150 
2151 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2152                                                             bool IVSigned) {
2153   assert((IVSize == 32 || IVSize == 64) &&
2154          "IV size is not compatible with the omp runtime");
2155   auto Name =
2156       IVSize == 32
2157           ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2158           : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2159   llvm::Type *TypeParams[] = {
2160       getIdentTyPointerTy(), // loc
2161       CGM.Int32Ty,           // tid
2162   };
2163   llvm::FunctionType *FnTy =
2164       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2165   return CGM.CreateRuntimeFunction(FnTy, Name);
2166 }
2167 
2168 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2169                                                             bool IVSigned) {
2170   assert((IVSize == 32 || IVSize == 64) &&
2171          "IV size is not compatible with the omp runtime");
2172   auto Name =
2173       IVSize == 32
2174           ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2175           : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2176   auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2177   auto PtrTy = llvm::PointerType::getUnqual(ITy);
2178   llvm::Type *TypeParams[] = {
2179     getIdentTyPointerTy(),                     // loc
2180     CGM.Int32Ty,                               // tid
2181     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2182     PtrTy,                                     // p_lower
2183     PtrTy,                                     // p_upper
2184     PtrTy                                      // p_stride
2185   };
2186   llvm::FunctionType *FnTy =
2187       llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2188   return CGM.CreateRuntimeFunction(FnTy, Name);
2189 }
2190 
2191 llvm::Constant *
2192 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
2193   assert(!CGM.getLangOpts().OpenMPUseTLS ||
2194          !CGM.getContext().getTargetInfo().isTLSSupported());
2195   // Lookup the entry, lazily creating it if necessary.
2196   return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
2197                                      Twine(CGM.getMangledName(VD)) + ".cache.");
2198 }
2199 
2200 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2201                                                 const VarDecl *VD,
2202                                                 Address VDAddr,
2203                                                 SourceLocation Loc) {
2204   if (CGM.getLangOpts().OpenMPUseTLS &&
2205       CGM.getContext().getTargetInfo().isTLSSupported())
2206     return VDAddr;
2207 
2208   auto VarTy = VDAddr.getElementType();
2209   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2210                          CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2211                                                        CGM.Int8PtrTy),
2212                          CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2213                          getOrCreateThreadPrivateCache(VD)};
2214   return Address(CGF.EmitRuntimeCall(
2215       createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2216                  VDAddr.getAlignment());
2217 }
2218 
2219 void CGOpenMPRuntime::emitThreadPrivateVarInit(
2220     CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
2221     llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2222   // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2223   // library.
2224   auto OMPLoc = emitUpdateLocation(CGF, Loc);
2225   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
2226                       OMPLoc);
2227   // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2228   // to register constructor/destructor for variable.
2229   llvm::Value *Args[] = {OMPLoc,
2230                          CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2231                                                        CGM.VoidPtrTy),
2232                          Ctor, CopyCtor, Dtor};
2233   CGF.EmitRuntimeCall(
2234       createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
2235 }
2236 
2237 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
2238     const VarDecl *VD, Address VDAddr, SourceLocation Loc,
2239     bool PerformInit, CodeGenFunction *CGF) {
2240   if (CGM.getLangOpts().OpenMPUseTLS &&
2241       CGM.getContext().getTargetInfo().isTLSSupported())
2242     return nullptr;
2243 
2244   VD = VD->getDefinition(CGM.getContext());
2245   if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2246     ThreadPrivateWithDefinition.insert(VD);
2247     QualType ASTTy = VD->getType();
2248 
2249     llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2250     auto Init = VD->getAnyInitializer();
2251     if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2252       // Generate function that re-emits the declaration's initializer into the
2253       // threadprivate copy of the variable VD
2254       CodeGenFunction CtorCGF(CGM);
2255       FunctionArgList Args;
2256       ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2257                             ImplicitParamDecl::Other);
2258       Args.push_back(&Dst);
2259 
2260       auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2261           CGM.getContext().VoidPtrTy, Args);
2262       auto FTy = CGM.getTypes().GetFunctionType(FI);
2263       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
2264           FTy, ".__kmpc_global_ctor_.", FI, Loc);
2265       CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2266                             Args, SourceLocation());
2267       auto ArgVal = CtorCGF.EmitLoadOfScalar(
2268           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2269           CGM.getContext().VoidPtrTy, Dst.getLocation());
2270       Address Arg = Address(ArgVal, VDAddr.getAlignment());
2271       Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2272                                              CtorCGF.ConvertTypeForMem(ASTTy));
2273       CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2274                                /*IsInitializer=*/true);
2275       ArgVal = CtorCGF.EmitLoadOfScalar(
2276           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2277           CGM.getContext().VoidPtrTy, Dst.getLocation());
2278       CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2279       CtorCGF.FinishFunction();
2280       Ctor = Fn;
2281     }
2282     if (VD->getType().isDestructedType() != QualType::DK_none) {
2283       // Generate function that emits destructor call for the threadprivate copy
2284       // of the variable VD
2285       CodeGenFunction DtorCGF(CGM);
2286       FunctionArgList Args;
2287       ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2288                             ImplicitParamDecl::Other);
2289       Args.push_back(&Dst);
2290 
2291       auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2292           CGM.getContext().VoidTy, Args);
2293       auto FTy = CGM.getTypes().GetFunctionType(FI);
2294       auto Fn = CGM.CreateGlobalInitOrDestructFunction(
2295           FTy, ".__kmpc_global_dtor_.", FI, Loc);
2296       auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2297       DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2298                             SourceLocation());
2299       // Create a scope with an artificial location for the body of this function.
2300       auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2301       auto ArgVal = DtorCGF.EmitLoadOfScalar(
2302           DtorCGF.GetAddrOfLocalVar(&Dst),
2303           /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2304       DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
2305                           DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2306                           DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2307       DtorCGF.FinishFunction();
2308       Dtor = Fn;
2309     }
2310     // Do not emit init function if it is not required.
2311     if (!Ctor && !Dtor)
2312       return nullptr;
2313 
2314     llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2315     auto CopyCtorTy =
2316         llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2317                                 /*isVarArg=*/false)->getPointerTo();
2318     // Copying constructor for the threadprivate variable.
2319     // Must be NULL - reserved by runtime, but currently it requires that this
2320     // parameter is always NULL. Otherwise it fires assertion.
2321     CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2322     if (Ctor == nullptr) {
2323       auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2324                                             /*isVarArg=*/false)->getPointerTo();
2325       Ctor = llvm::Constant::getNullValue(CtorTy);
2326     }
2327     if (Dtor == nullptr) {
2328       auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2329                                             /*isVarArg=*/false)->getPointerTo();
2330       Dtor = llvm::Constant::getNullValue(DtorTy);
2331     }
2332     if (!CGF) {
2333       auto InitFunctionTy =
2334           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2335       auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
2336           InitFunctionTy, ".__omp_threadprivate_init_.",
2337           CGM.getTypes().arrangeNullaryFunction());
2338       CodeGenFunction InitCGF(CGM);
2339       FunctionArgList ArgList;
2340       InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2341                             CGM.getTypes().arrangeNullaryFunction(), ArgList,
2342                             Loc);
2343       emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2344       InitCGF.FinishFunction();
2345       return InitFunction;
2346     }
2347     emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2348   }
2349   return nullptr;
2350 }
2351 
2352 Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2353                                                           QualType VarType,
2354                                                           StringRef Name) {
2355   llvm::Twine VarName(Name, ".artificial.");
2356   llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2357   llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2358   llvm::Value *Args[] = {
2359       emitUpdateLocation(CGF, SourceLocation()),
2360       getThreadID(CGF, SourceLocation()),
2361       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2362       CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2363                                 /*IsSigned=*/false),
2364       getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2365   return Address(
2366       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2367           CGF.EmitRuntimeCall(
2368               createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2369           VarLVType->getPointerTo(/*AddrSpace=*/0)),
2370       CGM.getPointerAlign());
2371 }
2372 
2373 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2374 /// function. Here is the logic:
2375 /// if (Cond) {
2376 ///   ThenGen();
2377 /// } else {
2378 ///   ElseGen();
2379 /// }
2380 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2381                                       const RegionCodeGenTy &ThenGen,
2382                                       const RegionCodeGenTy &ElseGen) {
2383   CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2384 
2385   // If the condition constant folds and can be elided, try to avoid emitting
2386   // the condition and the dead arm of the if/else.
2387   bool CondConstant;
2388   if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2389     if (CondConstant)
2390       ThenGen(CGF);
2391     else
2392       ElseGen(CGF);
2393     return;
2394   }
2395 
2396   // Otherwise, the condition did not fold, or we couldn't elide it.  Just
2397   // emit the conditional branch.
2398   auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2399   auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2400   auto ContBlock = CGF.createBasicBlock("omp_if.end");
2401   CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2402 
2403   // Emit the 'then' code.
2404   CGF.EmitBlock(ThenBlock);
2405   ThenGen(CGF);
2406   CGF.EmitBranch(ContBlock);
2407   // Emit the 'else' code if present.
2408   // There is no need to emit line number for unconditional branch.
2409   (void)ApplyDebugLocation::CreateEmpty(CGF);
2410   CGF.EmitBlock(ElseBlock);
2411   ElseGen(CGF);
2412   // There is no need to emit line number for unconditional branch.
2413   (void)ApplyDebugLocation::CreateEmpty(CGF);
2414   CGF.EmitBranch(ContBlock);
2415   // Emit the continuation block for code after the if.
2416   CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2417 }
2418 
2419 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2420                                        llvm::Value *OutlinedFn,
2421                                        ArrayRef<llvm::Value *> CapturedVars,
2422                                        const Expr *IfCond) {
2423   if (!CGF.HaveInsertPoint())
2424     return;
2425   auto *RTLoc = emitUpdateLocation(CGF, Loc);
2426   auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2427                                                      PrePostActionTy &) {
2428     // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2429     auto &RT = CGF.CGM.getOpenMPRuntime();
2430     llvm::Value *Args[] = {
2431         RTLoc,
2432         CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2433         CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2434     llvm::SmallVector<llvm::Value *, 16> RealArgs;
2435     RealArgs.append(std::begin(Args), std::end(Args));
2436     RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2437 
2438     auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
2439     CGF.EmitRuntimeCall(RTLFn, RealArgs);
2440   };
2441   auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2442                                                           PrePostActionTy &) {
2443     auto &RT = CGF.CGM.getOpenMPRuntime();
2444     auto ThreadID = RT.getThreadID(CGF, Loc);
2445     // Build calls:
2446     // __kmpc_serialized_parallel(&Loc, GTid);
2447     llvm::Value *Args[] = {RTLoc, ThreadID};
2448     CGF.EmitRuntimeCall(
2449         RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
2450 
2451     // OutlinedFn(&GTid, &zero, CapturedStruct);
2452     auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2453     Address ZeroAddr =
2454         CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2455                              /*Name*/ ".zero.addr");
2456     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2457     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2458     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2459     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2460     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2461     RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2462 
2463     // __kmpc_end_serialized_parallel(&Loc, GTid);
2464     llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2465     CGF.EmitRuntimeCall(
2466         RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2467         EndArgs);
2468   };
2469   if (IfCond)
2470     emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2471   else {
2472     RegionCodeGenTy ThenRCG(ThenGen);
2473     ThenRCG(CGF);
2474   }
2475 }
2476 
2477 // If we're inside an (outlined) parallel region, use the region info's
2478 // thread-ID variable (it is passed in a first argument of the outlined function
2479 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2480 // regular serial code region, get thread ID by calling kmp_int32
2481 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2482 // return the address of that temp.
2483 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2484                                              SourceLocation Loc) {
2485   if (auto *OMPRegionInfo =
2486           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2487     if (OMPRegionInfo->getThreadIDVariable())
2488       return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2489 
2490   auto ThreadID = getThreadID(CGF, Loc);
2491   auto Int32Ty =
2492       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2493   auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2494   CGF.EmitStoreOfScalar(ThreadID,
2495                         CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2496 
2497   return ThreadIDTemp;
2498 }
2499 
2500 llvm::Constant *
2501 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2502                                              const llvm::Twine &Name) {
2503   SmallString<256> Buffer;
2504   llvm::raw_svector_ostream Out(Buffer);
2505   Out << Name;
2506   auto RuntimeName = Out.str();
2507   auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2508   if (Elem.second) {
2509     assert(Elem.second->getType()->getPointerElementType() == Ty &&
2510            "OMP internal variable has different type than requested");
2511     return &*Elem.second;
2512   }
2513 
2514   return Elem.second = new llvm::GlobalVariable(
2515              CGM.getModule(), Ty, /*IsConstant*/ false,
2516              llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2517              Elem.first());
2518 }
2519 
2520 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2521   llvm::Twine Name(".gomp_critical_user_", CriticalName);
2522   return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
2523 }
2524 
2525 namespace {
2526 /// Common pre(post)-action for different OpenMP constructs.
2527 class CommonActionTy final : public PrePostActionTy {
2528   llvm::Value *EnterCallee;
2529   ArrayRef<llvm::Value *> EnterArgs;
2530   llvm::Value *ExitCallee;
2531   ArrayRef<llvm::Value *> ExitArgs;
2532   bool Conditional;
2533   llvm::BasicBlock *ContBlock = nullptr;
2534 
2535 public:
2536   CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2537                  llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2538                  bool Conditional = false)
2539       : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2540         ExitArgs(ExitArgs), Conditional(Conditional) {}
2541   void Enter(CodeGenFunction &CGF) override {
2542     llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2543     if (Conditional) {
2544       llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2545       auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2546       ContBlock = CGF.createBasicBlock("omp_if.end");
2547       // Generate the branch (If-stmt)
2548       CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2549       CGF.EmitBlock(ThenBlock);
2550     }
2551   }
2552   void Done(CodeGenFunction &CGF) {
2553     // Emit the rest of blocks/branches
2554     CGF.EmitBranch(ContBlock);
2555     CGF.EmitBlock(ContBlock, true);
2556   }
2557   void Exit(CodeGenFunction &CGF) override {
2558     CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2559   }
2560 };
2561 } // anonymous namespace
2562 
2563 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2564                                          StringRef CriticalName,
2565                                          const RegionCodeGenTy &CriticalOpGen,
2566                                          SourceLocation Loc, const Expr *Hint) {
2567   // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2568   // CriticalOpGen();
2569   // __kmpc_end_critical(ident_t *, gtid, Lock);
2570   // Prepare arguments and build a call to __kmpc_critical
2571   if (!CGF.HaveInsertPoint())
2572     return;
2573   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2574                          getCriticalRegionLock(CriticalName)};
2575   llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2576                                                 std::end(Args));
2577   if (Hint) {
2578     EnterArgs.push_back(CGF.Builder.CreateIntCast(
2579         CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2580   }
2581   CommonActionTy Action(
2582       createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2583                                  : OMPRTL__kmpc_critical),
2584       EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2585   CriticalOpGen.setAction(Action);
2586   emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2587 }
2588 
2589 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2590                                        const RegionCodeGenTy &MasterOpGen,
2591                                        SourceLocation Loc) {
2592   if (!CGF.HaveInsertPoint())
2593     return;
2594   // if(__kmpc_master(ident_t *, gtid)) {
2595   //   MasterOpGen();
2596   //   __kmpc_end_master(ident_t *, gtid);
2597   // }
2598   // Prepare arguments and build a call to __kmpc_master
2599   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2600   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2601                         createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2602                         /*Conditional=*/true);
2603   MasterOpGen.setAction(Action);
2604   emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2605   Action.Done(CGF);
2606 }
2607 
2608 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2609                                         SourceLocation Loc) {
2610   if (!CGF.HaveInsertPoint())
2611     return;
2612   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2613   llvm::Value *Args[] = {
2614       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2615       llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2616   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
2617   if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2618     Region->emitUntiedSwitch(CGF);
2619 }
2620 
2621 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2622                                           const RegionCodeGenTy &TaskgroupOpGen,
2623                                           SourceLocation Loc) {
2624   if (!CGF.HaveInsertPoint())
2625     return;
2626   // __kmpc_taskgroup(ident_t *, gtid);
2627   // TaskgroupOpGen();
2628   // __kmpc_end_taskgroup(ident_t *, gtid);
2629   // Prepare arguments and build a call to __kmpc_taskgroup
2630   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2631   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2632                         createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2633                         Args);
2634   TaskgroupOpGen.setAction(Action);
2635   emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2636 }
2637 
2638 /// Given an array of pointers to variables, project the address of a
2639 /// given variable.
2640 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2641                                       unsigned Index, const VarDecl *Var) {
2642   // Pull out the pointer to the variable.
2643   Address PtrAddr =
2644       CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
2645   llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2646 
2647   Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2648   Addr = CGF.Builder.CreateElementBitCast(
2649       Addr, CGF.ConvertTypeForMem(Var->getType()));
2650   return Addr;
2651 }
2652 
2653 static llvm::Value *emitCopyprivateCopyFunction(
2654     CodeGenModule &CGM, llvm::Type *ArgsType,
2655     ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2656     ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
2657   auto &C = CGM.getContext();
2658   // void copy_func(void *LHSArg, void *RHSArg);
2659   FunctionArgList Args;
2660   ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2661   ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2662   Args.push_back(&LHSArg);
2663   Args.push_back(&RHSArg);
2664   auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2665   auto *Fn = llvm::Function::Create(
2666       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2667       ".omp.copyprivate.copy_func", &CGM.getModule());
2668   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
2669   CodeGenFunction CGF(CGM);
2670   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
2671   // Dest = (void*[n])(LHSArg);
2672   // Src = (void*[n])(RHSArg);
2673   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2674       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2675       ArgsType), CGF.getPointerAlign());
2676   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2677       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2678       ArgsType), CGF.getPointerAlign());
2679   // *(Type0*)Dst[0] = *(Type0*)Src[0];
2680   // *(Type1*)Dst[1] = *(Type1*)Src[1];
2681   // ...
2682   // *(Typen*)Dst[n] = *(Typen*)Src[n];
2683   for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
2684     auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2685     Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2686 
2687     auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2688     Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2689 
2690     auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2691     QualType Type = VD->getType();
2692     CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2693   }
2694   CGF.FinishFunction();
2695   return Fn;
2696 }
2697 
2698 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2699                                        const RegionCodeGenTy &SingleOpGen,
2700                                        SourceLocation Loc,
2701                                        ArrayRef<const Expr *> CopyprivateVars,
2702                                        ArrayRef<const Expr *> SrcExprs,
2703                                        ArrayRef<const Expr *> DstExprs,
2704                                        ArrayRef<const Expr *> AssignmentOps) {
2705   if (!CGF.HaveInsertPoint())
2706     return;
2707   assert(CopyprivateVars.size() == SrcExprs.size() &&
2708          CopyprivateVars.size() == DstExprs.size() &&
2709          CopyprivateVars.size() == AssignmentOps.size());
2710   auto &C = CGM.getContext();
2711   // int32 did_it = 0;
2712   // if(__kmpc_single(ident_t *, gtid)) {
2713   //   SingleOpGen();
2714   //   __kmpc_end_single(ident_t *, gtid);
2715   //   did_it = 1;
2716   // }
2717   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2718   // <copy_func>, did_it);
2719 
2720   Address DidIt = Address::invalid();
2721   if (!CopyprivateVars.empty()) {
2722     // int32 did_it = 0;
2723     auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2724     DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2725     CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2726   }
2727   // Prepare arguments and build a call to __kmpc_single
2728   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2729   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2730                         createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2731                         /*Conditional=*/true);
2732   SingleOpGen.setAction(Action);
2733   emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2734   if (DidIt.isValid()) {
2735     // did_it = 1;
2736     CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2737   }
2738   Action.Done(CGF);
2739   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2740   // <copy_func>, did_it);
2741   if (DidIt.isValid()) {
2742     llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2743     auto CopyprivateArrayTy =
2744         C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2745                                /*IndexTypeQuals=*/0);
2746     // Create a list of all private variables for copyprivate.
2747     Address CopyprivateList =
2748         CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2749     for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
2750       Address Elem = CGF.Builder.CreateConstArrayGEP(
2751           CopyprivateList, I, CGF.getPointerSize());
2752       CGF.Builder.CreateStore(
2753           CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2754               CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2755           Elem);
2756     }
2757     // Build function that copies private values from single region to all other
2758     // threads in the corresponding parallel region.
2759     auto *CpyFn = emitCopyprivateCopyFunction(
2760         CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2761         CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
2762     auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2763     Address CL =
2764       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2765                                                       CGF.VoidPtrTy);
2766     auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
2767     llvm::Value *Args[] = {
2768         emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2769         getThreadID(CGF, Loc),        // i32 <gtid>
2770         BufSize,                      // size_t <buf_size>
2771         CL.getPointer(),              // void *<copyprivate list>
2772         CpyFn,                        // void (*) (void *, void *) <copy_func>
2773         DidItVal                      // i32 did_it
2774     };
2775     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2776   }
2777 }
2778 
2779 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2780                                         const RegionCodeGenTy &OrderedOpGen,
2781                                         SourceLocation Loc, bool IsThreads) {
2782   if (!CGF.HaveInsertPoint())
2783     return;
2784   // __kmpc_ordered(ident_t *, gtid);
2785   // OrderedOpGen();
2786   // __kmpc_end_ordered(ident_t *, gtid);
2787   // Prepare arguments and build a call to __kmpc_ordered
2788   if (IsThreads) {
2789     llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2790     CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2791                           createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2792                           Args);
2793     OrderedOpGen.setAction(Action);
2794     emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2795     return;
2796   }
2797   emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2798 }
2799 
2800 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2801                                       OpenMPDirectiveKind Kind, bool EmitChecks,
2802                                       bool ForceSimpleCall) {
2803   if (!CGF.HaveInsertPoint())
2804     return;
2805   // Build call __kmpc_cancel_barrier(loc, thread_id);
2806   // Build call __kmpc_barrier(loc, thread_id);
2807   unsigned Flags;
2808   if (Kind == OMPD_for)
2809     Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2810   else if (Kind == OMPD_sections)
2811     Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2812   else if (Kind == OMPD_single)
2813     Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2814   else if (Kind == OMPD_barrier)
2815     Flags = OMP_IDENT_BARRIER_EXPL;
2816   else
2817     Flags = OMP_IDENT_BARRIER_IMPL;
2818   // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2819   // thread_id);
2820   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2821                          getThreadID(CGF, Loc)};
2822   if (auto *OMPRegionInfo =
2823           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
2824     if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
2825       auto *Result = CGF.EmitRuntimeCall(
2826           createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
2827       if (EmitChecks) {
2828         // if (__kmpc_cancel_barrier()) {
2829         //   exit from construct;
2830         // }
2831         auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2832         auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2833         auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2834         CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2835         CGF.EmitBlock(ExitBB);
2836         //   exit from construct;
2837         auto CancelDestination =
2838             CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2839         CGF.EmitBranchThroughCleanup(CancelDestination);
2840         CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2841       }
2842       return;
2843     }
2844   }
2845   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2846 }
2847 
2848 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
2849 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2850                                           bool Chunked, bool Ordered) {
2851   switch (ScheduleKind) {
2852   case OMPC_SCHEDULE_static:
2853     return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2854                    : (Ordered ? OMP_ord_static : OMP_sch_static);
2855   case OMPC_SCHEDULE_dynamic:
2856     return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
2857   case OMPC_SCHEDULE_guided:
2858     return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
2859   case OMPC_SCHEDULE_runtime:
2860     return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2861   case OMPC_SCHEDULE_auto:
2862     return Ordered ? OMP_ord_auto : OMP_sch_auto;
2863   case OMPC_SCHEDULE_unknown:
2864     assert(!Chunked && "chunk was specified but schedule kind not known");
2865     return Ordered ? OMP_ord_static : OMP_sch_static;
2866   }
2867   llvm_unreachable("Unexpected runtime schedule");
2868 }
2869 
2870 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2871 static OpenMPSchedType
2872 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2873   // only static is allowed for dist_schedule
2874   return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2875 }
2876 
2877 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2878                                          bool Chunked) const {
2879   auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2880   return Schedule == OMP_sch_static;
2881 }
2882 
2883 bool CGOpenMPRuntime::isStaticNonchunked(
2884     OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2885   auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2886   return Schedule == OMP_dist_sch_static;
2887 }
2888 
2889 
2890 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2891   auto Schedule =
2892       getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2893   assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2894   return Schedule != OMP_sch_static;
2895 }
2896 
2897 static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2898                                   OpenMPScheduleClauseModifier M1,
2899                                   OpenMPScheduleClauseModifier M2) {
2900   int Modifier = 0;
2901   switch (M1) {
2902   case OMPC_SCHEDULE_MODIFIER_monotonic:
2903     Modifier = OMP_sch_modifier_monotonic;
2904     break;
2905   case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2906     Modifier = OMP_sch_modifier_nonmonotonic;
2907     break;
2908   case OMPC_SCHEDULE_MODIFIER_simd:
2909     if (Schedule == OMP_sch_static_chunked)
2910       Schedule = OMP_sch_static_balanced_chunked;
2911     break;
2912   case OMPC_SCHEDULE_MODIFIER_last:
2913   case OMPC_SCHEDULE_MODIFIER_unknown:
2914     break;
2915   }
2916   switch (M2) {
2917   case OMPC_SCHEDULE_MODIFIER_monotonic:
2918     Modifier = OMP_sch_modifier_monotonic;
2919     break;
2920   case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2921     Modifier = OMP_sch_modifier_nonmonotonic;
2922     break;
2923   case OMPC_SCHEDULE_MODIFIER_simd:
2924     if (Schedule == OMP_sch_static_chunked)
2925       Schedule = OMP_sch_static_balanced_chunked;
2926     break;
2927   case OMPC_SCHEDULE_MODIFIER_last:
2928   case OMPC_SCHEDULE_MODIFIER_unknown:
2929     break;
2930   }
2931   return Schedule | Modifier;
2932 }
2933 
2934 void CGOpenMPRuntime::emitForDispatchInit(
2935     CodeGenFunction &CGF, SourceLocation Loc,
2936     const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2937     bool Ordered, const DispatchRTInput &DispatchValues) {
2938   if (!CGF.HaveInsertPoint())
2939     return;
2940   OpenMPSchedType Schedule = getRuntimeSchedule(
2941       ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
2942   assert(Ordered ||
2943          (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2944           Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2945           Schedule != OMP_sch_static_balanced_chunked));
2946   // Call __kmpc_dispatch_init(
2947   //          ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2948   //          kmp_int[32|64] lower, kmp_int[32|64] upper,
2949   //          kmp_int[32|64] stride, kmp_int[32|64] chunk);
2950 
2951   // If the Chunk was not specified in the clause - use default value 1.
2952   llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2953                                             : CGF.Builder.getIntN(IVSize, 1);
2954   llvm::Value *Args[] = {
2955       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2956       CGF.Builder.getInt32(addMonoNonMonoModifier(
2957           Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2958       DispatchValues.LB,                                // Lower
2959       DispatchValues.UB,                                // Upper
2960       CGF.Builder.getIntN(IVSize, 1),                   // Stride
2961       Chunk                                             // Chunk
2962   };
2963   CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2964 }
2965 
2966 static void emitForStaticInitCall(
2967     CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2968     llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2969     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2970     const CGOpenMPRuntime::StaticRTInput &Values) {
2971   if (!CGF.HaveInsertPoint())
2972     return;
2973 
2974   assert(!Values.Ordered);
2975   assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2976          Schedule == OMP_sch_static_balanced_chunked ||
2977          Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2978          Schedule == OMP_dist_sch_static ||
2979          Schedule == OMP_dist_sch_static_chunked);
2980 
2981   // Call __kmpc_for_static_init(
2982   //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2983   //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2984   //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2985   //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
2986   llvm::Value *Chunk = Values.Chunk;
2987   if (Chunk == nullptr) {
2988     assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2989             Schedule == OMP_dist_sch_static) &&
2990            "expected static non-chunked schedule");
2991     // If the Chunk was not specified in the clause - use default value 1.
2992     Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2993   } else {
2994     assert((Schedule == OMP_sch_static_chunked ||
2995             Schedule == OMP_sch_static_balanced_chunked ||
2996             Schedule == OMP_ord_static_chunked ||
2997             Schedule == OMP_dist_sch_static_chunked) &&
2998            "expected static chunked schedule");
2999   }
3000   llvm::Value *Args[] = {
3001       UpdateLocation,
3002       ThreadId,
3003       CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3004                                                   M2)), // Schedule type
3005       Values.IL.getPointer(),                           // &isLastIter
3006       Values.LB.getPointer(),                           // &LB
3007       Values.UB.getPointer(),                           // &UB
3008       Values.ST.getPointer(),                           // &Stride
3009       CGF.Builder.getIntN(Values.IVSize, 1),            // Incr
3010       Chunk                                             // Chunk
3011   };
3012   CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3013 }
3014 
3015 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3016                                         SourceLocation Loc,
3017                                         OpenMPDirectiveKind DKind,
3018                                         const OpenMPScheduleTy &ScheduleKind,
3019                                         const StaticRTInput &Values) {
3020   OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3021       ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3022   assert(isOpenMPWorksharingDirective(DKind) &&
3023          "Expected loop-based or sections-based directive.");
3024   auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3025                                              isOpenMPLoopDirective(DKind)
3026                                                  ? OMP_IDENT_WORK_LOOP
3027                                                  : OMP_IDENT_WORK_SECTIONS);
3028   auto *ThreadId = getThreadID(CGF, Loc);
3029   auto *StaticInitFunction =
3030       createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3031   emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3032                         ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
3033 }
3034 
3035 void CGOpenMPRuntime::emitDistributeStaticInit(
3036     CodeGenFunction &CGF, SourceLocation Loc,
3037     OpenMPDistScheduleClauseKind SchedKind,
3038     const CGOpenMPRuntime::StaticRTInput &Values) {
3039   OpenMPSchedType ScheduleNum =
3040       getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3041   auto *UpdatedLocation =
3042       emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
3043   auto *ThreadId = getThreadID(CGF, Loc);
3044   auto *StaticInitFunction =
3045       createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3046   emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3047                         ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3048                         OMPC_SCHEDULE_MODIFIER_unknown, Values);
3049 }
3050 
3051 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3052                                           SourceLocation Loc) {
3053   if (!CGF.HaveInsertPoint())
3054     return;
3055   // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
3056   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3057   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3058                       Args);
3059 }
3060 
3061 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3062                                                  SourceLocation Loc,
3063                                                  unsigned IVSize,
3064                                                  bool IVSigned) {
3065   if (!CGF.HaveInsertPoint())
3066     return;
3067   // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
3068   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3069   CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3070 }
3071 
3072 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3073                                           SourceLocation Loc, unsigned IVSize,
3074                                           bool IVSigned, Address IL,
3075                                           Address LB, Address UB,
3076                                           Address ST) {
3077   // Call __kmpc_dispatch_next(
3078   //          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3079   //          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3080   //          kmp_int[32|64] *p_stride);
3081   llvm::Value *Args[] = {
3082       emitUpdateLocation(CGF, Loc),
3083       getThreadID(CGF, Loc),
3084       IL.getPointer(), // &isLastIter
3085       LB.getPointer(), // &Lower
3086       UB.getPointer(), // &Upper
3087       ST.getPointer()  // &Stride
3088   };
3089   llvm::Value *Call =
3090       CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3091   return CGF.EmitScalarConversion(
3092       Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
3093       CGF.getContext().BoolTy, Loc);
3094 }
3095 
3096 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3097                                            llvm::Value *NumThreads,
3098                                            SourceLocation Loc) {
3099   if (!CGF.HaveInsertPoint())
3100     return;
3101   // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3102   llvm::Value *Args[] = {
3103       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3104       CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
3105   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3106                       Args);
3107 }
3108 
3109 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3110                                          OpenMPProcBindClauseKind ProcBind,
3111                                          SourceLocation Loc) {
3112   if (!CGF.HaveInsertPoint())
3113     return;
3114   // Constants for proc bind value accepted by the runtime.
3115   enum ProcBindTy {
3116     ProcBindFalse = 0,
3117     ProcBindTrue,
3118     ProcBindMaster,
3119     ProcBindClose,
3120     ProcBindSpread,
3121     ProcBindIntel,
3122     ProcBindDefault
3123   } RuntimeProcBind;
3124   switch (ProcBind) {
3125   case OMPC_PROC_BIND_master:
3126     RuntimeProcBind = ProcBindMaster;
3127     break;
3128   case OMPC_PROC_BIND_close:
3129     RuntimeProcBind = ProcBindClose;
3130     break;
3131   case OMPC_PROC_BIND_spread:
3132     RuntimeProcBind = ProcBindSpread;
3133     break;
3134   case OMPC_PROC_BIND_unknown:
3135     llvm_unreachable("Unsupported proc_bind value.");
3136   }
3137   // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3138   llvm::Value *Args[] = {
3139       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3140       llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3141   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3142 }
3143 
3144 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3145                                 SourceLocation Loc) {
3146   if (!CGF.HaveInsertPoint())
3147     return;
3148   // Build call void __kmpc_flush(ident_t *loc)
3149   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3150                       emitUpdateLocation(CGF, Loc));
3151 }
3152 
3153 namespace {
3154 /// \brief Indexes of fields for type kmp_task_t.
3155 enum KmpTaskTFields {
3156   /// \brief List of shared variables.
3157   KmpTaskTShareds,
3158   /// \brief Task routine.
3159   KmpTaskTRoutine,
3160   /// \brief Partition id for the untied tasks.
3161   KmpTaskTPartId,
3162   /// Function with call of destructors for private variables.
3163   Data1,
3164   /// Task priority.
3165   Data2,
3166   /// (Taskloops only) Lower bound.
3167   KmpTaskTLowerBound,
3168   /// (Taskloops only) Upper bound.
3169   KmpTaskTUpperBound,
3170   /// (Taskloops only) Stride.
3171   KmpTaskTStride,
3172   /// (Taskloops only) Is last iteration flag.
3173   KmpTaskTLastIter,
3174   /// (Taskloops only) Reduction data.
3175   KmpTaskTReductions,
3176 };
3177 } // anonymous namespace
3178 
3179 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3180   // FIXME: Add other entries type when they become supported.
3181   return OffloadEntriesTargetRegion.empty();
3182 }
3183 
3184 /// \brief Initialize target region entry.
3185 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3186     initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3187                                     StringRef ParentName, unsigned LineNum,
3188                                     unsigned Order) {
3189   assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3190                                              "only required for the device "
3191                                              "code generation.");
3192   OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
3193       OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3194                                    /*Flags=*/0);
3195   ++OffloadingEntriesNum;
3196 }
3197 
3198 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3199     registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3200                                   StringRef ParentName, unsigned LineNum,
3201                                   llvm::Constant *Addr, llvm::Constant *ID,
3202                                   int32_t Flags) {
3203   // If we are emitting code for a target, the entry is already initialized,
3204   // only has to be registered.
3205   if (CGM.getLangOpts().OpenMPIsDevice) {
3206     assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
3207            "Entry must exist.");
3208     auto &Entry =
3209         OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3210     assert(Entry.isValid() && "Entry not initialized!");
3211     Entry.setAddress(Addr);
3212     Entry.setID(ID);
3213     Entry.setFlags(Flags);
3214     return;
3215   } else {
3216     OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
3217     OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3218   }
3219 }
3220 
3221 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3222     unsigned DeviceID, unsigned FileID, StringRef ParentName,
3223     unsigned LineNum) const {
3224   auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3225   if (PerDevice == OffloadEntriesTargetRegion.end())
3226     return false;
3227   auto PerFile = PerDevice->second.find(FileID);
3228   if (PerFile == PerDevice->second.end())
3229     return false;
3230   auto PerParentName = PerFile->second.find(ParentName);
3231   if (PerParentName == PerFile->second.end())
3232     return false;
3233   auto PerLine = PerParentName->second.find(LineNum);
3234   if (PerLine == PerParentName->second.end())
3235     return false;
3236   // Fail if this entry is already registered.
3237   if (PerLine->second.getAddress() || PerLine->second.getID())
3238     return false;
3239   return true;
3240 }
3241 
3242 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3243     const OffloadTargetRegionEntryInfoActTy &Action) {
3244   // Scan all target region entries and perform the provided action.
3245   for (auto &D : OffloadEntriesTargetRegion)
3246     for (auto &F : D.second)
3247       for (auto &P : F.second)
3248         for (auto &L : P.second)
3249           Action(D.first, F.first, P.first(), L.first, L.second);
3250 }
3251 
3252 /// \brief Create a Ctor/Dtor-like function whose body is emitted through
3253 /// \a Codegen. This is used to emit the two functions that register and
3254 /// unregister the descriptor of the current compilation unit.
3255 static llvm::Function *
3256 createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3257                                          const RegionCodeGenTy &Codegen) {
3258   auto &C = CGM.getContext();
3259   FunctionArgList Args;
3260   ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3261   Args.push_back(&DummyPtr);
3262 
3263   CodeGenFunction CGF(CGM);
3264   auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3265   auto FTy = CGM.getTypes().GetFunctionType(FI);
3266   auto *Fn =
3267       CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3268   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3269   Codegen(CGF);
3270   CGF.FinishFunction();
3271   return Fn;
3272 }
3273 
3274 llvm::Function *
3275 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3276 
3277   // If we don't have entries or if we are emitting code for the device, we
3278   // don't need to do anything.
3279   if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3280     return nullptr;
3281 
3282   auto &M = CGM.getModule();
3283   auto &C = CGM.getContext();
3284 
3285   // Get list of devices we care about
3286   auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3287 
3288   // We should be creating an offloading descriptor only if there are devices
3289   // specified.
3290   assert(!Devices.empty() && "No OpenMP offloading devices??");
3291 
3292   // Create the external variables that will point to the begin and end of the
3293   // host entries section. These will be defined by the linker.
3294   auto *OffloadEntryTy =
3295       CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3296   llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3297       M, OffloadEntryTy, /*isConstant=*/true,
3298       llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3299       ".omp_offloading.entries_begin");
3300   llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3301       M, OffloadEntryTy, /*isConstant=*/true,
3302       llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3303       ".omp_offloading.entries_end");
3304 
3305   // Create all device images
3306   auto *DeviceImageTy = cast<llvm::StructType>(
3307       CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
3308   ConstantInitBuilder DeviceImagesBuilder(CGM);
3309   auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
3310 
3311   for (unsigned i = 0; i < Devices.size(); ++i) {
3312     StringRef T = Devices[i].getTriple();
3313     auto *ImgBegin = new llvm::GlobalVariable(
3314         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3315         /*Initializer=*/nullptr,
3316         Twine(".omp_offloading.img_start.") + Twine(T));
3317     auto *ImgEnd = new llvm::GlobalVariable(
3318         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3319         /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
3320 
3321     auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3322     Dev.add(ImgBegin);
3323     Dev.add(ImgEnd);
3324     Dev.add(HostEntriesBegin);
3325     Dev.add(HostEntriesEnd);
3326     Dev.finishAndAddTo(DeviceImagesEntries);
3327   }
3328 
3329   // Create device images global array.
3330   llvm::GlobalVariable *DeviceImages =
3331     DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3332                                               CGM.getPointerAlign(),
3333                                               /*isConstant=*/true);
3334   DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3335 
3336   // This is a Zero array to be used in the creation of the constant expressions
3337   llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3338                              llvm::Constant::getNullValue(CGM.Int32Ty)};
3339 
3340   // Create the target region descriptor.
3341   auto *BinaryDescriptorTy = cast<llvm::StructType>(
3342       CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
3343   ConstantInitBuilder DescBuilder(CGM);
3344   auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3345   DescInit.addInt(CGM.Int32Ty, Devices.size());
3346   DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3347                                                     DeviceImages,
3348                                                     Index));
3349   DescInit.add(HostEntriesBegin);
3350   DescInit.add(HostEntriesEnd);
3351 
3352   auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3353                                               CGM.getPointerAlign(),
3354                                               /*isConstant=*/true);
3355 
3356   // Emit code to register or unregister the descriptor at execution
3357   // startup or closing, respectively.
3358 
3359   // Create a variable to drive the registration and unregistration of the
3360   // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3361   auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3362   ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
3363                                 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
3364 
3365   auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
3366       CGM, ".omp_offloading.descriptor_unreg",
3367       [&](CodeGenFunction &CGF, PrePostActionTy &) {
3368         CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3369                             Desc);
3370       });
3371   auto *RegFn = createOffloadingBinaryDescriptorFunction(
3372       CGM, ".omp_offloading.descriptor_reg",
3373       [&](CodeGenFunction &CGF, PrePostActionTy &) {
3374         CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3375                             Desc);
3376         CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3377       });
3378   if (CGM.supportsCOMDAT()) {
3379     // It is sufficient to call registration function only once, so create a
3380     // COMDAT group for registration/unregistration functions and associated
3381     // data. That would reduce startup time and code size. Registration
3382     // function serves as a COMDAT group key.
3383     auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3384     RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3385     RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3386     RegFn->setComdat(ComdatKey);
3387     UnRegFn->setComdat(ComdatKey);
3388     DeviceImages->setComdat(ComdatKey);
3389     Desc->setComdat(ComdatKey);
3390   }
3391   return RegFn;
3392 }
3393 
3394 void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
3395                                          llvm::Constant *Addr, uint64_t Size,
3396                                          int32_t Flags) {
3397   StringRef Name = Addr->getName();
3398   auto *TgtOffloadEntryType = cast<llvm::StructType>(
3399       CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3400   llvm::LLVMContext &C = CGM.getModule().getContext();
3401   llvm::Module &M = CGM.getModule();
3402 
3403   // Make sure the address has the right type.
3404   llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
3405 
3406   // Create constant string with the name.
3407   llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3408 
3409   llvm::GlobalVariable *Str =
3410       new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3411                                llvm::GlobalValue::InternalLinkage, StrPtrInit,
3412                                ".omp_offloading.entry_name");
3413   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3414   llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3415 
3416   // We can't have any padding between symbols, so we need to have 1-byte
3417   // alignment.
3418   auto Align = CharUnits::fromQuantity(1);
3419 
3420   // Create the entry struct.
3421   ConstantInitBuilder EntryBuilder(CGM);
3422   auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3423   EntryInit.add(AddrPtr);
3424   EntryInit.add(StrPtr);
3425   EntryInit.addInt(CGM.SizeTy, Size);
3426   EntryInit.addInt(CGM.Int32Ty, Flags);
3427   EntryInit.addInt(CGM.Int32Ty, 0);
3428   llvm::GlobalVariable *Entry =
3429     EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3430                                     Align,
3431                                     /*constant*/ true,
3432                                     llvm::GlobalValue::ExternalLinkage);
3433 
3434   // The entry has to be created in the section the linker expects it to be.
3435   Entry->setSection(".omp_offloading.entries");
3436 }
3437 
3438 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3439   // Emit the offloading entries and metadata so that the device codegen side
3440   // can easily figure out what to emit. The produced metadata looks like
3441   // this:
3442   //
3443   // !omp_offload.info = !{!1, ...}
3444   //
3445   // Right now we only generate metadata for function that contain target
3446   // regions.
3447 
3448   // If we do not have entries, we dont need to do anything.
3449   if (OffloadEntriesInfoManager.empty())
3450     return;
3451 
3452   llvm::Module &M = CGM.getModule();
3453   llvm::LLVMContext &C = M.getContext();
3454   SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3455       OrderedEntries(OffloadEntriesInfoManager.size());
3456 
3457   // Create the offloading info metadata node.
3458   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3459 
3460   // Auxiliary methods to create metadata values and strings.
3461   auto getMDInt = [&](unsigned v) {
3462     return llvm::ConstantAsMetadata::get(
3463         llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3464   };
3465 
3466   auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3467 
3468   // Create function that emits metadata for each target region entry;
3469   auto &&TargetRegionMetadataEmitter = [&](
3470       unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
3471       OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3472     llvm::SmallVector<llvm::Metadata *, 32> Ops;
3473     // Generate metadata for target regions. Each entry of this metadata
3474     // contains:
3475     // - Entry 0 -> Kind of this type of metadata (0).
3476     // - Entry 1 -> Device ID of the file where the entry was identified.
3477     // - Entry 2 -> File ID of the file where the entry was identified.
3478     // - Entry 3 -> Mangled name of the function where the entry was identified.
3479     // - Entry 4 -> Line in the file where the entry was identified.
3480     // - Entry 5 -> Order the entry was created.
3481     // The first element of the metadata node is the kind.
3482     Ops.push_back(getMDInt(E.getKind()));
3483     Ops.push_back(getMDInt(DeviceID));
3484     Ops.push_back(getMDInt(FileID));
3485     Ops.push_back(getMDString(ParentName));
3486     Ops.push_back(getMDInt(Line));
3487     Ops.push_back(getMDInt(E.getOrder()));
3488 
3489     // Save this entry in the right position of the ordered entries array.
3490     OrderedEntries[E.getOrder()] = &E;
3491 
3492     // Add metadata to the named metadata node.
3493     MD->addOperand(llvm::MDNode::get(C, Ops));
3494   };
3495 
3496   OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3497       TargetRegionMetadataEmitter);
3498 
3499   for (auto *E : OrderedEntries) {
3500     assert(E && "All ordered entries must exist!");
3501     if (auto *CE =
3502             dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3503                 E)) {
3504       assert(CE->getID() && CE->getAddress() &&
3505              "Entry ID and Addr are invalid!");
3506       createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
3507     } else
3508       llvm_unreachable("Unsupported entry kind.");
3509   }
3510 }
3511 
3512 /// \brief Loads all the offload entries information from the host IR
3513 /// metadata.
3514 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3515   // If we are in target mode, load the metadata from the host IR. This code has
3516   // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3517 
3518   if (!CGM.getLangOpts().OpenMPIsDevice)
3519     return;
3520 
3521   if (CGM.getLangOpts().OMPHostIRFile.empty())
3522     return;
3523 
3524   auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3525   if (Buf.getError())
3526     return;
3527 
3528   llvm::LLVMContext C;
3529   auto ME = expectedToErrorOrAndEmitErrors(
3530       C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3531 
3532   if (ME.getError())
3533     return;
3534 
3535   llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3536   if (!MD)
3537     return;
3538 
3539   for (auto I : MD->operands()) {
3540     llvm::MDNode *MN = cast<llvm::MDNode>(I);
3541 
3542     auto getMDInt = [&](unsigned Idx) {
3543       llvm::ConstantAsMetadata *V =
3544           cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3545       return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3546     };
3547 
3548     auto getMDString = [&](unsigned Idx) {
3549       llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3550       return V->getString();
3551     };
3552 
3553     switch (getMDInt(0)) {
3554     default:
3555       llvm_unreachable("Unexpected metadata!");
3556       break;
3557     case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3558         OFFLOAD_ENTRY_INFO_TARGET_REGION:
3559       OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3560           /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3561           /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
3562           /*Order=*/getMDInt(5));
3563       break;
3564     }
3565   }
3566 }
3567 
3568 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3569   if (!KmpRoutineEntryPtrTy) {
3570     // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3571     auto &C = CGM.getContext();
3572     QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3573     FunctionProtoType::ExtProtoInfo EPI;
3574     KmpRoutineEntryPtrQTy = C.getPointerType(
3575         C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3576     KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3577   }
3578 }
3579 
3580 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3581                                        QualType FieldTy) {
3582   auto *Field = FieldDecl::Create(
3583       C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3584       C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3585       /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3586   Field->setAccess(AS_public);
3587   DC->addDecl(Field);
3588   return Field;
3589 }
3590 
3591 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3592 
3593   // Make sure the type of the entry is already created. This is the type we
3594   // have to create:
3595   // struct __tgt_offload_entry{
3596   //   void      *addr;       // Pointer to the offload entry info.
3597   //                          // (function or global)
3598   //   char      *name;       // Name of the function or global.
3599   //   size_t     size;       // Size of the entry info (0 if it a function).
3600   //   int32_t    flags;      // Flags associated with the entry, e.g. 'link'.
3601   //   int32_t    reserved;   // Reserved, to use by the runtime library.
3602   // };
3603   if (TgtOffloadEntryQTy.isNull()) {
3604     ASTContext &C = CGM.getContext();
3605     auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3606     RD->startDefinition();
3607     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3608     addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3609     addFieldToRecordDecl(C, RD, C.getSizeType());
3610     addFieldToRecordDecl(
3611         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3612     addFieldToRecordDecl(
3613         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3614     RD->completeDefinition();
3615     TgtOffloadEntryQTy = C.getRecordType(RD);
3616   }
3617   return TgtOffloadEntryQTy;
3618 }
3619 
3620 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3621   // These are the types we need to build:
3622   // struct __tgt_device_image{
3623   // void   *ImageStart;       // Pointer to the target code start.
3624   // void   *ImageEnd;         // Pointer to the target code end.
3625   // // We also add the host entries to the device image, as it may be useful
3626   // // for the target runtime to have access to that information.
3627   // __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all
3628   //                                       // the entries.
3629   // __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
3630   //                                       // entries (non inclusive).
3631   // };
3632   if (TgtDeviceImageQTy.isNull()) {
3633     ASTContext &C = CGM.getContext();
3634     auto *RD = C.buildImplicitRecord("__tgt_device_image");
3635     RD->startDefinition();
3636     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3637     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3638     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3639     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3640     RD->completeDefinition();
3641     TgtDeviceImageQTy = C.getRecordType(RD);
3642   }
3643   return TgtDeviceImageQTy;
3644 }
3645 
3646 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3647   // struct __tgt_bin_desc{
3648   //   int32_t              NumDevices;      // Number of devices supported.
3649   //   __tgt_device_image   *DeviceImages;   // Arrays of device images
3650   //                                         // (one per device).
3651   //   __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all the
3652   //                                         // entries.
3653   //   __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
3654   //                                         // entries (non inclusive).
3655   // };
3656   if (TgtBinaryDescriptorQTy.isNull()) {
3657     ASTContext &C = CGM.getContext();
3658     auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3659     RD->startDefinition();
3660     addFieldToRecordDecl(
3661         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3662     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3663     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3664     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3665     RD->completeDefinition();
3666     TgtBinaryDescriptorQTy = C.getRecordType(RD);
3667   }
3668   return TgtBinaryDescriptorQTy;
3669 }
3670 
3671 namespace {
3672 struct PrivateHelpersTy {
3673   PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3674                    const VarDecl *PrivateElemInit)
3675       : Original(Original), PrivateCopy(PrivateCopy),
3676         PrivateElemInit(PrivateElemInit) {}
3677   const VarDecl *Original;
3678   const VarDecl *PrivateCopy;
3679   const VarDecl *PrivateElemInit;
3680 };
3681 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3682 } // anonymous namespace
3683 
3684 static RecordDecl *
3685 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3686   if (!Privates.empty()) {
3687     auto &C = CGM.getContext();
3688     // Build struct .kmp_privates_t. {
3689     //         /*  private vars  */
3690     //       };
3691     auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3692     RD->startDefinition();
3693     for (auto &&Pair : Privates) {
3694       auto *VD = Pair.second.Original;
3695       auto Type = VD->getType();
3696       Type = Type.getNonReferenceType();
3697       auto *FD = addFieldToRecordDecl(C, RD, Type);
3698       if (VD->hasAttrs()) {
3699         for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3700              E(VD->getAttrs().end());
3701              I != E; ++I)
3702           FD->addAttr(*I);
3703       }
3704     }
3705     RD->completeDefinition();
3706     return RD;
3707   }
3708   return nullptr;
3709 }
3710 
3711 static RecordDecl *
3712 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3713                          QualType KmpInt32Ty,
3714                          QualType KmpRoutineEntryPointerQTy) {
3715   auto &C = CGM.getContext();
3716   // Build struct kmp_task_t {
3717   //         void *              shareds;
3718   //         kmp_routine_entry_t routine;
3719   //         kmp_int32           part_id;
3720   //         kmp_cmplrdata_t data1;
3721   //         kmp_cmplrdata_t data2;
3722   // For taskloops additional fields:
3723   //         kmp_uint64          lb;
3724   //         kmp_uint64          ub;
3725   //         kmp_int64           st;
3726   //         kmp_int32           liter;
3727   //         void *              reductions;
3728   //       };
3729   auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3730   UD->startDefinition();
3731   addFieldToRecordDecl(C, UD, KmpInt32Ty);
3732   addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3733   UD->completeDefinition();
3734   QualType KmpCmplrdataTy = C.getRecordType(UD);
3735   auto *RD = C.buildImplicitRecord("kmp_task_t");
3736   RD->startDefinition();
3737   addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3738   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3739   addFieldToRecordDecl(C, RD, KmpInt32Ty);
3740   addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3741   addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3742   if (isOpenMPTaskLoopDirective(Kind)) {
3743     QualType KmpUInt64Ty =
3744         CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3745     QualType KmpInt64Ty =
3746         CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3747     addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3748     addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3749     addFieldToRecordDecl(C, RD, KmpInt64Ty);
3750     addFieldToRecordDecl(C, RD, KmpInt32Ty);
3751     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3752   }
3753   RD->completeDefinition();
3754   return RD;
3755 }
3756 
3757 static RecordDecl *
3758 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3759                                      ArrayRef<PrivateDataTy> Privates) {
3760   auto &C = CGM.getContext();
3761   // Build struct kmp_task_t_with_privates {
3762   //         kmp_task_t task_data;
3763   //         .kmp_privates_t. privates;
3764   //       };
3765   auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3766   RD->startDefinition();
3767   addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3768   if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3769     addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3770   }
3771   RD->completeDefinition();
3772   return RD;
3773 }
3774 
3775 /// \brief Emit a proxy function which accepts kmp_task_t as the second
3776 /// argument.
3777 /// \code
3778 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3779 ///   TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3780 ///   For taskloops:
3781 ///   tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3782 ///   tt->reductions, tt->shareds);
3783 ///   return 0;
3784 /// }
3785 /// \endcode
3786 static llvm::Value *
3787 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3788                       OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3789                       QualType KmpTaskTWithPrivatesPtrQTy,
3790                       QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3791                       QualType SharedsPtrTy, llvm::Value *TaskFunction,
3792                       llvm::Value *TaskPrivatesMap) {
3793   auto &C = CGM.getContext();
3794   FunctionArgList Args;
3795   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3796                             ImplicitParamDecl::Other);
3797   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3798                                 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3799                                 ImplicitParamDecl::Other);
3800   Args.push_back(&GtidArg);
3801   Args.push_back(&TaskTypeArg);
3802   auto &TaskEntryFnInfo =
3803       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3804   auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3805   auto *TaskEntry =
3806       llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3807                              ".omp_task_entry.", &CGM.getModule());
3808   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
3809   CodeGenFunction CGF(CGM);
3810   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3811 
3812   // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3813   // tt,
3814   // For taskloops:
3815   // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3816   // tt->task_data.shareds);
3817   auto *GtidParam = CGF.EmitLoadOfScalar(
3818       CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3819   LValue TDBase = CGF.EmitLoadOfPointerLValue(
3820       CGF.GetAddrOfLocalVar(&TaskTypeArg),
3821       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3822   auto *KmpTaskTWithPrivatesQTyRD =
3823       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3824   LValue Base =
3825       CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3826   auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3827   auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3828   auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3829   auto *PartidParam = PartIdLVal.getPointer();
3830 
3831   auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3832   auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3833   auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3834       CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
3835       CGF.ConvertTypeForMem(SharedsPtrTy));
3836 
3837   auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3838   llvm::Value *PrivatesParam;
3839   if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3840     auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3841     PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3842         PrivatesLVal.getPointer(), CGF.VoidPtrTy);
3843   } else
3844     PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3845 
3846   llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3847                                TaskPrivatesMap,
3848                                CGF.Builder
3849                                    .CreatePointerBitCastOrAddrSpaceCast(
3850                                        TDBase.getAddress(), CGF.VoidPtrTy)
3851                                    .getPointer()};
3852   SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3853                                           std::end(CommonArgs));
3854   if (isOpenMPTaskLoopDirective(Kind)) {
3855     auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3856     auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3857     auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3858     auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3859     auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3860     auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3861     auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3862     auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3863     auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3864     auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3865     auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3866     auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3867     auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3868     auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3869     auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
3870     CallArgs.push_back(LBParam);
3871     CallArgs.push_back(UBParam);
3872     CallArgs.push_back(StParam);
3873     CallArgs.push_back(LIParam);
3874     CallArgs.push_back(RParam);
3875   }
3876   CallArgs.push_back(SharedsParam);
3877 
3878   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3879                                                   CallArgs);
3880   CGF.EmitStoreThroughLValue(
3881       RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3882       CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3883   CGF.FinishFunction();
3884   return TaskEntry;
3885 }
3886 
3887 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3888                                             SourceLocation Loc,
3889                                             QualType KmpInt32Ty,
3890                                             QualType KmpTaskTWithPrivatesPtrQTy,
3891                                             QualType KmpTaskTWithPrivatesQTy) {
3892   auto &C = CGM.getContext();
3893   FunctionArgList Args;
3894   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3895                             ImplicitParamDecl::Other);
3896   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3897                                 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3898                                 ImplicitParamDecl::Other);
3899   Args.push_back(&GtidArg);
3900   Args.push_back(&TaskTypeArg);
3901   FunctionType::ExtInfo Info;
3902   auto &DestructorFnInfo =
3903       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3904   auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3905   auto *DestructorFn =
3906       llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3907                              ".omp_task_destructor.", &CGM.getModule());
3908   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3909                                     DestructorFnInfo);
3910   CodeGenFunction CGF(CGM);
3911   CGF.disableDebugInfo();
3912   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3913                     Args);
3914 
3915   LValue Base = CGF.EmitLoadOfPointerLValue(
3916       CGF.GetAddrOfLocalVar(&TaskTypeArg),
3917       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3918   auto *KmpTaskTWithPrivatesQTyRD =
3919       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3920   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3921   Base = CGF.EmitLValueForField(Base, *FI);
3922   for (auto *Field :
3923        cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3924     if (auto DtorKind = Field->getType().isDestructedType()) {
3925       auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3926       CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3927     }
3928   }
3929   CGF.FinishFunction();
3930   return DestructorFn;
3931 }
3932 
3933 /// \brief Emit a privates mapping function for correct handling of private and
3934 /// firstprivate variables.
3935 /// \code
3936 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3937 /// **noalias priv1,...,  <tyn> **noalias privn) {
3938 ///   *priv1 = &.privates.priv1;
3939 ///   ...;
3940 ///   *privn = &.privates.privn;
3941 /// }
3942 /// \endcode
3943 static llvm::Value *
3944 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3945                                ArrayRef<const Expr *> PrivateVars,
3946                                ArrayRef<const Expr *> FirstprivateVars,
3947                                ArrayRef<const Expr *> LastprivateVars,
3948                                QualType PrivatesQTy,
3949                                ArrayRef<PrivateDataTy> Privates) {
3950   auto &C = CGM.getContext();
3951   FunctionArgList Args;
3952   ImplicitParamDecl TaskPrivatesArg(
3953       C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3954       C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3955       ImplicitParamDecl::Other);
3956   Args.push_back(&TaskPrivatesArg);
3957   llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3958   unsigned Counter = 1;
3959   for (auto *E: PrivateVars) {
3960     Args.push_back(ImplicitParamDecl::Create(
3961         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3962         C.getPointerType(C.getPointerType(E->getType()))
3963             .withConst()
3964             .withRestrict(),
3965         ImplicitParamDecl::Other));
3966     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3967     PrivateVarsPos[VD] = Counter;
3968     ++Counter;
3969   }
3970   for (auto *E : FirstprivateVars) {
3971     Args.push_back(ImplicitParamDecl::Create(
3972         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3973         C.getPointerType(C.getPointerType(E->getType()))
3974             .withConst()
3975             .withRestrict(),
3976         ImplicitParamDecl::Other));
3977     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3978     PrivateVarsPos[VD] = Counter;
3979     ++Counter;
3980   }
3981   for (auto *E: LastprivateVars) {
3982     Args.push_back(ImplicitParamDecl::Create(
3983         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3984         C.getPointerType(C.getPointerType(E->getType()))
3985             .withConst()
3986             .withRestrict(),
3987         ImplicitParamDecl::Other));
3988     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3989     PrivateVarsPos[VD] = Counter;
3990     ++Counter;
3991   }
3992   auto &TaskPrivatesMapFnInfo =
3993       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3994   auto *TaskPrivatesMapTy =
3995       CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3996   auto *TaskPrivatesMap = llvm::Function::Create(
3997       TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3998       ".omp_task_privates_map.", &CGM.getModule());
3999   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4000                                     TaskPrivatesMapFnInfo);
4001   TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
4002   TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
4003   TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
4004   CodeGenFunction CGF(CGM);
4005   CGF.disableDebugInfo();
4006   CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4007                     TaskPrivatesMapFnInfo, Args);
4008 
4009   // *privi = &.privates.privi;
4010   LValue Base = CGF.EmitLoadOfPointerLValue(
4011       CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4012       TaskPrivatesArg.getType()->castAs<PointerType>());
4013   auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4014   Counter = 0;
4015   for (auto *Field : PrivatesQTyRD->fields()) {
4016     auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4017     auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4018     auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4019     auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4020         RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
4021     CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
4022     ++Counter;
4023   }
4024   CGF.FinishFunction();
4025   return TaskPrivatesMap;
4026 }
4027 
4028 static int array_pod_sort_comparator(const PrivateDataTy *P1,
4029                                      const PrivateDataTy *P2) {
4030   return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4031 }
4032 
4033 /// Emit initialization for private variables in task-based directives.
4034 static void emitPrivatesInit(CodeGenFunction &CGF,
4035                              const OMPExecutableDirective &D,
4036                              Address KmpTaskSharedsPtr, LValue TDBase,
4037                              const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4038                              QualType SharedsTy, QualType SharedsPtrTy,
4039                              const OMPTaskDataTy &Data,
4040                              ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4041   auto &C = CGF.getContext();
4042   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4043   LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4044   LValue SrcBase;
4045   if (!Data.FirstprivateVars.empty()) {
4046     SrcBase = CGF.MakeAddrLValue(
4047         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4048             KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4049         SharedsTy);
4050   }
4051   CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4052       cast<CapturedStmt>(*D.getAssociatedStmt()));
4053   FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4054   for (auto &&Pair : Privates) {
4055     auto *VD = Pair.second.PrivateCopy;
4056     auto *Init = VD->getAnyInitializer();
4057     if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4058                              !CGF.isTrivialInitializer(Init)))) {
4059       LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
4060       if (auto *Elem = Pair.second.PrivateElemInit) {
4061         auto *OriginalVD = Pair.second.Original;
4062         auto *SharedField = CapturesInfo.lookup(OriginalVD);
4063         auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4064         SharedRefLValue = CGF.MakeAddrLValue(
4065             Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4066             SharedRefLValue.getType(),
4067             LValueBaseInfo(AlignmentSource::Decl,
4068                            SharedRefLValue.getBaseInfo().getMayAlias()));
4069         QualType Type = OriginalVD->getType();
4070         if (Type->isArrayType()) {
4071           // Initialize firstprivate array.
4072           if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4073             // Perform simple memcpy.
4074             CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4075                                     SharedRefLValue.getAddress(), Type);
4076           } else {
4077             // Initialize firstprivate array using element-by-element
4078             // initialization.
4079             CGF.EmitOMPAggregateAssign(
4080                 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4081                 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4082                                                   Address SrcElement) {
4083                   // Clean up any temporaries needed by the initialization.
4084                   CodeGenFunction::OMPPrivateScope InitScope(CGF);
4085                   InitScope.addPrivate(
4086                       Elem, [SrcElement]() -> Address { return SrcElement; });
4087                   (void)InitScope.Privatize();
4088                   // Emit initialization for single element.
4089                   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4090                       CGF, &CapturesInfo);
4091                   CGF.EmitAnyExprToMem(Init, DestElement,
4092                                        Init->getType().getQualifiers(),
4093                                        /*IsInitializer=*/false);
4094                 });
4095           }
4096         } else {
4097           CodeGenFunction::OMPPrivateScope InitScope(CGF);
4098           InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4099             return SharedRefLValue.getAddress();
4100           });
4101           (void)InitScope.Privatize();
4102           CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4103           CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4104                              /*capturedByInit=*/false);
4105         }
4106       } else
4107         CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4108     }
4109     ++FI;
4110   }
4111 }
4112 
4113 /// Check if duplication function is required for taskloops.
4114 static bool checkInitIsRequired(CodeGenFunction &CGF,
4115                                 ArrayRef<PrivateDataTy> Privates) {
4116   bool InitRequired = false;
4117   for (auto &&Pair : Privates) {
4118     auto *VD = Pair.second.PrivateCopy;
4119     auto *Init = VD->getAnyInitializer();
4120     InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4121                                     !CGF.isTrivialInitializer(Init));
4122   }
4123   return InitRequired;
4124 }
4125 
4126 
4127 /// Emit task_dup function (for initialization of
4128 /// private/firstprivate/lastprivate vars and last_iter flag)
4129 /// \code
4130 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4131 /// lastpriv) {
4132 /// // setup lastprivate flag
4133 ///    task_dst->last = lastpriv;
4134 /// // could be constructor calls here...
4135 /// }
4136 /// \endcode
4137 static llvm::Value *
4138 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4139                     const OMPExecutableDirective &D,
4140                     QualType KmpTaskTWithPrivatesPtrQTy,
4141                     const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4142                     const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4143                     QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4144                     ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4145   auto &C = CGM.getContext();
4146   FunctionArgList Args;
4147   ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4148                            KmpTaskTWithPrivatesPtrQTy,
4149                            ImplicitParamDecl::Other);
4150   ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4151                            KmpTaskTWithPrivatesPtrQTy,
4152                            ImplicitParamDecl::Other);
4153   ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4154                                 ImplicitParamDecl::Other);
4155   Args.push_back(&DstArg);
4156   Args.push_back(&SrcArg);
4157   Args.push_back(&LastprivArg);
4158   auto &TaskDupFnInfo =
4159       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4160   auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4161   auto *TaskDup =
4162       llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4163                              ".omp_task_dup.", &CGM.getModule());
4164   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4165   CodeGenFunction CGF(CGM);
4166   CGF.disableDebugInfo();
4167   CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4168 
4169   LValue TDBase = CGF.EmitLoadOfPointerLValue(
4170       CGF.GetAddrOfLocalVar(&DstArg),
4171       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4172   // task_dst->liter = lastpriv;
4173   if (WithLastIter) {
4174     auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4175     LValue Base = CGF.EmitLValueForField(
4176         TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4177     LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4178     llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4179         CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4180     CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4181   }
4182 
4183   // Emit initial values for private copies (if any).
4184   assert(!Privates.empty());
4185   Address KmpTaskSharedsPtr = Address::invalid();
4186   if (!Data.FirstprivateVars.empty()) {
4187     LValue TDBase = CGF.EmitLoadOfPointerLValue(
4188         CGF.GetAddrOfLocalVar(&SrcArg),
4189         KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4190     LValue Base = CGF.EmitLValueForField(
4191         TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4192     KmpTaskSharedsPtr = Address(
4193         CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4194                                  Base, *std::next(KmpTaskTQTyRD->field_begin(),
4195                                                   KmpTaskTShareds)),
4196                              Loc),
4197         CGF.getNaturalTypeAlignment(SharedsTy));
4198   }
4199   emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4200                    SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
4201   CGF.FinishFunction();
4202   return TaskDup;
4203 }
4204 
4205 /// Checks if destructor function is required to be generated.
4206 /// \return true if cleanups are required, false otherwise.
4207 static bool
4208 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4209   bool NeedsCleanup = false;
4210   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4211   auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4212   for (auto *FD : PrivateRD->fields()) {
4213     NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4214     if (NeedsCleanup)
4215       break;
4216   }
4217   return NeedsCleanup;
4218 }
4219 
4220 CGOpenMPRuntime::TaskResultTy
4221 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4222                               const OMPExecutableDirective &D,
4223                               llvm::Value *TaskFunction, QualType SharedsTy,
4224                               Address Shareds, const OMPTaskDataTy &Data) {
4225   auto &C = CGM.getContext();
4226   llvm::SmallVector<PrivateDataTy, 4> Privates;
4227   // Aggregate privates and sort them by the alignment.
4228   auto I = Data.PrivateCopies.begin();
4229   for (auto *E : Data.PrivateVars) {
4230     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4231     Privates.push_back(std::make_pair(
4232         C.getDeclAlign(VD),
4233         PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4234                          /*PrivateElemInit=*/nullptr)));
4235     ++I;
4236   }
4237   I = Data.FirstprivateCopies.begin();
4238   auto IElemInitRef = Data.FirstprivateInits.begin();
4239   for (auto *E : Data.FirstprivateVars) {
4240     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4241     Privates.push_back(std::make_pair(
4242         C.getDeclAlign(VD),
4243         PrivateHelpersTy(
4244             VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4245             cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
4246     ++I;
4247     ++IElemInitRef;
4248   }
4249   I = Data.LastprivateCopies.begin();
4250   for (auto *E : Data.LastprivateVars) {
4251     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4252     Privates.push_back(std::make_pair(
4253         C.getDeclAlign(VD),
4254         PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4255                          /*PrivateElemInit=*/nullptr)));
4256     ++I;
4257   }
4258   llvm::array_pod_sort(Privates.begin(), Privates.end(),
4259                        array_pod_sort_comparator);
4260   auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4261   // Build type kmp_routine_entry_t (if not built yet).
4262   emitKmpRoutineEntryT(KmpInt32Ty);
4263   // Build type kmp_task_t (if not built yet).
4264   if (KmpTaskTQTy.isNull()) {
4265     KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4266         CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4267   }
4268   auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4269   // Build particular struct kmp_task_t for the given task.
4270   auto *KmpTaskTWithPrivatesQTyRD =
4271       createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4272   auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4273   QualType KmpTaskTWithPrivatesPtrQTy =
4274       C.getPointerType(KmpTaskTWithPrivatesQTy);
4275   auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4276   auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
4277   auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
4278   QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4279 
4280   // Emit initial values for private copies (if any).
4281   llvm::Value *TaskPrivatesMap = nullptr;
4282   auto *TaskPrivatesMapTy =
4283       std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
4284   if (!Privates.empty()) {
4285     auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4286     TaskPrivatesMap = emitTaskPrivateMappingFunction(
4287         CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4288         FI->getType(), Privates);
4289     TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4290         TaskPrivatesMap, TaskPrivatesMapTy);
4291   } else {
4292     TaskPrivatesMap = llvm::ConstantPointerNull::get(
4293         cast<llvm::PointerType>(TaskPrivatesMapTy));
4294   }
4295   // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4296   // kmp_task_t *tt);
4297   auto *TaskEntry = emitProxyTaskFunction(
4298       CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4299       KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4300       TaskPrivatesMap);
4301 
4302   // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4303   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4304   // kmp_routine_entry_t *task_entry);
4305   // Task flags. Format is taken from
4306   // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4307   // description of kmp_tasking_flags struct.
4308   enum {
4309     TiedFlag = 0x1,
4310     FinalFlag = 0x2,
4311     DestructorsFlag = 0x8,
4312     PriorityFlag = 0x20
4313   };
4314   unsigned Flags = Data.Tied ? TiedFlag : 0;
4315   bool NeedsCleanup = false;
4316   if (!Privates.empty()) {
4317     NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4318     if (NeedsCleanup)
4319       Flags = Flags | DestructorsFlag;
4320   }
4321   if (Data.Priority.getInt())
4322     Flags = Flags | PriorityFlag;
4323   auto *TaskFlags =
4324       Data.Final.getPointer()
4325           ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
4326                                      CGF.Builder.getInt32(FinalFlag),
4327                                      CGF.Builder.getInt32(/*C=*/0))
4328           : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
4329   TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
4330   auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
4331   llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4332                               getThreadID(CGF, Loc), TaskFlags,
4333                               KmpTaskTWithPrivatesTySize, SharedsSize,
4334                               CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4335                                   TaskEntry, KmpRoutineEntryPtrTy)};
4336   auto *NewTask = CGF.EmitRuntimeCall(
4337       createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
4338   auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4339       NewTask, KmpTaskTWithPrivatesPtrTy);
4340   LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4341                                                KmpTaskTWithPrivatesQTy);
4342   LValue TDBase =
4343       CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4344   // Fill the data in the resulting kmp_task_t record.
4345   // Copy shareds if there are any.
4346   Address KmpTaskSharedsPtr = Address::invalid();
4347   if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
4348     KmpTaskSharedsPtr =
4349         Address(CGF.EmitLoadOfScalar(
4350                     CGF.EmitLValueForField(
4351                         TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4352                                            KmpTaskTShareds)),
4353                     Loc),
4354                 CGF.getNaturalTypeAlignment(SharedsTy));
4355     CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
4356   }
4357   // Emit initial values for private copies (if any).
4358   TaskResultTy Result;
4359   if (!Privates.empty()) {
4360     emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4361                      SharedsTy, SharedsPtrTy, Data, Privates,
4362                      /*ForDup=*/false);
4363     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4364         (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4365       Result.TaskDupFn = emitTaskDupFunction(
4366           CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4367           KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4368           /*WithLastIter=*/!Data.LastprivateVars.empty());
4369     }
4370   }
4371   // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4372   enum { Priority = 0, Destructors = 1 };
4373   // Provide pointer to function with destructors for privates.
4374   auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4375   auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4376   if (NeedsCleanup) {
4377     llvm::Value *DestructorFn = emitDestructorsFunction(
4378         CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4379         KmpTaskTWithPrivatesQTy);
4380     LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4381     LValue DestructorsLV = CGF.EmitLValueForField(
4382         Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4383     CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4384                               DestructorFn, KmpRoutineEntryPtrTy),
4385                           DestructorsLV);
4386   }
4387   // Set priority.
4388   if (Data.Priority.getInt()) {
4389     LValue Data2LV = CGF.EmitLValueForField(
4390         TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4391     LValue PriorityLV = CGF.EmitLValueForField(
4392         Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4393     CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4394   }
4395   Result.NewTask = NewTask;
4396   Result.TaskEntry = TaskEntry;
4397   Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4398   Result.TDBase = TDBase;
4399   Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4400   return Result;
4401 }
4402 
4403 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4404                                    const OMPExecutableDirective &D,
4405                                    llvm::Value *TaskFunction,
4406                                    QualType SharedsTy, Address Shareds,
4407                                    const Expr *IfCond,
4408                                    const OMPTaskDataTy &Data) {
4409   if (!CGF.HaveInsertPoint())
4410     return;
4411 
4412   TaskResultTy Result =
4413       emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4414   llvm::Value *NewTask = Result.NewTask;
4415   llvm::Value *TaskEntry = Result.TaskEntry;
4416   llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4417   LValue TDBase = Result.TDBase;
4418   RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4419   auto &C = CGM.getContext();
4420   // Process list of dependences.
4421   Address DependenciesArray = Address::invalid();
4422   unsigned NumDependencies = Data.Dependences.size();
4423   if (NumDependencies) {
4424     // Dependence kind for RTL.
4425     enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
4426     enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4427     RecordDecl *KmpDependInfoRD;
4428     QualType FlagsTy =
4429         C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4430     llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4431     if (KmpDependInfoTy.isNull()) {
4432       KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4433       KmpDependInfoRD->startDefinition();
4434       addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4435       addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4436       addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4437       KmpDependInfoRD->completeDefinition();
4438       KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
4439     } else
4440       KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4441     CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
4442     // Define type kmp_depend_info[<Dependences.size()>];
4443     QualType KmpDependInfoArrayTy = C.getConstantArrayType(
4444         KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
4445         ArrayType::Normal, /*IndexTypeQuals=*/0);
4446     // kmp_depend_info[<Dependences.size()>] deps;
4447     DependenciesArray =
4448         CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4449     for (unsigned i = 0; i < NumDependencies; ++i) {
4450       const Expr *E = Data.Dependences[i].second;
4451       auto Addr = CGF.EmitLValue(E);
4452       llvm::Value *Size;
4453       QualType Ty = E->getType();
4454       if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4455         LValue UpAddrLVal =
4456             CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4457         llvm::Value *UpAddr =
4458             CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
4459         llvm::Value *LowIntPtr =
4460             CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
4461         llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4462         Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
4463       } else
4464         Size = CGF.getTypeSize(Ty);
4465       auto Base = CGF.MakeAddrLValue(
4466           CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
4467           KmpDependInfoTy);
4468       // deps[i].base_addr = &<Dependences[i].second>;
4469       auto BaseAddrLVal = CGF.EmitLValueForField(
4470           Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4471       CGF.EmitStoreOfScalar(
4472           CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4473           BaseAddrLVal);
4474       // deps[i].len = sizeof(<Dependences[i].second>);
4475       auto LenLVal = CGF.EmitLValueForField(
4476           Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4477       CGF.EmitStoreOfScalar(Size, LenLVal);
4478       // deps[i].flags = <Dependences[i].first>;
4479       RTLDependenceKindTy DepKind;
4480       switch (Data.Dependences[i].first) {
4481       case OMPC_DEPEND_in:
4482         DepKind = DepIn;
4483         break;
4484       // Out and InOut dependencies must use the same code.
4485       case OMPC_DEPEND_out:
4486       case OMPC_DEPEND_inout:
4487         DepKind = DepInOut;
4488         break;
4489       case OMPC_DEPEND_source:
4490       case OMPC_DEPEND_sink:
4491       case OMPC_DEPEND_unknown:
4492         llvm_unreachable("Unknown task dependence type");
4493       }
4494       auto FlagsLVal = CGF.EmitLValueForField(
4495           Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4496       CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4497                             FlagsLVal);
4498     }
4499     DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4500         CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
4501         CGF.VoidPtrTy);
4502   }
4503 
4504   // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4505   // libcall.
4506   // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4507   // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4508   // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4509   // list is not empty
4510   auto *ThreadID = getThreadID(CGF, Loc);
4511   auto *UpLoc = emitUpdateLocation(CGF, Loc);
4512   llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4513   llvm::Value *DepTaskArgs[7];
4514   if (NumDependencies) {
4515     DepTaskArgs[0] = UpLoc;
4516     DepTaskArgs[1] = ThreadID;
4517     DepTaskArgs[2] = NewTask;
4518     DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4519     DepTaskArgs[4] = DependenciesArray.getPointer();
4520     DepTaskArgs[5] = CGF.Builder.getInt32(0);
4521     DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4522   }
4523   auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4524                         &TaskArgs,
4525                         &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
4526     if (!Data.Tied) {
4527       auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4528       auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4529       CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4530     }
4531     if (NumDependencies) {
4532       CGF.EmitRuntimeCall(
4533           createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
4534     } else {
4535       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
4536                           TaskArgs);
4537     }
4538     // Check if parent region is untied and build return for untied task;
4539     if (auto *Region =
4540             dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4541       Region->emitUntiedSwitch(CGF);
4542   };
4543 
4544   llvm::Value *DepWaitTaskArgs[6];
4545   if (NumDependencies) {
4546     DepWaitTaskArgs[0] = UpLoc;
4547     DepWaitTaskArgs[1] = ThreadID;
4548     DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4549     DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4550     DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4551     DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4552   }
4553   auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4554                         NumDependencies, &DepWaitTaskArgs,
4555                         Loc](CodeGenFunction &CGF, PrePostActionTy &) {
4556     auto &RT = CGF.CGM.getOpenMPRuntime();
4557     CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4558     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4559     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4560     // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4561     // is specified.
4562     if (NumDependencies)
4563       CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
4564                           DepWaitTaskArgs);
4565     // Call proxy_task_entry(gtid, new_task);
4566     auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4567                       Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
4568       Action.Enter(CGF);
4569       llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4570       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
4571                                                           OutlinedFnArgs);
4572     };
4573 
4574     // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4575     // kmp_task_t *new_task);
4576     // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4577     // kmp_task_t *new_task);
4578     RegionCodeGenTy RCG(CodeGen);
4579     CommonActionTy Action(
4580         RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4581         RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4582     RCG.setAction(Action);
4583     RCG(CGF);
4584   };
4585 
4586   if (IfCond)
4587     emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
4588   else {
4589     RegionCodeGenTy ThenRCG(ThenCodeGen);
4590     ThenRCG(CGF);
4591   }
4592 }
4593 
4594 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4595                                        const OMPLoopDirective &D,
4596                                        llvm::Value *TaskFunction,
4597                                        QualType SharedsTy, Address Shareds,
4598                                        const Expr *IfCond,
4599                                        const OMPTaskDataTy &Data) {
4600   if (!CGF.HaveInsertPoint())
4601     return;
4602   TaskResultTy Result =
4603       emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4604   // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4605   // libcall.
4606   // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4607   // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4608   // sched, kmp_uint64 grainsize, void *task_dup);
4609   llvm::Value *ThreadID = getThreadID(CGF, Loc);
4610   llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4611   llvm::Value *IfVal;
4612   if (IfCond) {
4613     IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4614                                       /*isSigned=*/true);
4615   } else
4616     IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4617 
4618   LValue LBLVal = CGF.EmitLValueForField(
4619       Result.TDBase,
4620       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
4621   auto *LBVar =
4622       cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4623   CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4624                        /*IsInitializer=*/true);
4625   LValue UBLVal = CGF.EmitLValueForField(
4626       Result.TDBase,
4627       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
4628   auto *UBVar =
4629       cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4630   CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4631                        /*IsInitializer=*/true);
4632   LValue StLVal = CGF.EmitLValueForField(
4633       Result.TDBase,
4634       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
4635   auto *StVar =
4636       cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4637   CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4638                        /*IsInitializer=*/true);
4639   // Store reductions address.
4640   LValue RedLVal = CGF.EmitLValueForField(
4641       Result.TDBase,
4642       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4643   if (Data.Reductions)
4644     CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4645   else {
4646     CGF.EmitNullInitialization(RedLVal.getAddress(),
4647                                CGF.getContext().VoidPtrTy);
4648   }
4649   enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
4650   llvm::Value *TaskArgs[] = {
4651       UpLoc,
4652       ThreadID,
4653       Result.NewTask,
4654       IfVal,
4655       LBLVal.getPointer(),
4656       UBLVal.getPointer(),
4657       CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4658       llvm::ConstantInt::getNullValue(
4659           CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
4660       llvm::ConstantInt::getSigned(
4661           CGF.IntTy, Data.Schedule.getPointer()
4662                          ? Data.Schedule.getInt() ? NumTasks : Grainsize
4663                          : NoSchedule),
4664       Data.Schedule.getPointer()
4665           ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
4666                                       /*isSigned=*/false)
4667           : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
4668       Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4669                              Result.TaskDupFn, CGF.VoidPtrTy)
4670                        : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
4671   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4672 }
4673 
4674 /// \brief Emit reduction operation for each element of array (required for
4675 /// array sections) LHS op = RHS.
4676 /// \param Type Type of array.
4677 /// \param LHSVar Variable on the left side of the reduction operation
4678 /// (references element of array in original variable).
4679 /// \param RHSVar Variable on the right side of the reduction operation
4680 /// (references element of array in original variable).
4681 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
4682 /// RHSVar.
4683 static void EmitOMPAggregateReduction(
4684     CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4685     const VarDecl *RHSVar,
4686     const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4687                                   const Expr *, const Expr *)> &RedOpGen,
4688     const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4689     const Expr *UpExpr = nullptr) {
4690   // Perform element-by-element initialization.
4691   QualType ElementTy;
4692   Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4693   Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4694 
4695   // Drill down to the base element type on both arrays.
4696   auto ArrayTy = Type->getAsArrayTypeUnsafe();
4697   auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4698 
4699   auto RHSBegin = RHSAddr.getPointer();
4700   auto LHSBegin = LHSAddr.getPointer();
4701   // Cast from pointer to array type to pointer to single element.
4702   auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4703   // The basic structure here is a while-do loop.
4704   auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4705   auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4706   auto IsEmpty =
4707       CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4708   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4709 
4710   // Enter the loop body, making that address the current address.
4711   auto EntryBB = CGF.Builder.GetInsertBlock();
4712   CGF.EmitBlock(BodyBB);
4713 
4714   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4715 
4716   llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4717       RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4718   RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4719   Address RHSElementCurrent =
4720       Address(RHSElementPHI,
4721               RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4722 
4723   llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4724       LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4725   LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4726   Address LHSElementCurrent =
4727       Address(LHSElementPHI,
4728               LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4729 
4730   // Emit copy.
4731   CodeGenFunction::OMPPrivateScope Scope(CGF);
4732   Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4733   Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4734   Scope.Privatize();
4735   RedOpGen(CGF, XExpr, EExpr, UpExpr);
4736   Scope.ForceCleanup();
4737 
4738   // Shift the address forward by one element.
4739   auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4740       LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4741   auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4742       RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4743   // Check whether we've reached the end.
4744   auto Done =
4745       CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4746   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4747   LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4748   RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4749 
4750   // Done.
4751   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4752 }
4753 
4754 /// Emit reduction combiner. If the combiner is a simple expression emit it as
4755 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4756 /// UDR combiner function.
4757 static void emitReductionCombiner(CodeGenFunction &CGF,
4758                                   const Expr *ReductionOp) {
4759   if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4760     if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4761       if (auto *DRE =
4762               dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4763         if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4764           std::pair<llvm::Function *, llvm::Function *> Reduction =
4765               CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4766           RValue Func = RValue::get(Reduction.first);
4767           CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4768           CGF.EmitIgnoredExpr(ReductionOp);
4769           return;
4770         }
4771   CGF.EmitIgnoredExpr(ReductionOp);
4772 }
4773 
4774 llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4775     CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4776     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4777     ArrayRef<const Expr *> ReductionOps) {
4778   auto &C = CGM.getContext();
4779 
4780   // void reduction_func(void *LHSArg, void *RHSArg);
4781   FunctionArgList Args;
4782   ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4783   ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4784   Args.push_back(&LHSArg);
4785   Args.push_back(&RHSArg);
4786   auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4787   auto *Fn = llvm::Function::Create(
4788       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4789       ".omp.reduction.reduction_func", &CGM.getModule());
4790   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
4791   CodeGenFunction CGF(CGM);
4792   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4793 
4794   // Dst = (void*[n])(LHSArg);
4795   // Src = (void*[n])(RHSArg);
4796   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4797       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4798       ArgsType), CGF.getPointerAlign());
4799   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4800       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4801       ArgsType), CGF.getPointerAlign());
4802 
4803   //  ...
4804   //  *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4805   //  ...
4806   CodeGenFunction::OMPPrivateScope Scope(CGF);
4807   auto IPriv = Privates.begin();
4808   unsigned Idx = 0;
4809   for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
4810     auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4811     Scope.addPrivate(RHSVar, [&]() -> Address {
4812       return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
4813     });
4814     auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4815     Scope.addPrivate(LHSVar, [&]() -> Address {
4816       return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
4817     });
4818     QualType PrivTy = (*IPriv)->getType();
4819     if (PrivTy->isVariablyModifiedType()) {
4820       // Get array size and emit VLA type.
4821       ++Idx;
4822       Address Elem =
4823           CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4824       llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
4825       auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4826       auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
4827       CodeGenFunction::OpaqueValueMapping OpaqueMap(
4828           CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
4829       CGF.EmitVariablyModifiedType(PrivTy);
4830     }
4831   }
4832   Scope.Privatize();
4833   IPriv = Privates.begin();
4834   auto ILHS = LHSExprs.begin();
4835   auto IRHS = RHSExprs.begin();
4836   for (auto *E : ReductionOps) {
4837     if ((*IPriv)->getType()->isArrayType()) {
4838       // Emit reduction for array section.
4839       auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4840       auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4841       EmitOMPAggregateReduction(
4842           CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4843           [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4844             emitReductionCombiner(CGF, E);
4845           });
4846     } else
4847       // Emit reduction for array subscript or single variable.
4848       emitReductionCombiner(CGF, E);
4849     ++IPriv;
4850     ++ILHS;
4851     ++IRHS;
4852   }
4853   Scope.ForceCleanup();
4854   CGF.FinishFunction();
4855   return Fn;
4856 }
4857 
4858 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4859                                                   const Expr *ReductionOp,
4860                                                   const Expr *PrivateRef,
4861                                                   const DeclRefExpr *LHS,
4862                                                   const DeclRefExpr *RHS) {
4863   if (PrivateRef->getType()->isArrayType()) {
4864     // Emit reduction for array section.
4865     auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4866     auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4867     EmitOMPAggregateReduction(
4868         CGF, PrivateRef->getType(), LHSVar, RHSVar,
4869         [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4870           emitReductionCombiner(CGF, ReductionOp);
4871         });
4872   } else
4873     // Emit reduction for array subscript or single variable.
4874     emitReductionCombiner(CGF, ReductionOp);
4875 }
4876 
4877 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
4878                                     ArrayRef<const Expr *> Privates,
4879                                     ArrayRef<const Expr *> LHSExprs,
4880                                     ArrayRef<const Expr *> RHSExprs,
4881                                     ArrayRef<const Expr *> ReductionOps,
4882                                     ReductionOptionsTy Options) {
4883   if (!CGF.HaveInsertPoint())
4884     return;
4885 
4886   bool WithNowait = Options.WithNowait;
4887   bool SimpleReduction = Options.SimpleReduction;
4888 
4889   // Next code should be emitted for reduction:
4890   //
4891   // static kmp_critical_name lock = { 0 };
4892   //
4893   // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4894   //  *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4895   //  ...
4896   //  *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4897   //  *(Type<n>-1*)rhs[<n>-1]);
4898   // }
4899   //
4900   // ...
4901   // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4902   // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4903   // RedList, reduce_func, &<lock>)) {
4904   // case 1:
4905   //  ...
4906   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4907   //  ...
4908   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4909   // break;
4910   // case 2:
4911   //  ...
4912   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4913   //  ...
4914   // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
4915   // break;
4916   // default:;
4917   // }
4918   //
4919   // if SimpleReduction is true, only the next code is generated:
4920   //  ...
4921   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4922   //  ...
4923 
4924   auto &C = CGM.getContext();
4925 
4926   if (SimpleReduction) {
4927     CodeGenFunction::RunCleanupsScope Scope(CGF);
4928     auto IPriv = Privates.begin();
4929     auto ILHS = LHSExprs.begin();
4930     auto IRHS = RHSExprs.begin();
4931     for (auto *E : ReductionOps) {
4932       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4933                                   cast<DeclRefExpr>(*IRHS));
4934       ++IPriv;
4935       ++ILHS;
4936       ++IRHS;
4937     }
4938     return;
4939   }
4940 
4941   // 1. Build a list of reduction variables.
4942   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4943   auto Size = RHSExprs.size();
4944   for (auto *E : Privates) {
4945     if (E->getType()->isVariablyModifiedType())
4946       // Reserve place for array size.
4947       ++Size;
4948   }
4949   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4950   QualType ReductionArrayTy =
4951       C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4952                              /*IndexTypeQuals=*/0);
4953   Address ReductionList =
4954       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4955   auto IPriv = Privates.begin();
4956   unsigned Idx = 0;
4957   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4958     Address Elem =
4959       CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
4960     CGF.Builder.CreateStore(
4961         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4962             CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4963         Elem);
4964     if ((*IPriv)->getType()->isVariablyModifiedType()) {
4965       // Store array size.
4966       ++Idx;
4967       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4968                                              CGF.getPointerSize());
4969       llvm::Value *Size = CGF.Builder.CreateIntCast(
4970           CGF.getVLASize(
4971                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4972               .first,
4973           CGF.SizeTy, /*isSigned=*/false);
4974       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4975                               Elem);
4976     }
4977   }
4978 
4979   // 2. Emit reduce_func().
4980   auto *ReductionFn = emitReductionFunction(
4981       CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4982       LHSExprs, RHSExprs, ReductionOps);
4983 
4984   // 3. Create static kmp_critical_name lock = { 0 };
4985   auto *Lock = getCriticalRegionLock(".reduction");
4986 
4987   // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4988   // RedList, reduce_func, &<lock>);
4989   auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
4990   auto *ThreadId = getThreadID(CGF, Loc);
4991   auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4992   auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4993       ReductionList.getPointer(), CGF.VoidPtrTy);
4994   llvm::Value *Args[] = {
4995       IdentTLoc,                             // ident_t *<loc>
4996       ThreadId,                              // i32 <gtid>
4997       CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4998       ReductionArrayTySize,                  // size_type sizeof(RedList)
4999       RL,                                    // void *RedList
5000       ReductionFn, // void (*) (void *, void *) <reduce_func>
5001       Lock         // kmp_critical_name *&<lock>
5002   };
5003   auto Res = CGF.EmitRuntimeCall(
5004       createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5005                                        : OMPRTL__kmpc_reduce),
5006       Args);
5007 
5008   // 5. Build switch(res)
5009   auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5010   auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5011 
5012   // 6. Build case 1:
5013   //  ...
5014   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5015   //  ...
5016   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5017   // break;
5018   auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5019   SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5020   CGF.EmitBlock(Case1BB);
5021 
5022   // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5023   llvm::Value *EndArgs[] = {
5024       IdentTLoc, // ident_t *<loc>
5025       ThreadId,  // i32 <gtid>
5026       Lock       // kmp_critical_name *&<lock>
5027   };
5028   auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5029       CodeGenFunction &CGF, PrePostActionTy &Action) {
5030     auto &RT = CGF.CGM.getOpenMPRuntime();
5031     auto IPriv = Privates.begin();
5032     auto ILHS = LHSExprs.begin();
5033     auto IRHS = RHSExprs.begin();
5034     for (auto *E : ReductionOps) {
5035       RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5036                                      cast<DeclRefExpr>(*IRHS));
5037       ++IPriv;
5038       ++ILHS;
5039       ++IRHS;
5040     }
5041   };
5042   RegionCodeGenTy RCG(CodeGen);
5043   CommonActionTy Action(
5044       nullptr, llvm::None,
5045       createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5046                                        : OMPRTL__kmpc_end_reduce),
5047       EndArgs);
5048   RCG.setAction(Action);
5049   RCG(CGF);
5050 
5051   CGF.EmitBranch(DefaultBB);
5052 
5053   // 7. Build case 2:
5054   //  ...
5055   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5056   //  ...
5057   // break;
5058   auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5059   SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5060   CGF.EmitBlock(Case2BB);
5061 
5062   auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5063       CodeGenFunction &CGF, PrePostActionTy &Action) {
5064     auto ILHS = LHSExprs.begin();
5065     auto IRHS = RHSExprs.begin();
5066     auto IPriv = Privates.begin();
5067     for (auto *E : ReductionOps) {
5068       const Expr *XExpr = nullptr;
5069       const Expr *EExpr = nullptr;
5070       const Expr *UpExpr = nullptr;
5071       BinaryOperatorKind BO = BO_Comma;
5072       if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5073         if (BO->getOpcode() == BO_Assign) {
5074           XExpr = BO->getLHS();
5075           UpExpr = BO->getRHS();
5076         }
5077       }
5078       // Try to emit update expression as a simple atomic.
5079       auto *RHSExpr = UpExpr;
5080       if (RHSExpr) {
5081         // Analyze RHS part of the whole expression.
5082         if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5083                 RHSExpr->IgnoreParenImpCasts())) {
5084           // If this is a conditional operator, analyze its condition for
5085           // min/max reduction operator.
5086           RHSExpr = ACO->getCond();
5087         }
5088         if (auto *BORHS =
5089                 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5090           EExpr = BORHS->getRHS();
5091           BO = BORHS->getOpcode();
5092         }
5093       }
5094       if (XExpr) {
5095         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5096         auto &&AtomicRedGen = [BO, VD,
5097                                Loc](CodeGenFunction &CGF, const Expr *XExpr,
5098                                     const Expr *EExpr, const Expr *UpExpr) {
5099           LValue X = CGF.EmitLValue(XExpr);
5100           RValue E;
5101           if (EExpr)
5102             E = CGF.EmitAnyExpr(EExpr);
5103           CGF.EmitOMPAtomicSimpleUpdateExpr(
5104               X, E, BO, /*IsXLHSInRHSPart=*/true,
5105               llvm::AtomicOrdering::Monotonic, Loc,
5106               [&CGF, UpExpr, VD, Loc](RValue XRValue) {
5107                 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5108                 PrivateScope.addPrivate(
5109                     VD, [&CGF, VD, XRValue, Loc]() -> Address {
5110                       Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5111                       CGF.emitOMPSimpleStore(
5112                           CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5113                           VD->getType().getNonReferenceType(), Loc);
5114                       return LHSTemp;
5115                     });
5116                 (void)PrivateScope.Privatize();
5117                 return CGF.EmitAnyExpr(UpExpr);
5118               });
5119         };
5120         if ((*IPriv)->getType()->isArrayType()) {
5121           // Emit atomic reduction for array section.
5122           auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5123           EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5124                                     AtomicRedGen, XExpr, EExpr, UpExpr);
5125         } else
5126           // Emit atomic reduction for array subscript or single variable.
5127           AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5128       } else {
5129         // Emit as a critical region.
5130         auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5131                                      const Expr *, const Expr *) {
5132           auto &RT = CGF.CGM.getOpenMPRuntime();
5133           RT.emitCriticalRegion(
5134               CGF, ".atomic_reduction",
5135               [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5136                 Action.Enter(CGF);
5137                 emitReductionCombiner(CGF, E);
5138               },
5139               Loc);
5140         };
5141         if ((*IPriv)->getType()->isArrayType()) {
5142           auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5143           auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5144           EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5145                                     CritRedGen);
5146         } else
5147           CritRedGen(CGF, nullptr, nullptr, nullptr);
5148       }
5149       ++ILHS;
5150       ++IRHS;
5151       ++IPriv;
5152     }
5153   };
5154   RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5155   if (!WithNowait) {
5156     // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5157     llvm::Value *EndArgs[] = {
5158         IdentTLoc, // ident_t *<loc>
5159         ThreadId,  // i32 <gtid>
5160         Lock       // kmp_critical_name *&<lock>
5161     };
5162     CommonActionTy Action(nullptr, llvm::None,
5163                           createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5164                           EndArgs);
5165     AtomicRCG.setAction(Action);
5166     AtomicRCG(CGF);
5167   } else
5168     AtomicRCG(CGF);
5169 
5170   CGF.EmitBranch(DefaultBB);
5171   CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5172 }
5173 
5174 /// Generates unique name for artificial threadprivate variables.
5175 /// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5176 static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5177                                       unsigned N) {
5178   SmallString<256> Buffer;
5179   llvm::raw_svector_ostream Out(Buffer);
5180   Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5181   return Out.str();
5182 }
5183 
5184 /// Emits reduction initializer function:
5185 /// \code
5186 /// void @.red_init(void* %arg) {
5187 /// %0 = bitcast void* %arg to <type>*
5188 /// store <type> <init>, <type>* %0
5189 /// ret void
5190 /// }
5191 /// \endcode
5192 static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5193                                            SourceLocation Loc,
5194                                            ReductionCodeGen &RCG, unsigned N) {
5195   auto &C = CGM.getContext();
5196   FunctionArgList Args;
5197   ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5198   Args.emplace_back(&Param);
5199   auto &FnInfo =
5200       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5201   auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5202   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5203                                     ".red_init.", &CGM.getModule());
5204   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5205   CodeGenFunction CGF(CGM);
5206   CGF.disableDebugInfo();
5207   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5208   Address PrivateAddr = CGF.EmitLoadOfPointer(
5209       CGF.GetAddrOfLocalVar(&Param),
5210       C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5211   llvm::Value *Size = nullptr;
5212   // If the size of the reduction item is non-constant, load it from global
5213   // threadprivate variable.
5214   if (RCG.getSizes(N).second) {
5215     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5216         CGF, CGM.getContext().getSizeType(),
5217         generateUniqueName("reduction_size", Loc, N));
5218     Size =
5219         CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5220                              CGM.getContext().getSizeType(), SourceLocation());
5221   }
5222   RCG.emitAggregateType(CGF, N, Size);
5223   LValue SharedLVal;
5224   // If initializer uses initializer from declare reduction construct, emit a
5225   // pointer to the address of the original reduction item (reuired by reduction
5226   // initializer)
5227   if (RCG.usesReductionInitializer(N)) {
5228     Address SharedAddr =
5229         CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5230             CGF, CGM.getContext().VoidPtrTy,
5231             generateUniqueName("reduction", Loc, N));
5232     SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5233   } else {
5234     SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5235         llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5236         CGM.getContext().VoidPtrTy);
5237   }
5238   // Emit the initializer:
5239   // %0 = bitcast void* %arg to <type>*
5240   // store <type> <init>, <type>* %0
5241   RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5242                          [](CodeGenFunction &) { return false; });
5243   CGF.FinishFunction();
5244   return Fn;
5245 }
5246 
5247 /// Emits reduction combiner function:
5248 /// \code
5249 /// void @.red_comb(void* %arg0, void* %arg1) {
5250 /// %lhs = bitcast void* %arg0 to <type>*
5251 /// %rhs = bitcast void* %arg1 to <type>*
5252 /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5253 /// store <type> %2, <type>* %lhs
5254 /// ret void
5255 /// }
5256 /// \endcode
5257 static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5258                                            SourceLocation Loc,
5259                                            ReductionCodeGen &RCG, unsigned N,
5260                                            const Expr *ReductionOp,
5261                                            const Expr *LHS, const Expr *RHS,
5262                                            const Expr *PrivateRef) {
5263   auto &C = CGM.getContext();
5264   auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5265   auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5266   FunctionArgList Args;
5267   ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5268   ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5269   Args.emplace_back(&ParamInOut);
5270   Args.emplace_back(&ParamIn);
5271   auto &FnInfo =
5272       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5273   auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5274   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5275                                     ".red_comb.", &CGM.getModule());
5276   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5277   CodeGenFunction CGF(CGM);
5278   CGF.disableDebugInfo();
5279   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5280   llvm::Value *Size = nullptr;
5281   // If the size of the reduction item is non-constant, load it from global
5282   // threadprivate variable.
5283   if (RCG.getSizes(N).second) {
5284     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5285         CGF, CGM.getContext().getSizeType(),
5286         generateUniqueName("reduction_size", Loc, N));
5287     Size =
5288         CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5289                              CGM.getContext().getSizeType(), SourceLocation());
5290   }
5291   RCG.emitAggregateType(CGF, N, Size);
5292   // Remap lhs and rhs variables to the addresses of the function arguments.
5293   // %lhs = bitcast void* %arg0 to <type>*
5294   // %rhs = bitcast void* %arg1 to <type>*
5295   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5296   PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5297     // Pull out the pointer to the variable.
5298     Address PtrAddr = CGF.EmitLoadOfPointer(
5299         CGF.GetAddrOfLocalVar(&ParamInOut),
5300         C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5301     return CGF.Builder.CreateElementBitCast(
5302         PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5303   });
5304   PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5305     // Pull out the pointer to the variable.
5306     Address PtrAddr = CGF.EmitLoadOfPointer(
5307         CGF.GetAddrOfLocalVar(&ParamIn),
5308         C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5309     return CGF.Builder.CreateElementBitCast(
5310         PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5311   });
5312   PrivateScope.Privatize();
5313   // Emit the combiner body:
5314   // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5315   // store <type> %2, <type>* %lhs
5316   CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5317       CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5318       cast<DeclRefExpr>(RHS));
5319   CGF.FinishFunction();
5320   return Fn;
5321 }
5322 
5323 /// Emits reduction finalizer function:
5324 /// \code
5325 /// void @.red_fini(void* %arg) {
5326 /// %0 = bitcast void* %arg to <type>*
5327 /// <destroy>(<type>* %0)
5328 /// ret void
5329 /// }
5330 /// \endcode
5331 static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5332                                            SourceLocation Loc,
5333                                            ReductionCodeGen &RCG, unsigned N) {
5334   if (!RCG.needCleanups(N))
5335     return nullptr;
5336   auto &C = CGM.getContext();
5337   FunctionArgList Args;
5338   ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5339   Args.emplace_back(&Param);
5340   auto &FnInfo =
5341       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5342   auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5343   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5344                                     ".red_fini.", &CGM.getModule());
5345   CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5346   CodeGenFunction CGF(CGM);
5347   CGF.disableDebugInfo();
5348   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5349   Address PrivateAddr = CGF.EmitLoadOfPointer(
5350       CGF.GetAddrOfLocalVar(&Param),
5351       C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5352   llvm::Value *Size = nullptr;
5353   // If the size of the reduction item is non-constant, load it from global
5354   // threadprivate variable.
5355   if (RCG.getSizes(N).second) {
5356     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5357         CGF, CGM.getContext().getSizeType(),
5358         generateUniqueName("reduction_size", Loc, N));
5359     Size =
5360         CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5361                              CGM.getContext().getSizeType(), SourceLocation());
5362   }
5363   RCG.emitAggregateType(CGF, N, Size);
5364   // Emit the finalizer body:
5365   // <destroy>(<type>* %0)
5366   RCG.emitCleanups(CGF, N, PrivateAddr);
5367   CGF.FinishFunction();
5368   return Fn;
5369 }
5370 
5371 llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5372     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5373     ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5374   if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5375     return nullptr;
5376 
5377   // Build typedef struct:
5378   // kmp_task_red_input {
5379   //   void *reduce_shar; // shared reduction item
5380   //   size_t reduce_size; // size of data item
5381   //   void *reduce_init; // data initialization routine
5382   //   void *reduce_fini; // data finalization routine
5383   //   void *reduce_comb; // data combiner routine
5384   //   kmp_task_red_flags_t flags; // flags for additional info from compiler
5385   // } kmp_task_red_input_t;
5386   ASTContext &C = CGM.getContext();
5387   auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5388   RD->startDefinition();
5389   const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5390   const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5391   const FieldDecl *InitFD  = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5392   const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5393   const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5394   const FieldDecl *FlagsFD = addFieldToRecordDecl(
5395       C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5396   RD->completeDefinition();
5397   QualType RDType = C.getRecordType(RD);
5398   unsigned Size = Data.ReductionVars.size();
5399   llvm::APInt ArraySize(/*numBits=*/64, Size);
5400   QualType ArrayRDType = C.getConstantArrayType(
5401       RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5402   // kmp_task_red_input_t .rd_input.[Size];
5403   Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5404   ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5405                        Data.ReductionOps);
5406   for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5407     // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5408     llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5409                            llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5410     llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5411         TaskRedInput.getPointer(), Idxs,
5412         /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5413         ".rd_input.gep.");
5414     LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5415     // ElemLVal.reduce_shar = &Shareds[Cnt];
5416     LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5417     RCG.emitSharedLValue(CGF, Cnt);
5418     llvm::Value *CastedShared =
5419         CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5420     CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5421     RCG.emitAggregateType(CGF, Cnt);
5422     llvm::Value *SizeValInChars;
5423     llvm::Value *SizeVal;
5424     std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5425     // We use delayed creation/initialization for VLAs, array sections and
5426     // custom reduction initializations. It is required because runtime does not
5427     // provide the way to pass the sizes of VLAs/array sections to
5428     // initializer/combiner/finalizer functions and does not pass the pointer to
5429     // original reduction item to the initializer. Instead threadprivate global
5430     // variables are used to store these values and use them in the functions.
5431     bool DelayedCreation = !!SizeVal;
5432     SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5433                                                /*isSigned=*/false);
5434     LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5435     CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5436     // ElemLVal.reduce_init = init;
5437     LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5438     llvm::Value *InitAddr =
5439         CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5440     CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5441     DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5442     // ElemLVal.reduce_fini = fini;
5443     LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5444     llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5445     llvm::Value *FiniAddr = Fini
5446                                 ? CGF.EmitCastToVoidPtr(Fini)
5447                                 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5448     CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5449     // ElemLVal.reduce_comb = comb;
5450     LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5451     llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5452         CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5453         RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5454     CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5455     // ElemLVal.flags = 0;
5456     LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5457     if (DelayedCreation) {
5458       CGF.EmitStoreOfScalar(
5459           llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5460           FlagsLVal);
5461     } else
5462       CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5463   }
5464   // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5465   // *data);
5466   llvm::Value *Args[] = {
5467       CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5468                                 /*isSigned=*/true),
5469       llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5470       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5471                                                       CGM.VoidPtrTy)};
5472   return CGF.EmitRuntimeCall(
5473       createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5474 }
5475 
5476 void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5477                                               SourceLocation Loc,
5478                                               ReductionCodeGen &RCG,
5479                                               unsigned N) {
5480   auto Sizes = RCG.getSizes(N);
5481   // Emit threadprivate global variable if the type is non-constant
5482   // (Sizes.second = nullptr).
5483   if (Sizes.second) {
5484     llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5485                                                      /*isSigned=*/false);
5486     Address SizeAddr = getAddrOfArtificialThreadPrivate(
5487         CGF, CGM.getContext().getSizeType(),
5488         generateUniqueName("reduction_size", Loc, N));
5489     CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5490   }
5491   // Store address of the original reduction item if custom initializer is used.
5492   if (RCG.usesReductionInitializer(N)) {
5493     Address SharedAddr = getAddrOfArtificialThreadPrivate(
5494         CGF, CGM.getContext().VoidPtrTy,
5495         generateUniqueName("reduction", Loc, N));
5496     CGF.Builder.CreateStore(
5497         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5498             RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5499         SharedAddr, /*IsVolatile=*/false);
5500   }
5501 }
5502 
5503 Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5504                                               SourceLocation Loc,
5505                                               llvm::Value *ReductionsPtr,
5506                                               LValue SharedLVal) {
5507   // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5508   // *d);
5509   llvm::Value *Args[] = {
5510       CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5511                                 /*isSigned=*/true),
5512       ReductionsPtr,
5513       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5514                                                       CGM.VoidPtrTy)};
5515   return Address(
5516       CGF.EmitRuntimeCall(
5517           createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5518       SharedLVal.getAlignment());
5519 }
5520 
5521 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5522                                        SourceLocation Loc) {
5523   if (!CGF.HaveInsertPoint())
5524     return;
5525   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5526   // global_tid);
5527   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5528   // Ignore return result until untied tasks are supported.
5529   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
5530   if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5531     Region->emitUntiedSwitch(CGF);
5532 }
5533 
5534 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
5535                                            OpenMPDirectiveKind InnerKind,
5536                                            const RegionCodeGenTy &CodeGen,
5537                                            bool HasCancel) {
5538   if (!CGF.HaveInsertPoint())
5539     return;
5540   InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
5541   CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
5542 }
5543 
5544 namespace {
5545 enum RTCancelKind {
5546   CancelNoreq = 0,
5547   CancelParallel = 1,
5548   CancelLoop = 2,
5549   CancelSections = 3,
5550   CancelTaskgroup = 4
5551 };
5552 } // anonymous namespace
5553 
5554 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5555   RTCancelKind CancelKind = CancelNoreq;
5556   if (CancelRegion == OMPD_parallel)
5557     CancelKind = CancelParallel;
5558   else if (CancelRegion == OMPD_for)
5559     CancelKind = CancelLoop;
5560   else if (CancelRegion == OMPD_sections)
5561     CancelKind = CancelSections;
5562   else {
5563     assert(CancelRegion == OMPD_taskgroup);
5564     CancelKind = CancelTaskgroup;
5565   }
5566   return CancelKind;
5567 }
5568 
5569 void CGOpenMPRuntime::emitCancellationPointCall(
5570     CodeGenFunction &CGF, SourceLocation Loc,
5571     OpenMPDirectiveKind CancelRegion) {
5572   if (!CGF.HaveInsertPoint())
5573     return;
5574   // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5575   // global_tid, kmp_int32 cncl_kind);
5576   if (auto *OMPRegionInfo =
5577           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
5578     // For 'cancellation point taskgroup', the task region info may not have a
5579     // cancel. This may instead happen in another adjacent task.
5580     if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
5581       llvm::Value *Args[] = {
5582           emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5583           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5584       // Ignore return result until untied tasks are supported.
5585       auto *Result = CGF.EmitRuntimeCall(
5586           createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5587       // if (__kmpc_cancellationpoint()) {
5588       //   exit from construct;
5589       // }
5590       auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5591       auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5592       auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5593       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5594       CGF.EmitBlock(ExitBB);
5595       // exit from construct;
5596       auto CancelDest =
5597           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5598       CGF.EmitBranchThroughCleanup(CancelDest);
5599       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5600     }
5601   }
5602 }
5603 
5604 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
5605                                      const Expr *IfCond,
5606                                      OpenMPDirectiveKind CancelRegion) {
5607   if (!CGF.HaveInsertPoint())
5608     return;
5609   // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5610   // kmp_int32 cncl_kind);
5611   if (auto *OMPRegionInfo =
5612           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
5613     auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5614                                                         PrePostActionTy &) {
5615       auto &RT = CGF.CGM.getOpenMPRuntime();
5616       llvm::Value *Args[] = {
5617           RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
5618           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5619       // Ignore return result until untied tasks are supported.
5620       auto *Result = CGF.EmitRuntimeCall(
5621           RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
5622       // if (__kmpc_cancel()) {
5623       //   exit from construct;
5624       // }
5625       auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5626       auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5627       auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5628       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5629       CGF.EmitBlock(ExitBB);
5630       // exit from construct;
5631       auto CancelDest =
5632           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5633       CGF.EmitBranchThroughCleanup(CancelDest);
5634       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5635     };
5636     if (IfCond)
5637       emitOMPIfClause(CGF, IfCond, ThenGen,
5638                       [](CodeGenFunction &, PrePostActionTy &) {});
5639     else {
5640       RegionCodeGenTy ThenRCG(ThenGen);
5641       ThenRCG(CGF);
5642     }
5643   }
5644 }
5645 
5646 /// \brief Obtain information that uniquely identifies a target entry. This
5647 /// consists of the file and device IDs as well as line number associated with
5648 /// the relevant entry source location.
5649 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5650                                      unsigned &DeviceID, unsigned &FileID,
5651                                      unsigned &LineNum) {
5652 
5653   auto &SM = C.getSourceManager();
5654 
5655   // The loc should be always valid and have a file ID (the user cannot use
5656   // #pragma directives in macros)
5657 
5658   assert(Loc.isValid() && "Source location is expected to be always valid.");
5659   assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5660 
5661   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5662   assert(PLoc.isValid() && "Source location is expected to be always valid.");
5663 
5664   llvm::sys::fs::UniqueID ID;
5665   if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5666     llvm_unreachable("Source file with target region no longer exists!");
5667 
5668   DeviceID = ID.getDevice();
5669   FileID = ID.getFile();
5670   LineNum = PLoc.getLine();
5671 }
5672 
5673 void CGOpenMPRuntime::emitTargetOutlinedFunction(
5674     const OMPExecutableDirective &D, StringRef ParentName,
5675     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5676     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
5677   assert(!ParentName.empty() && "Invalid target region parent name!");
5678 
5679   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5680                                    IsOffloadEntry, CodeGen);
5681 }
5682 
5683 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5684     const OMPExecutableDirective &D, StringRef ParentName,
5685     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5686     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
5687   // Create a unique name for the entry function using the source location
5688   // information of the current target region. The name will be something like:
5689   //
5690   // __omp_offloading_DD_FFFF_PP_lBB
5691   //
5692   // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
5693   // mangled name of the function that encloses the target region and BB is the
5694   // line number of the target region.
5695 
5696   unsigned DeviceID;
5697   unsigned FileID;
5698   unsigned Line;
5699   getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
5700                            Line);
5701   SmallString<64> EntryFnName;
5702   {
5703     llvm::raw_svector_ostream OS(EntryFnName);
5704     OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5705        << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
5706   }
5707 
5708   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5709 
5710   CodeGenFunction CGF(CGM, true);
5711   CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
5712   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5713 
5714   OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
5715 
5716   // If this target outline function is not an offload entry, we don't need to
5717   // register it.
5718   if (!IsOffloadEntry)
5719     return;
5720 
5721   // The target region ID is used by the runtime library to identify the current
5722   // target region, so it only has to be unique and not necessarily point to
5723   // anything. It could be the pointer to the outlined function that implements
5724   // the target region, but we aren't using that so that the compiler doesn't
5725   // need to keep that, and could therefore inline the host function if proven
5726   // worthwhile during optimization. In the other hand, if emitting code for the
5727   // device, the ID has to be the function address so that it can retrieved from
5728   // the offloading entry and launched by the runtime library. We also mark the
5729   // outlined function to have external linkage in case we are emitting code for
5730   // the device, because these functions will be entry points to the device.
5731 
5732   if (CGM.getLangOpts().OpenMPIsDevice) {
5733     OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5734     OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5735   } else
5736     OutlinedFnID = new llvm::GlobalVariable(
5737         CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5738         llvm::GlobalValue::PrivateLinkage,
5739         llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5740 
5741   // Register the information for the entry associated with this target region.
5742   OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
5743       DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5744       /*Flags=*/0);
5745 }
5746 
5747 /// discard all CompoundStmts intervening between two constructs
5748 static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5749   while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5750     Body = CS->body_front();
5751 
5752   return Body;
5753 }
5754 
5755 /// Emit the number of teams for a target directive.  Inspect the num_teams
5756 /// clause associated with a teams construct combined or closely nested
5757 /// with the target directive.
5758 ///
5759 /// Emit a team of size one for directives such as 'target parallel' that
5760 /// have no associated teams construct.
5761 ///
5762 /// Otherwise, return nullptr.
5763 static llvm::Value *
5764 emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5765                                CodeGenFunction &CGF,
5766                                const OMPExecutableDirective &D) {
5767 
5768   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5769                                               "teams directive expected to be "
5770                                               "emitted only for the host!");
5771 
5772   auto &Bld = CGF.Builder;
5773 
5774   // If the target directive is combined with a teams directive:
5775   //   Return the value in the num_teams clause, if any.
5776   //   Otherwise, return 0 to denote the runtime default.
5777   if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5778     if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5779       CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5780       auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5781                                          /*IgnoreResultAssign*/ true);
5782       return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5783                                /*IsSigned=*/true);
5784     }
5785 
5786     // The default value is 0.
5787     return Bld.getInt32(0);
5788   }
5789 
5790   // If the target directive is combined with a parallel directive but not a
5791   // teams directive, start one team.
5792   if (isOpenMPParallelDirective(D.getDirectiveKind()))
5793     return Bld.getInt32(1);
5794 
5795   // If the current target region has a teams region enclosed, we need to get
5796   // the number of teams to pass to the runtime function call. This is done
5797   // by generating the expression in a inlined region. This is required because
5798   // the expression is captured in the enclosing target environment when the
5799   // teams directive is not combined with target.
5800 
5801   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5802 
5803   // FIXME: Accommodate other combined directives with teams when they become
5804   // available.
5805   if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5806           ignoreCompoundStmts(CS.getCapturedStmt()))) {
5807     if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5808       CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5809       CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5810       llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
5811       return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5812                                /*IsSigned=*/true);
5813     }
5814 
5815     // If we have an enclosed teams directive but no num_teams clause we use
5816     // the default value 0.
5817     return Bld.getInt32(0);
5818   }
5819 
5820   // No teams associated with the directive.
5821   return nullptr;
5822 }
5823 
5824 /// Emit the number of threads for a target directive.  Inspect the
5825 /// thread_limit clause associated with a teams construct combined or closely
5826 /// nested with the target directive.
5827 ///
5828 /// Emit the num_threads clause for directives such as 'target parallel' that
5829 /// have no associated teams construct.
5830 ///
5831 /// Otherwise, return nullptr.
5832 static llvm::Value *
5833 emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5834                                  CodeGenFunction &CGF,
5835                                  const OMPExecutableDirective &D) {
5836 
5837   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5838                                               "teams directive expected to be "
5839                                               "emitted only for the host!");
5840 
5841   auto &Bld = CGF.Builder;
5842 
5843   //
5844   // If the target directive is combined with a teams directive:
5845   //   Return the value in the thread_limit clause, if any.
5846   //
5847   // If the target directive is combined with a parallel directive:
5848   //   Return the value in the num_threads clause, if any.
5849   //
5850   // If both clauses are set, select the minimum of the two.
5851   //
5852   // If neither teams or parallel combined directives set the number of threads
5853   // in a team, return 0 to denote the runtime default.
5854   //
5855   // If this is not a teams directive return nullptr.
5856 
5857   if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5858       isOpenMPParallelDirective(D.getDirectiveKind())) {
5859     llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5860     llvm::Value *NumThreadsVal = nullptr;
5861     llvm::Value *ThreadLimitVal = nullptr;
5862 
5863     if (const auto *ThreadLimitClause =
5864             D.getSingleClause<OMPThreadLimitClause>()) {
5865       CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5866       auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5867                                             /*IgnoreResultAssign*/ true);
5868       ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5869                                          /*IsSigned=*/true);
5870     }
5871 
5872     if (const auto *NumThreadsClause =
5873             D.getSingleClause<OMPNumThreadsClause>()) {
5874       CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5875       llvm::Value *NumThreads =
5876           CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5877                              /*IgnoreResultAssign*/ true);
5878       NumThreadsVal =
5879           Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5880     }
5881 
5882     // Select the lesser of thread_limit and num_threads.
5883     if (NumThreadsVal)
5884       ThreadLimitVal = ThreadLimitVal
5885                            ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5886                                                                 ThreadLimitVal),
5887                                               NumThreadsVal, ThreadLimitVal)
5888                            : NumThreadsVal;
5889 
5890     // Set default value passed to the runtime if either teams or a target
5891     // parallel type directive is found but no clause is specified.
5892     if (!ThreadLimitVal)
5893       ThreadLimitVal = DefaultThreadLimitVal;
5894 
5895     return ThreadLimitVal;
5896   }
5897 
5898   // If the current target region has a teams region enclosed, we need to get
5899   // the thread limit to pass to the runtime function call. This is done
5900   // by generating the expression in a inlined region. This is required because
5901   // the expression is captured in the enclosing target environment when the
5902   // teams directive is not combined with target.
5903 
5904   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5905 
5906   // FIXME: Accommodate other combined directives with teams when they become
5907   // available.
5908   if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5909           ignoreCompoundStmts(CS.getCapturedStmt()))) {
5910     if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5911       CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5912       CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5913       llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5914       return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5915                                        /*IsSigned=*/true);
5916     }
5917 
5918     // If we have an enclosed teams directive but no thread_limit clause we use
5919     // the default value 0.
5920     return CGF.Builder.getInt32(0);
5921   }
5922 
5923   // No teams associated with the directive.
5924   return nullptr;
5925 }
5926 
5927 namespace {
5928 // \brief Utility to handle information from clauses associated with a given
5929 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5930 // It provides a convenient interface to obtain the information and generate
5931 // code for that information.
5932 class MappableExprsHandler {
5933 public:
5934   /// \brief Values for bit flags used to specify the mapping type for
5935   /// offloading.
5936   enum OpenMPOffloadMappingFlags {
5937     /// \brief Allocate memory on the device and move data from host to device.
5938     OMP_MAP_TO = 0x01,
5939     /// \brief Allocate memory on the device and move data from device to host.
5940     OMP_MAP_FROM = 0x02,
5941     /// \brief Always perform the requested mapping action on the element, even
5942     /// if it was already mapped before.
5943     OMP_MAP_ALWAYS = 0x04,
5944     /// \brief Delete the element from the device environment, ignoring the
5945     /// current reference count associated with the element.
5946     OMP_MAP_DELETE = 0x08,
5947     /// \brief The element being mapped is a pointer, therefore the pointee
5948     /// should be mapped as well.
5949     OMP_MAP_IS_PTR = 0x10,
5950     /// \brief This flags signals that an argument is the first one relating to
5951     /// a map/private clause expression. For some cases a single
5952     /// map/privatization results in multiple arguments passed to the runtime
5953     /// library.
5954     OMP_MAP_FIRST_REF = 0x20,
5955     /// \brief Signal that the runtime library has to return the device pointer
5956     /// in the current position for the data being mapped.
5957     OMP_MAP_RETURN_PTR = 0x40,
5958     /// \brief This flag signals that the reference being passed is a pointer to
5959     /// private data.
5960     OMP_MAP_PRIVATE_PTR = 0x80,
5961     /// \brief Pass the element to the device by value.
5962     OMP_MAP_PRIVATE_VAL = 0x100,
5963   };
5964 
5965   /// Class that associates information with a base pointer to be passed to the
5966   /// runtime library.
5967   class BasePointerInfo {
5968     /// The base pointer.
5969     llvm::Value *Ptr = nullptr;
5970     /// The base declaration that refers to this device pointer, or null if
5971     /// there is none.
5972     const ValueDecl *DevPtrDecl = nullptr;
5973 
5974   public:
5975     BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5976         : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5977     llvm::Value *operator*() const { return Ptr; }
5978     const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5979     void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5980   };
5981 
5982   typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
5983   typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5984   typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5985 
5986 private:
5987   /// \brief Directive from where the map clauses were extracted.
5988   const OMPExecutableDirective &CurDir;
5989 
5990   /// \brief Function the directive is being generated for.
5991   CodeGenFunction &CGF;
5992 
5993   /// \brief Set of all first private variables in the current directive.
5994   llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5995 
5996   /// Map between device pointer declarations and their expression components.
5997   /// The key value for declarations in 'this' is null.
5998   llvm::DenseMap<
5999       const ValueDecl *,
6000       SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6001       DevPointersMap;
6002 
6003   llvm::Value *getExprTypeSize(const Expr *E) const {
6004     auto ExprTy = E->getType().getCanonicalType();
6005 
6006     // Reference types are ignored for mapping purposes.
6007     if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6008       ExprTy = RefTy->getPointeeType().getCanonicalType();
6009 
6010     // Given that an array section is considered a built-in type, we need to
6011     // do the calculation based on the length of the section instead of relying
6012     // on CGF.getTypeSize(E->getType()).
6013     if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6014       QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6015                             OAE->getBase()->IgnoreParenImpCasts())
6016                             .getCanonicalType();
6017 
6018       // If there is no length associated with the expression, that means we
6019       // are using the whole length of the base.
6020       if (!OAE->getLength() && OAE->getColonLoc().isValid())
6021         return CGF.getTypeSize(BaseTy);
6022 
6023       llvm::Value *ElemSize;
6024       if (auto *PTy = BaseTy->getAs<PointerType>())
6025         ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6026       else {
6027         auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6028         assert(ATy && "Expecting array type if not a pointer type.");
6029         ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6030       }
6031 
6032       // If we don't have a length at this point, that is because we have an
6033       // array section with a single element.
6034       if (!OAE->getLength())
6035         return ElemSize;
6036 
6037       auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6038       LengthVal =
6039           CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6040       return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6041     }
6042     return CGF.getTypeSize(ExprTy);
6043   }
6044 
6045   /// \brief Return the corresponding bits for a given map clause modifier. Add
6046   /// a flag marking the map as a pointer if requested. Add a flag marking the
6047   /// map as the first one of a series of maps that relate to the same map
6048   /// expression.
6049   unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6050                           OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
6051                           bool AddIsFirstFlag) const {
6052     unsigned Bits = 0u;
6053     switch (MapType) {
6054     case OMPC_MAP_alloc:
6055     case OMPC_MAP_release:
6056       // alloc and release is the default behavior in the runtime library,  i.e.
6057       // if we don't pass any bits alloc/release that is what the runtime is
6058       // going to do. Therefore, we don't need to signal anything for these two
6059       // type modifiers.
6060       break;
6061     case OMPC_MAP_to:
6062       Bits = OMP_MAP_TO;
6063       break;
6064     case OMPC_MAP_from:
6065       Bits = OMP_MAP_FROM;
6066       break;
6067     case OMPC_MAP_tofrom:
6068       Bits = OMP_MAP_TO | OMP_MAP_FROM;
6069       break;
6070     case OMPC_MAP_delete:
6071       Bits = OMP_MAP_DELETE;
6072       break;
6073     default:
6074       llvm_unreachable("Unexpected map type!");
6075       break;
6076     }
6077     if (AddPtrFlag)
6078       Bits |= OMP_MAP_IS_PTR;
6079     if (AddIsFirstFlag)
6080       Bits |= OMP_MAP_FIRST_REF;
6081     if (MapTypeModifier == OMPC_MAP_always)
6082       Bits |= OMP_MAP_ALWAYS;
6083     return Bits;
6084   }
6085 
6086   /// \brief Return true if the provided expression is a final array section. A
6087   /// final array section, is one whose length can't be proved to be one.
6088   bool isFinalArraySectionExpression(const Expr *E) const {
6089     auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6090 
6091     // It is not an array section and therefore not a unity-size one.
6092     if (!OASE)
6093       return false;
6094 
6095     // An array section with no colon always refer to a single element.
6096     if (OASE->getColonLoc().isInvalid())
6097       return false;
6098 
6099     auto *Length = OASE->getLength();
6100 
6101     // If we don't have a length we have to check if the array has size 1
6102     // for this dimension. Also, we should always expect a length if the
6103     // base type is pointer.
6104     if (!Length) {
6105       auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6106                          OASE->getBase()->IgnoreParenImpCasts())
6107                          .getCanonicalType();
6108       if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6109         return ATy->getSize().getSExtValue() != 1;
6110       // If we don't have a constant dimension length, we have to consider
6111       // the current section as having any size, so it is not necessarily
6112       // unitary. If it happen to be unity size, that's user fault.
6113       return true;
6114     }
6115 
6116     // Check if the length evaluates to 1.
6117     llvm::APSInt ConstLength;
6118     if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6119       return true; // Can have more that size 1.
6120 
6121     return ConstLength.getSExtValue() != 1;
6122   }
6123 
6124   /// \brief Generate the base pointers, section pointers, sizes and map type
6125   /// bits for the provided map type, map modifier, and expression components.
6126   /// \a IsFirstComponent should be set to true if the provided set of
6127   /// components is the first associated with a capture.
6128   void generateInfoForComponentList(
6129       OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6130       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6131       MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
6132       MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6133       bool IsFirstComponentList) const {
6134 
6135     // The following summarizes what has to be generated for each map and the
6136     // types bellow. The generated information is expressed in this order:
6137     // base pointer, section pointer, size, flags
6138     // (to add to the ones that come from the map type and modifier).
6139     //
6140     // double d;
6141     // int i[100];
6142     // float *p;
6143     //
6144     // struct S1 {
6145     //   int i;
6146     //   float f[50];
6147     // }
6148     // struct S2 {
6149     //   int i;
6150     //   float f[50];
6151     //   S1 s;
6152     //   double *p;
6153     //   struct S2 *ps;
6154     // }
6155     // S2 s;
6156     // S2 *ps;
6157     //
6158     // map(d)
6159     // &d, &d, sizeof(double), noflags
6160     //
6161     // map(i)
6162     // &i, &i, 100*sizeof(int), noflags
6163     //
6164     // map(i[1:23])
6165     // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6166     //
6167     // map(p)
6168     // &p, &p, sizeof(float*), noflags
6169     //
6170     // map(p[1:24])
6171     // p, &p[1], 24*sizeof(float), noflags
6172     //
6173     // map(s)
6174     // &s, &s, sizeof(S2), noflags
6175     //
6176     // map(s.i)
6177     // &s, &(s.i), sizeof(int), noflags
6178     //
6179     // map(s.s.f)
6180     // &s, &(s.i.f), 50*sizeof(int), noflags
6181     //
6182     // map(s.p)
6183     // &s, &(s.p), sizeof(double*), noflags
6184     //
6185     // map(s.p[:22], s.a s.b)
6186     // &s, &(s.p), sizeof(double*), noflags
6187     // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6188     //
6189     // map(s.ps)
6190     // &s, &(s.ps), sizeof(S2*), noflags
6191     //
6192     // map(s.ps->s.i)
6193     // &s, &(s.ps), sizeof(S2*), noflags
6194     // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6195     //
6196     // map(s.ps->ps)
6197     // &s, &(s.ps), sizeof(S2*), noflags
6198     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6199     //
6200     // map(s.ps->ps->ps)
6201     // &s, &(s.ps), sizeof(S2*), noflags
6202     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6203     // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6204     //
6205     // map(s.ps->ps->s.f[:22])
6206     // &s, &(s.ps), sizeof(S2*), noflags
6207     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6208     // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6209     //
6210     // map(ps)
6211     // &ps, &ps, sizeof(S2*), noflags
6212     //
6213     // map(ps->i)
6214     // ps, &(ps->i), sizeof(int), noflags
6215     //
6216     // map(ps->s.f)
6217     // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6218     //
6219     // map(ps->p)
6220     // ps, &(ps->p), sizeof(double*), noflags
6221     //
6222     // map(ps->p[:22])
6223     // ps, &(ps->p), sizeof(double*), noflags
6224     // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6225     //
6226     // map(ps->ps)
6227     // ps, &(ps->ps), sizeof(S2*), noflags
6228     //
6229     // map(ps->ps->s.i)
6230     // ps, &(ps->ps), sizeof(S2*), noflags
6231     // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6232     //
6233     // map(ps->ps->ps)
6234     // ps, &(ps->ps), sizeof(S2*), noflags
6235     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6236     //
6237     // map(ps->ps->ps->ps)
6238     // ps, &(ps->ps), sizeof(S2*), noflags
6239     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6240     // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6241     //
6242     // map(ps->ps->ps->s.f[:22])
6243     // ps, &(ps->ps), sizeof(S2*), noflags
6244     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6245     // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6246     // extra_flag
6247 
6248     // Track if the map information being generated is the first for a capture.
6249     bool IsCaptureFirstInfo = IsFirstComponentList;
6250 
6251     // Scan the components from the base to the complete expression.
6252     auto CI = Components.rbegin();
6253     auto CE = Components.rend();
6254     auto I = CI;
6255 
6256     // Track if the map information being generated is the first for a list of
6257     // components.
6258     bool IsExpressionFirstInfo = true;
6259     llvm::Value *BP = nullptr;
6260 
6261     if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6262       // The base is the 'this' pointer. The content of the pointer is going
6263       // to be the base of the field being mapped.
6264       BP = CGF.EmitScalarExpr(ME->getBase());
6265     } else {
6266       // The base is the reference to the variable.
6267       // BP = &Var.
6268       BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6269                .getPointer();
6270 
6271       // If the variable is a pointer and is being dereferenced (i.e. is not
6272       // the last component), the base has to be the pointer itself, not its
6273       // reference. References are ignored for mapping purposes.
6274       QualType Ty =
6275           I->getAssociatedDeclaration()->getType().getNonReferenceType();
6276       if (Ty->isAnyPointerType() && std::next(I) != CE) {
6277         auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
6278         BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
6279                                          Ty->castAs<PointerType>())
6280                  .getPointer();
6281 
6282         // We do not need to generate individual map information for the
6283         // pointer, it can be associated with the combined storage.
6284         ++I;
6285       }
6286     }
6287 
6288     for (; I != CE; ++I) {
6289       auto Next = std::next(I);
6290 
6291       // We need to generate the addresses and sizes if this is the last
6292       // component, if the component is a pointer or if it is an array section
6293       // whose length can't be proved to be one. If this is a pointer, it
6294       // becomes the base address for the following components.
6295 
6296       // A final array section, is one whose length can't be proved to be one.
6297       bool IsFinalArraySection =
6298           isFinalArraySectionExpression(I->getAssociatedExpression());
6299 
6300       // Get information on whether the element is a pointer. Have to do a
6301       // special treatment for array sections given that they are built-in
6302       // types.
6303       const auto *OASE =
6304           dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6305       bool IsPointer =
6306           (OASE &&
6307            OMPArraySectionExpr::getBaseOriginalType(OASE)
6308                .getCanonicalType()
6309                ->isAnyPointerType()) ||
6310           I->getAssociatedExpression()->getType()->isAnyPointerType();
6311 
6312       if (Next == CE || IsPointer || IsFinalArraySection) {
6313 
6314         // If this is not the last component, we expect the pointer to be
6315         // associated with an array expression or member expression.
6316         assert((Next == CE ||
6317                 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6318                 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6319                 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6320                "Unexpected expression");
6321 
6322         auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6323         auto *Size = getExprTypeSize(I->getAssociatedExpression());
6324 
6325         // If we have a member expression and the current component is a
6326         // reference, we have to map the reference too. Whenever we have a
6327         // reference, the section that reference refers to is going to be a
6328         // load instruction from the storage assigned to the reference.
6329         if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6330             I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6331           auto *LI = cast<llvm::LoadInst>(LB);
6332           auto *RefAddr = LI->getPointerOperand();
6333 
6334           BasePointers.push_back(BP);
6335           Pointers.push_back(RefAddr);
6336           Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6337           Types.push_back(getMapTypeBits(
6338               /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6339               !IsExpressionFirstInfo, IsCaptureFirstInfo));
6340           IsExpressionFirstInfo = false;
6341           IsCaptureFirstInfo = false;
6342           // The reference will be the next base address.
6343           BP = RefAddr;
6344         }
6345 
6346         BasePointers.push_back(BP);
6347         Pointers.push_back(LB);
6348         Sizes.push_back(Size);
6349 
6350         // We need to add a pointer flag for each map that comes from the
6351         // same expression except for the first one. We also need to signal
6352         // this map is the first one that relates with the current capture
6353         // (there is a set of entries for each capture).
6354         Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6355                                        !IsExpressionFirstInfo,
6356                                        IsCaptureFirstInfo));
6357 
6358         // If we have a final array section, we are done with this expression.
6359         if (IsFinalArraySection)
6360           break;
6361 
6362         // The pointer becomes the base for the next element.
6363         if (Next != CE)
6364           BP = LB;
6365 
6366         IsExpressionFirstInfo = false;
6367         IsCaptureFirstInfo = false;
6368         continue;
6369       }
6370     }
6371   }
6372 
6373   /// \brief Return the adjusted map modifiers if the declaration a capture
6374   /// refers to appears in a first-private clause. This is expected to be used
6375   /// only with directives that start with 'target'.
6376   unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6377                                                unsigned CurrentModifiers) {
6378     assert(Cap.capturesVariable() && "Expected capture by reference only!");
6379 
6380     // A first private variable captured by reference will use only the
6381     // 'private ptr' and 'map to' flag. Return the right flags if the captured
6382     // declaration is known as first-private in this handler.
6383     if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6384       return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6385              MappableExprsHandler::OMP_MAP_TO;
6386 
6387     // We didn't modify anything.
6388     return CurrentModifiers;
6389   }
6390 
6391 public:
6392   MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6393       : CurDir(Dir), CGF(CGF) {
6394     // Extract firstprivate clause information.
6395     for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6396       for (const auto *D : C->varlists())
6397         FirstPrivateDecls.insert(
6398             cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6399     // Extract device pointer clause information.
6400     for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6401       for (auto L : C->component_lists())
6402         DevPointersMap[L.first].push_back(L.second);
6403   }
6404 
6405   /// \brief Generate all the base pointers, section pointers, sizes and map
6406   /// types for the extracted mappable expressions. Also, for each item that
6407   /// relates with a device pointer, a pair of the relevant declaration and
6408   /// index where it occurs is appended to the device pointers info array.
6409   void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
6410                        MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6411                        MapFlagsArrayTy &Types) const {
6412     BasePointers.clear();
6413     Pointers.clear();
6414     Sizes.clear();
6415     Types.clear();
6416 
6417     struct MapInfo {
6418       /// Kind that defines how a device pointer has to be returned.
6419       enum ReturnPointerKind {
6420         // Don't have to return any pointer.
6421         RPK_None,
6422         // Pointer is the base of the declaration.
6423         RPK_Base,
6424         // Pointer is a member of the base declaration - 'this'
6425         RPK_Member,
6426         // Pointer is a reference and a member of the base declaration - 'this'
6427         RPK_MemberReference,
6428       };
6429       OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6430       OpenMPMapClauseKind MapType;
6431       OpenMPMapClauseKind MapTypeModifier;
6432       ReturnPointerKind ReturnDevicePointer;
6433 
6434       MapInfo()
6435           : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6436             ReturnDevicePointer(RPK_None) {}
6437       MapInfo(
6438           OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6439           OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6440           ReturnPointerKind ReturnDevicePointer)
6441           : Components(Components), MapType(MapType),
6442             MapTypeModifier(MapTypeModifier),
6443             ReturnDevicePointer(ReturnDevicePointer) {}
6444     };
6445 
6446     // We have to process the component lists that relate with the same
6447     // declaration in a single chunk so that we can generate the map flags
6448     // correctly. Therefore, we organize all lists in a map.
6449     llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
6450 
6451     // Helper function to fill the information map for the different supported
6452     // clauses.
6453     auto &&InfoGen = [&Info](
6454         const ValueDecl *D,
6455         OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6456         OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
6457         MapInfo::ReturnPointerKind ReturnDevicePointer) {
6458       const ValueDecl *VD =
6459           D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6460       Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6461     };
6462 
6463     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
6464     for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
6465       for (auto L : C->component_lists())
6466         InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6467                 MapInfo::RPK_None);
6468     for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
6469       for (auto L : C->component_lists())
6470         InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6471                 MapInfo::RPK_None);
6472     for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
6473       for (auto L : C->component_lists())
6474         InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6475                 MapInfo::RPK_None);
6476 
6477     // Look at the use_device_ptr clause information and mark the existing map
6478     // entries as such. If there is no map information for an entry in the
6479     // use_device_ptr list, we create one with map type 'alloc' and zero size
6480     // section. It is the user fault if that was not mapped before.
6481     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
6482     for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
6483       for (auto L : C->component_lists()) {
6484         assert(!L.second.empty() && "Not expecting empty list of components!");
6485         const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6486         VD = cast<ValueDecl>(VD->getCanonicalDecl());
6487         auto *IE = L.second.back().getAssociatedExpression();
6488         // If the first component is a member expression, we have to look into
6489         // 'this', which maps to null in the map of map information. Otherwise
6490         // look directly for the information.
6491         auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6492 
6493         // We potentially have map information for this declaration already.
6494         // Look for the first set of components that refer to it.
6495         if (It != Info.end()) {
6496           auto CI = std::find_if(
6497               It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6498                 return MI.Components.back().getAssociatedDeclaration() == VD;
6499               });
6500           // If we found a map entry, signal that the pointer has to be returned
6501           // and move on to the next declaration.
6502           if (CI != It->second.end()) {
6503             CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6504                                           ? (VD->getType()->isReferenceType()
6505                                                  ? MapInfo::RPK_MemberReference
6506                                                  : MapInfo::RPK_Member)
6507                                           : MapInfo::RPK_Base;
6508             continue;
6509           }
6510         }
6511 
6512         // We didn't find any match in our map information - generate a zero
6513         // size array section.
6514         // FIXME: MSVC 2013 seems to require this-> to find member CGF.
6515         llvm::Value *Ptr =
6516             this->CGF
6517                 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
6518                 .getScalarVal();
6519         BasePointers.push_back({Ptr, VD});
6520         Pointers.push_back(Ptr);
6521         Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
6522         Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6523       }
6524 
6525     for (auto &M : Info) {
6526       // We need to know when we generate information for the first component
6527       // associated with a capture, because the mapping flags depend on it.
6528       bool IsFirstComponentList = true;
6529       for (MapInfo &L : M.second) {
6530         assert(!L.Components.empty() &&
6531                "Not expecting declaration with no component lists.");
6532 
6533         // Remember the current base pointer index.
6534         unsigned CurrentBasePointersIdx = BasePointers.size();
6535         // FIXME: MSVC 2013 seems to require this-> to find the member method.
6536         this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6537                                            L.Components, BasePointers, Pointers,
6538                                            Sizes, Types, IsFirstComponentList);
6539 
6540         // If this entry relates with a device pointer, set the relevant
6541         // declaration and add the 'return pointer' flag.
6542         if (IsFirstComponentList &&
6543             L.ReturnDevicePointer != MapInfo::RPK_None) {
6544           // If the pointer is not the base of the map, we need to skip the
6545           // base. If it is a reference in a member field, we also need to skip
6546           // the map of the reference.
6547           if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6548             ++CurrentBasePointersIdx;
6549             if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6550               ++CurrentBasePointersIdx;
6551           }
6552           assert(BasePointers.size() > CurrentBasePointersIdx &&
6553                  "Unexpected number of mapped base pointers.");
6554 
6555           auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6556           assert(RelevantVD &&
6557                  "No relevant declaration related with device pointer??");
6558 
6559           BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6560           Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6561         }
6562         IsFirstComponentList = false;
6563       }
6564     }
6565   }
6566 
6567   /// \brief Generate the base pointers, section pointers, sizes and map types
6568   /// associated to a given capture.
6569   void generateInfoForCapture(const CapturedStmt::Capture *Cap,
6570                               llvm::Value *Arg,
6571                               MapBaseValuesArrayTy &BasePointers,
6572                               MapValuesArrayTy &Pointers,
6573                               MapValuesArrayTy &Sizes,
6574                               MapFlagsArrayTy &Types) const {
6575     assert(!Cap->capturesVariableArrayType() &&
6576            "Not expecting to generate map info for a variable array type!");
6577 
6578     BasePointers.clear();
6579     Pointers.clear();
6580     Sizes.clear();
6581     Types.clear();
6582 
6583     // We need to know when we generating information for the first component
6584     // associated with a capture, because the mapping flags depend on it.
6585     bool IsFirstComponentList = true;
6586 
6587     const ValueDecl *VD =
6588         Cap->capturesThis()
6589             ? nullptr
6590             : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6591 
6592     // If this declaration appears in a is_device_ptr clause we just have to
6593     // pass the pointer by value. If it is a reference to a declaration, we just
6594     // pass its value, otherwise, if it is a member expression, we need to map
6595     // 'to' the field.
6596     if (!VD) {
6597       auto It = DevPointersMap.find(VD);
6598       if (It != DevPointersMap.end()) {
6599         for (auto L : It->second) {
6600           generateInfoForComponentList(
6601               /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6602               BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6603           IsFirstComponentList = false;
6604         }
6605         return;
6606       }
6607     } else if (DevPointersMap.count(VD)) {
6608       BasePointers.push_back({Arg, VD});
6609       Pointers.push_back(Arg);
6610       Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6611       Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6612       return;
6613     }
6614 
6615     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
6616     for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
6617       for (auto L : C->decl_component_lists(VD)) {
6618         assert(L.first == VD &&
6619                "We got information for the wrong declaration??");
6620         assert(!L.second.empty() &&
6621                "Not expecting declaration with no component lists.");
6622         generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6623                                      L.second, BasePointers, Pointers, Sizes,
6624                                      Types, IsFirstComponentList);
6625         IsFirstComponentList = false;
6626       }
6627 
6628     return;
6629   }
6630 
6631   /// \brief Generate the default map information for a given capture \a CI,
6632   /// record field declaration \a RI and captured value \a CV.
6633   void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6634                               const FieldDecl &RI, llvm::Value *CV,
6635                               MapBaseValuesArrayTy &CurBasePointers,
6636                               MapValuesArrayTy &CurPointers,
6637                               MapValuesArrayTy &CurSizes,
6638                               MapFlagsArrayTy &CurMapTypes) {
6639 
6640     // Do the default mapping.
6641     if (CI.capturesThis()) {
6642       CurBasePointers.push_back(CV);
6643       CurPointers.push_back(CV);
6644       const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6645       CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6646       // Default map type.
6647       CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
6648     } else if (CI.capturesVariableByCopy()) {
6649       CurBasePointers.push_back(CV);
6650       CurPointers.push_back(CV);
6651       if (!RI.getType()->isAnyPointerType()) {
6652         // We have to signal to the runtime captures passed by value that are
6653         // not pointers.
6654         CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
6655         CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6656       } else {
6657         // Pointers are implicitly mapped with a zero size and no flags
6658         // (other than first map that is added for all implicit maps).
6659         CurMapTypes.push_back(0u);
6660         CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6661       }
6662     } else {
6663       assert(CI.capturesVariable() && "Expected captured reference.");
6664       CurBasePointers.push_back(CV);
6665       CurPointers.push_back(CV);
6666 
6667       const ReferenceType *PtrTy =
6668           cast<ReferenceType>(RI.getType().getTypePtr());
6669       QualType ElementType = PtrTy->getPointeeType();
6670       CurSizes.push_back(CGF.getTypeSize(ElementType));
6671       // The default map type for a scalar/complex type is 'to' because by
6672       // default the value doesn't have to be retrieved. For an aggregate
6673       // type, the default is 'tofrom'.
6674       CurMapTypes.push_back(ElementType->isAggregateType()
6675                                 ? (OMP_MAP_TO | OMP_MAP_FROM)
6676                                 : OMP_MAP_TO);
6677 
6678       // If we have a capture by reference we may need to add the private
6679       // pointer flag if the base declaration shows in some first-private
6680       // clause.
6681       CurMapTypes.back() =
6682           adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6683     }
6684     // Every default map produces a single argument, so, it is always the
6685     // first one.
6686     CurMapTypes.back() |= OMP_MAP_FIRST_REF;
6687   }
6688 };
6689 
6690 enum OpenMPOffloadingReservedDeviceIDs {
6691   /// \brief Device ID if the device was not defined, runtime should get it
6692   /// from environment variables in the spec.
6693   OMP_DEVICEID_UNDEF = -1,
6694 };
6695 } // anonymous namespace
6696 
6697 /// \brief Emit the arrays used to pass the captures and map information to the
6698 /// offloading runtime library. If there is no map or capture information,
6699 /// return nullptr by reference.
6700 static void
6701 emitOffloadingArrays(CodeGenFunction &CGF,
6702                      MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
6703                      MappableExprsHandler::MapValuesArrayTy &Pointers,
6704                      MappableExprsHandler::MapValuesArrayTy &Sizes,
6705                      MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6706                      CGOpenMPRuntime::TargetDataInfo &Info) {
6707   auto &CGM = CGF.CGM;
6708   auto &Ctx = CGF.getContext();
6709 
6710   // Reset the array information.
6711   Info.clearArrayInfo();
6712   Info.NumberOfPtrs = BasePointers.size();
6713 
6714   if (Info.NumberOfPtrs) {
6715     // Detect if we have any capture size requiring runtime evaluation of the
6716     // size so that a constant array could be eventually used.
6717     bool hasRuntimeEvaluationCaptureSize = false;
6718     for (auto *S : Sizes)
6719       if (!isa<llvm::Constant>(S)) {
6720         hasRuntimeEvaluationCaptureSize = true;
6721         break;
6722       }
6723 
6724     llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
6725     QualType PointerArrayType =
6726         Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6727                                  /*IndexTypeQuals=*/0);
6728 
6729     Info.BasePointersArray =
6730         CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
6731     Info.PointersArray =
6732         CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6733 
6734     // If we don't have any VLA types or other types that require runtime
6735     // evaluation, we can use a constant array for the map sizes, otherwise we
6736     // need to fill up the arrays as we do for the pointers.
6737     if (hasRuntimeEvaluationCaptureSize) {
6738       QualType SizeArrayType = Ctx.getConstantArrayType(
6739           Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6740           /*IndexTypeQuals=*/0);
6741       Info.SizesArray =
6742           CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6743     } else {
6744       // We expect all the sizes to be constant, so we collect them to create
6745       // a constant array.
6746       SmallVector<llvm::Constant *, 16> ConstSizes;
6747       for (auto S : Sizes)
6748         ConstSizes.push_back(cast<llvm::Constant>(S));
6749 
6750       auto *SizesArrayInit = llvm::ConstantArray::get(
6751           llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6752       auto *SizesArrayGbl = new llvm::GlobalVariable(
6753           CGM.getModule(), SizesArrayInit->getType(),
6754           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6755           SizesArrayInit, ".offload_sizes");
6756       SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6757       Info.SizesArray = SizesArrayGbl;
6758     }
6759 
6760     // The map types are always constant so we don't need to generate code to
6761     // fill arrays. Instead, we create an array constant.
6762     llvm::Constant *MapTypesArrayInit =
6763         llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6764     auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6765         CGM.getModule(), MapTypesArrayInit->getType(),
6766         /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6767         MapTypesArrayInit, ".offload_maptypes");
6768     MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6769     Info.MapTypesArray = MapTypesArrayGbl;
6770 
6771     for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6772       llvm::Value *BPVal = *BasePointers[i];
6773       llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
6774           llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6775           Info.BasePointersArray, 0, i);
6776       BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6777           BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
6778       Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6779       CGF.Builder.CreateStore(BPVal, BPAddr);
6780 
6781       if (Info.requiresDevicePointerInfo())
6782         if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6783           Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6784 
6785       llvm::Value *PVal = Pointers[i];
6786       llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
6787           llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6788           Info.PointersArray, 0, i);
6789       P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6790           P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
6791       Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6792       CGF.Builder.CreateStore(PVal, PAddr);
6793 
6794       if (hasRuntimeEvaluationCaptureSize) {
6795         llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
6796             llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6797             Info.SizesArray,
6798             /*Idx0=*/0,
6799             /*Idx1=*/i);
6800         Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6801         CGF.Builder.CreateStore(
6802             CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6803             SAddr);
6804       }
6805     }
6806   }
6807 }
6808 /// \brief Emit the arguments to be passed to the runtime library based on the
6809 /// arrays of pointers, sizes and map types.
6810 static void emitOffloadingArraysArgument(
6811     CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6812     llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
6813     llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
6814   auto &CGM = CGF.CGM;
6815   if (Info.NumberOfPtrs) {
6816     BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
6817         llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6818         Info.BasePointersArray,
6819         /*Idx0=*/0, /*Idx1=*/0);
6820     PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
6821         llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6822         Info.PointersArray,
6823         /*Idx0=*/0,
6824         /*Idx1=*/0);
6825     SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
6826         llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
6827         /*Idx0=*/0, /*Idx1=*/0);
6828     MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
6829         llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6830         Info.MapTypesArray,
6831         /*Idx0=*/0,
6832         /*Idx1=*/0);
6833   } else {
6834     BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6835     PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6836     SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6837     MapTypesArrayArg =
6838         llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6839   }
6840 }
6841 
6842 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6843                                      const OMPExecutableDirective &D,
6844                                      llvm::Value *OutlinedFn,
6845                                      llvm::Value *OutlinedFnID,
6846                                      const Expr *IfCond, const Expr *Device,
6847                                      ArrayRef<llvm::Value *> CapturedVars) {
6848   if (!CGF.HaveInsertPoint())
6849     return;
6850 
6851   assert(OutlinedFn && "Invalid outlined function!");
6852 
6853   auto &Ctx = CGF.getContext();
6854 
6855   // Fill up the arrays with all the captured variables.
6856   MappableExprsHandler::MapValuesArrayTy KernelArgs;
6857   MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
6858   MappableExprsHandler::MapValuesArrayTy Pointers;
6859   MappableExprsHandler::MapValuesArrayTy Sizes;
6860   MappableExprsHandler::MapFlagsArrayTy MapTypes;
6861 
6862   MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
6863   MappableExprsHandler::MapValuesArrayTy CurPointers;
6864   MappableExprsHandler::MapValuesArrayTy CurSizes;
6865   MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6866 
6867   // Get mappable expression information.
6868   MappableExprsHandler MEHandler(D, CGF);
6869 
6870   const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6871   auto RI = CS.getCapturedRecordDecl()->field_begin();
6872   auto CV = CapturedVars.begin();
6873   for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6874                                             CE = CS.capture_end();
6875        CI != CE; ++CI, ++RI, ++CV) {
6876     StringRef Name;
6877     QualType Ty;
6878 
6879     CurBasePointers.clear();
6880     CurPointers.clear();
6881     CurSizes.clear();
6882     CurMapTypes.clear();
6883 
6884     // VLA sizes are passed to the outlined region by copy and do not have map
6885     // information associated.
6886     if (CI->capturesVariableArrayType()) {
6887       CurBasePointers.push_back(*CV);
6888       CurPointers.push_back(*CV);
6889       CurSizes.push_back(CGF.getTypeSize(RI->getType()));
6890       // Copy to the device as an argument. No need to retrieve it.
6891       CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6892                             MappableExprsHandler::OMP_MAP_FIRST_REF);
6893     } else {
6894       // If we have any information in the map clause, we use it, otherwise we
6895       // just do a default mapping.
6896       MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
6897                                        CurSizes, CurMapTypes);
6898       if (CurBasePointers.empty())
6899         MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6900                                          CurPointers, CurSizes, CurMapTypes);
6901     }
6902     // We expect to have at least an element of information for this capture.
6903     assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6904     assert(CurBasePointers.size() == CurPointers.size() &&
6905            CurBasePointers.size() == CurSizes.size() &&
6906            CurBasePointers.size() == CurMapTypes.size() &&
6907            "Inconsistent map information sizes!");
6908 
6909     // The kernel args are always the first elements of the base pointers
6910     // associated with a capture.
6911     KernelArgs.push_back(*CurBasePointers.front());
6912     // We need to append the results of this capture to what we already have.
6913     BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6914     Pointers.append(CurPointers.begin(), CurPointers.end());
6915     Sizes.append(CurSizes.begin(), CurSizes.end());
6916     MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
6917   }
6918 
6919   // Keep track on whether the host function has to be executed.
6920   auto OffloadErrorQType =
6921       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
6922   auto OffloadError = CGF.MakeAddrLValue(
6923       CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6924       OffloadErrorQType);
6925   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6926                         OffloadError);
6927 
6928   // Fill up the pointer arrays and transfer execution to the device.
6929   auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6930                     OutlinedFnID, OffloadError,
6931                     &D](CodeGenFunction &CGF, PrePostActionTy &) {
6932     auto &RT = CGF.CGM.getOpenMPRuntime();
6933     // Emit the offloading arrays.
6934     TargetDataInfo Info;
6935     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6936     emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6937                                  Info.PointersArray, Info.SizesArray,
6938                                  Info.MapTypesArray, Info);
6939 
6940     // On top of the arrays that were filled up, the target offloading call
6941     // takes as arguments the device id as well as the host pointer. The host
6942     // pointer is used by the runtime library to identify the current target
6943     // region, so it only has to be unique and not necessarily point to
6944     // anything. It could be the pointer to the outlined function that
6945     // implements the target region, but we aren't using that so that the
6946     // compiler doesn't need to keep that, and could therefore inline the host
6947     // function if proven worthwhile during optimization.
6948 
6949     // From this point on, we need to have an ID of the target region defined.
6950     assert(OutlinedFnID && "Invalid outlined function ID!");
6951 
6952     // Emit device ID if any.
6953     llvm::Value *DeviceID;
6954     if (Device)
6955       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6956                                            CGF.Int32Ty, /*isSigned=*/true);
6957     else
6958       DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6959 
6960     // Emit the number of elements in the offloading arrays.
6961     llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6962 
6963     // Return value of the runtime offloading call.
6964     llvm::Value *Return;
6965 
6966     auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6967     auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
6968 
6969     // The target region is an outlined function launched by the runtime
6970     // via calls __tgt_target() or __tgt_target_teams().
6971     //
6972     // __tgt_target() launches a target region with one team and one thread,
6973     // executing a serial region.  This master thread may in turn launch
6974     // more threads within its team upon encountering a parallel region,
6975     // however, no additional teams can be launched on the device.
6976     //
6977     // __tgt_target_teams() launches a target region with one or more teams,
6978     // each with one or more threads.  This call is required for target
6979     // constructs such as:
6980     //  'target teams'
6981     //  'target' / 'teams'
6982     //  'target teams distribute parallel for'
6983     //  'target parallel'
6984     // and so on.
6985     //
6986     // Note that on the host and CPU targets, the runtime implementation of
6987     // these calls simply call the outlined function without forking threads.
6988     // The outlined functions themselves have runtime calls to
6989     // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6990     // the compiler in emitTeamsCall() and emitParallelCall().
6991     //
6992     // In contrast, on the NVPTX target, the implementation of
6993     // __tgt_target_teams() launches a GPU kernel with the requested number
6994     // of teams and threads so no additional calls to the runtime are required.
6995     if (NumTeams) {
6996       // If we have NumTeams defined this means that we have an enclosed teams
6997       // region. Therefore we also expect to have NumThreads defined. These two
6998       // values should be defined in the presence of a teams directive,
6999       // regardless of having any clauses associated. If the user is using teams
7000       // but no clauses, these two values will be the default that should be
7001       // passed to the runtime library - a 32-bit integer with the value zero.
7002       assert(NumThreads && "Thread limit expression should be available along "
7003                            "with number of teams.");
7004       llvm::Value *OffloadingArgs[] = {
7005           DeviceID,           OutlinedFnID,
7006           PointerNum,         Info.BasePointersArray,
7007           Info.PointersArray, Info.SizesArray,
7008           Info.MapTypesArray, NumTeams,
7009           NumThreads};
7010       Return = CGF.EmitRuntimeCall(
7011           RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
7012     } else {
7013       llvm::Value *OffloadingArgs[] = {
7014           DeviceID,           OutlinedFnID,
7015           PointerNum,         Info.BasePointersArray,
7016           Info.PointersArray, Info.SizesArray,
7017           Info.MapTypesArray};
7018       Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
7019                                    OffloadingArgs);
7020     }
7021 
7022     CGF.EmitStoreOfScalar(Return, OffloadError);
7023   };
7024 
7025   // Notify that the host version must be executed.
7026   auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7027     CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
7028                           OffloadError);
7029   };
7030 
7031   // If we have a target function ID it means that we need to support
7032   // offloading, otherwise, just execute on the host. We need to execute on host
7033   // regardless of the conditional in the if clause if, e.g., the user do not
7034   // specify target triples.
7035   if (OutlinedFnID) {
7036     if (IfCond)
7037       emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7038     else {
7039       RegionCodeGenTy ThenRCG(ThenGen);
7040       ThenRCG(CGF);
7041     }
7042   } else {
7043     RegionCodeGenTy ElseRCG(ElseGen);
7044     ElseRCG(CGF);
7045   }
7046 
7047   // Check the error code and execute the host version if required.
7048   auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7049   auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7050   auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7051   auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7052   CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7053 
7054   CGF.EmitBlock(OffloadFailedBlock);
7055   emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7056   CGF.EmitBranch(OffloadContBlock);
7057 
7058   CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
7059 }
7060 
7061 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7062                                                     StringRef ParentName) {
7063   if (!S)
7064     return;
7065 
7066   // Codegen OMP target directives that offload compute to the device.
7067   bool requiresDeviceCodegen =
7068       isa<OMPExecutableDirective>(S) &&
7069       isOpenMPTargetExecutionDirective(
7070           cast<OMPExecutableDirective>(S)->getDirectiveKind());
7071 
7072   if (requiresDeviceCodegen) {
7073     auto &E = *cast<OMPExecutableDirective>(S);
7074     unsigned DeviceID;
7075     unsigned FileID;
7076     unsigned Line;
7077     getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
7078                              FileID, Line);
7079 
7080     // Is this a target region that should not be emitted as an entry point? If
7081     // so just signal we are done with this target region.
7082     if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7083                                                             ParentName, Line))
7084       return;
7085 
7086     switch (S->getStmtClass()) {
7087     case Stmt::OMPTargetDirectiveClass:
7088       CodeGenFunction::EmitOMPTargetDeviceFunction(
7089           CGM, ParentName, cast<OMPTargetDirective>(*S));
7090       break;
7091     case Stmt::OMPTargetParallelDirectiveClass:
7092       CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7093           CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7094       break;
7095     case Stmt::OMPTargetTeamsDirectiveClass:
7096       CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7097           CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7098       break;
7099     default:
7100       llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7101     }
7102     return;
7103   }
7104 
7105   if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
7106     if (!E->hasAssociatedStmt())
7107       return;
7108 
7109     scanForTargetRegionsFunctions(
7110         cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7111         ParentName);
7112     return;
7113   }
7114 
7115   // If this is a lambda function, look into its body.
7116   if (auto *L = dyn_cast<LambdaExpr>(S))
7117     S = L->getBody();
7118 
7119   // Keep looking for target regions recursively.
7120   for (auto *II : S->children())
7121     scanForTargetRegionsFunctions(II, ParentName);
7122 }
7123 
7124 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7125   auto &FD = *cast<FunctionDecl>(GD.getDecl());
7126 
7127   // If emitting code for the host, we do not process FD here. Instead we do
7128   // the normal code generation.
7129   if (!CGM.getLangOpts().OpenMPIsDevice)
7130     return false;
7131 
7132   // Try to detect target regions in the function.
7133   scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7134 
7135   // We should not emit any function other that the ones created during the
7136   // scanning. Therefore, we signal that this function is completely dealt
7137   // with.
7138   return true;
7139 }
7140 
7141 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7142   if (!CGM.getLangOpts().OpenMPIsDevice)
7143     return false;
7144 
7145   // Check if there are Ctors/Dtors in this declaration and look for target
7146   // regions in it. We use the complete variant to produce the kernel name
7147   // mangling.
7148   QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7149   if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7150     for (auto *Ctor : RD->ctors()) {
7151       StringRef ParentName =
7152           CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7153       scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7154     }
7155     auto *Dtor = RD->getDestructor();
7156     if (Dtor) {
7157       StringRef ParentName =
7158           CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7159       scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7160     }
7161   }
7162 
7163   // If we are in target mode, we do not emit any global (declare target is not
7164   // implemented yet). Therefore we signal that GD was processed in this case.
7165   return true;
7166 }
7167 
7168 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7169   auto *VD = GD.getDecl();
7170   if (isa<FunctionDecl>(VD))
7171     return emitTargetFunctions(GD);
7172 
7173   return emitTargetGlobalVariable(GD);
7174 }
7175 
7176 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7177   // If we have offloading in the current module, we need to emit the entries
7178   // now and register the offloading descriptor.
7179   createOffloadEntriesAndInfoMetadata();
7180 
7181   // Create and register the offloading binary descriptors. This is the main
7182   // entity that captures all the information about offloading in the current
7183   // compilation unit.
7184   return createOffloadingBinaryDescriptorRegistration();
7185 }
7186 
7187 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7188                                     const OMPExecutableDirective &D,
7189                                     SourceLocation Loc,
7190                                     llvm::Value *OutlinedFn,
7191                                     ArrayRef<llvm::Value *> CapturedVars) {
7192   if (!CGF.HaveInsertPoint())
7193     return;
7194 
7195   auto *RTLoc = emitUpdateLocation(CGF, Loc);
7196   CodeGenFunction::RunCleanupsScope Scope(CGF);
7197 
7198   // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7199   llvm::Value *Args[] = {
7200       RTLoc,
7201       CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7202       CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7203   llvm::SmallVector<llvm::Value *, 16> RealArgs;
7204   RealArgs.append(std::begin(Args), std::end(Args));
7205   RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7206 
7207   auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7208   CGF.EmitRuntimeCall(RTLFn, RealArgs);
7209 }
7210 
7211 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
7212                                          const Expr *NumTeams,
7213                                          const Expr *ThreadLimit,
7214                                          SourceLocation Loc) {
7215   if (!CGF.HaveInsertPoint())
7216     return;
7217 
7218   auto *RTLoc = emitUpdateLocation(CGF, Loc);
7219 
7220   llvm::Value *NumTeamsVal =
7221       (NumTeams)
7222           ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7223                                       CGF.CGM.Int32Ty, /* isSigned = */ true)
7224           : CGF.Builder.getInt32(0);
7225 
7226   llvm::Value *ThreadLimitVal =
7227       (ThreadLimit)
7228           ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7229                                       CGF.CGM.Int32Ty, /* isSigned = */ true)
7230           : CGF.Builder.getInt32(0);
7231 
7232   // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
7233   llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7234                                      ThreadLimitVal};
7235   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7236                       PushNumTeamsArgs);
7237 }
7238 
7239 void CGOpenMPRuntime::emitTargetDataCalls(
7240     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7241     const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
7242   if (!CGF.HaveInsertPoint())
7243     return;
7244 
7245   // Action used to replace the default codegen action and turn privatization
7246   // off.
7247   PrePostActionTy NoPrivAction;
7248 
7249   // Generate the code for the opening of the data environment. Capture all the
7250   // arguments of the runtime call by reference because they are used in the
7251   // closing of the region.
7252   auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7253                                                       PrePostActionTy &) {
7254     // Fill up the arrays with all the mapped variables.
7255     MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7256     MappableExprsHandler::MapValuesArrayTy Pointers;
7257     MappableExprsHandler::MapValuesArrayTy Sizes;
7258     MappableExprsHandler::MapFlagsArrayTy MapTypes;
7259 
7260     // Get map clause information.
7261     MappableExprsHandler MCHandler(D, CGF);
7262     MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7263 
7264     // Fill up the arrays and create the arguments.
7265     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7266 
7267     llvm::Value *BasePointersArrayArg = nullptr;
7268     llvm::Value *PointersArrayArg = nullptr;
7269     llvm::Value *SizesArrayArg = nullptr;
7270     llvm::Value *MapTypesArrayArg = nullptr;
7271     emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
7272                                  SizesArrayArg, MapTypesArrayArg, Info);
7273 
7274     // Emit device ID if any.
7275     llvm::Value *DeviceID = nullptr;
7276     if (Device)
7277       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7278                                            CGF.Int32Ty, /*isSigned=*/true);
7279     else
7280       DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7281 
7282     // Emit the number of elements in the offloading arrays.
7283     auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
7284 
7285     llvm::Value *OffloadingArgs[] = {
7286         DeviceID,         PointerNum,    BasePointersArrayArg,
7287         PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7288     auto &RT = CGF.CGM.getOpenMPRuntime();
7289     CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7290                         OffloadingArgs);
7291 
7292     // If device pointer privatization is required, emit the body of the region
7293     // here. It will have to be duplicated: with and without privatization.
7294     if (!Info.CaptureDeviceAddrMap.empty())
7295       CodeGen(CGF);
7296   };
7297 
7298   // Generate code for the closing of the data region.
7299   auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
7300     assert(Info.isValid() && "Invalid data environment closing arguments.");
7301 
7302     llvm::Value *BasePointersArrayArg = nullptr;
7303     llvm::Value *PointersArrayArg = nullptr;
7304     llvm::Value *SizesArrayArg = nullptr;
7305     llvm::Value *MapTypesArrayArg = nullptr;
7306     emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
7307                                  SizesArrayArg, MapTypesArrayArg, Info);
7308 
7309     // Emit device ID if any.
7310     llvm::Value *DeviceID = nullptr;
7311     if (Device)
7312       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7313                                            CGF.Int32Ty, /*isSigned=*/true);
7314     else
7315       DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7316 
7317     // Emit the number of elements in the offloading arrays.
7318     auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
7319 
7320     llvm::Value *OffloadingArgs[] = {
7321         DeviceID,         PointerNum,    BasePointersArrayArg,
7322         PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7323     auto &RT = CGF.CGM.getOpenMPRuntime();
7324     CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7325                         OffloadingArgs);
7326   };
7327 
7328   // If we need device pointer privatization, we need to emit the body of the
7329   // region with no privatization in the 'else' branch of the conditional.
7330   // Otherwise, we don't have to do anything.
7331   auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7332                                                          PrePostActionTy &) {
7333     if (!Info.CaptureDeviceAddrMap.empty()) {
7334       CodeGen.setAction(NoPrivAction);
7335       CodeGen(CGF);
7336     }
7337   };
7338 
7339   // We don't have to do anything to close the region if the if clause evaluates
7340   // to false.
7341   auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7342 
7343   if (IfCond) {
7344     emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
7345   } else {
7346     RegionCodeGenTy RCG(BeginThenGen);
7347     RCG(CGF);
7348   }
7349 
7350   // If we don't require privatization of device pointers, we emit the body in
7351   // between the runtime calls. This avoids duplicating the body code.
7352   if (Info.CaptureDeviceAddrMap.empty()) {
7353     CodeGen.setAction(NoPrivAction);
7354     CodeGen(CGF);
7355   }
7356 
7357   if (IfCond) {
7358     emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
7359   } else {
7360     RegionCodeGenTy RCG(EndThenGen);
7361     RCG(CGF);
7362   }
7363 }
7364 
7365 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
7366     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7367     const Expr *Device) {
7368   if (!CGF.HaveInsertPoint())
7369     return;
7370 
7371   assert((isa<OMPTargetEnterDataDirective>(D) ||
7372           isa<OMPTargetExitDataDirective>(D) ||
7373           isa<OMPTargetUpdateDirective>(D)) &&
7374          "Expecting either target enter, exit data, or update directives.");
7375 
7376   // Generate the code for the opening of the data environment.
7377   auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
7378     // Fill up the arrays with all the mapped variables.
7379     MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7380     MappableExprsHandler::MapValuesArrayTy Pointers;
7381     MappableExprsHandler::MapValuesArrayTy Sizes;
7382     MappableExprsHandler::MapFlagsArrayTy MapTypes;
7383 
7384     // Get map clause information.
7385     MappableExprsHandler MEHandler(D, CGF);
7386     MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7387 
7388     // Fill up the arrays and create the arguments.
7389     TargetDataInfo Info;
7390     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7391     emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7392                                  Info.PointersArray, Info.SizesArray,
7393                                  Info.MapTypesArray, Info);
7394 
7395     // Emit device ID if any.
7396     llvm::Value *DeviceID = nullptr;
7397     if (Device)
7398       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7399                                            CGF.Int32Ty, /*isSigned=*/true);
7400     else
7401       DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7402 
7403     // Emit the number of elements in the offloading arrays.
7404     auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7405 
7406     llvm::Value *OffloadingArgs[] = {
7407         DeviceID,           PointerNum,      Info.BasePointersArray,
7408         Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
7409 
7410     auto &RT = CGF.CGM.getOpenMPRuntime();
7411     // Select the right runtime function call for each expected standalone
7412     // directive.
7413     OpenMPRTLFunction RTLFn;
7414     switch (D.getDirectiveKind()) {
7415     default:
7416       llvm_unreachable("Unexpected standalone target data directive.");
7417       break;
7418     case OMPD_target_enter_data:
7419       RTLFn = OMPRTL__tgt_target_data_begin;
7420       break;
7421     case OMPD_target_exit_data:
7422       RTLFn = OMPRTL__tgt_target_data_end;
7423       break;
7424     case OMPD_target_update:
7425       RTLFn = OMPRTL__tgt_target_data_update;
7426       break;
7427     }
7428     CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
7429   };
7430 
7431   // In the event we get an if clause, we don't have to take any action on the
7432   // else side.
7433   auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7434 
7435   if (IfCond) {
7436     emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7437   } else {
7438     RegionCodeGenTy ThenGenRCG(ThenGen);
7439     ThenGenRCG(CGF);
7440   }
7441 }
7442 
7443 namespace {
7444   /// Kind of parameter in a function with 'declare simd' directive.
7445   enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7446   /// Attribute set of the parameter.
7447   struct ParamAttrTy {
7448     ParamKindTy Kind = Vector;
7449     llvm::APSInt StrideOrArg;
7450     llvm::APSInt Alignment;
7451   };
7452 } // namespace
7453 
7454 static unsigned evaluateCDTSize(const FunctionDecl *FD,
7455                                 ArrayRef<ParamAttrTy> ParamAttrs) {
7456   // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7457   // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7458   // of that clause. The VLEN value must be power of 2.
7459   // In other case the notion of the function`s "characteristic data type" (CDT)
7460   // is used to compute the vector length.
7461   // CDT is defined in the following order:
7462   //   a) For non-void function, the CDT is the return type.
7463   //   b) If the function has any non-uniform, non-linear parameters, then the
7464   //   CDT is the type of the first such parameter.
7465   //   c) If the CDT determined by a) or b) above is struct, union, or class
7466   //   type which is pass-by-value (except for the type that maps to the
7467   //   built-in complex data type), the characteristic data type is int.
7468   //   d) If none of the above three cases is applicable, the CDT is int.
7469   // The VLEN is then determined based on the CDT and the size of vector
7470   // register of that ISA for which current vector version is generated. The
7471   // VLEN is computed using the formula below:
7472   //   VLEN  = sizeof(vector_register) / sizeof(CDT),
7473   // where vector register size specified in section 3.2.1 Registers and the
7474   // Stack Frame of original AMD64 ABI document.
7475   QualType RetType = FD->getReturnType();
7476   if (RetType.isNull())
7477     return 0;
7478   ASTContext &C = FD->getASTContext();
7479   QualType CDT;
7480   if (!RetType.isNull() && !RetType->isVoidType())
7481     CDT = RetType;
7482   else {
7483     unsigned Offset = 0;
7484     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7485       if (ParamAttrs[Offset].Kind == Vector)
7486         CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7487       ++Offset;
7488     }
7489     if (CDT.isNull()) {
7490       for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7491         if (ParamAttrs[I + Offset].Kind == Vector) {
7492           CDT = FD->getParamDecl(I)->getType();
7493           break;
7494         }
7495       }
7496     }
7497   }
7498   if (CDT.isNull())
7499     CDT = C.IntTy;
7500   CDT = CDT->getCanonicalTypeUnqualified();
7501   if (CDT->isRecordType() || CDT->isUnionType())
7502     CDT = C.IntTy;
7503   return C.getTypeSize(CDT);
7504 }
7505 
7506 static void
7507 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
7508                            const llvm::APSInt &VLENVal,
7509                            ArrayRef<ParamAttrTy> ParamAttrs,
7510                            OMPDeclareSimdDeclAttr::BranchStateTy State) {
7511   struct ISADataTy {
7512     char ISA;
7513     unsigned VecRegSize;
7514   };
7515   ISADataTy ISAData[] = {
7516       {
7517           'b', 128
7518       }, // SSE
7519       {
7520           'c', 256
7521       }, // AVX
7522       {
7523           'd', 256
7524       }, // AVX2
7525       {
7526           'e', 512
7527       }, // AVX512
7528   };
7529   llvm::SmallVector<char, 2> Masked;
7530   switch (State) {
7531   case OMPDeclareSimdDeclAttr::BS_Undefined:
7532     Masked.push_back('N');
7533     Masked.push_back('M');
7534     break;
7535   case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7536     Masked.push_back('N');
7537     break;
7538   case OMPDeclareSimdDeclAttr::BS_Inbranch:
7539     Masked.push_back('M');
7540     break;
7541   }
7542   for (auto Mask : Masked) {
7543     for (auto &Data : ISAData) {
7544       SmallString<256> Buffer;
7545       llvm::raw_svector_ostream Out(Buffer);
7546       Out << "_ZGV" << Data.ISA << Mask;
7547       if (!VLENVal) {
7548         Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7549                                          evaluateCDTSize(FD, ParamAttrs));
7550       } else
7551         Out << VLENVal;
7552       for (auto &ParamAttr : ParamAttrs) {
7553         switch (ParamAttr.Kind){
7554         case LinearWithVarStride:
7555           Out << 's' << ParamAttr.StrideOrArg;
7556           break;
7557         case Linear:
7558           Out << 'l';
7559           if (!!ParamAttr.StrideOrArg)
7560             Out << ParamAttr.StrideOrArg;
7561           break;
7562         case Uniform:
7563           Out << 'u';
7564           break;
7565         case Vector:
7566           Out << 'v';
7567           break;
7568         }
7569         if (!!ParamAttr.Alignment)
7570           Out << 'a' << ParamAttr.Alignment;
7571       }
7572       Out << '_' << Fn->getName();
7573       Fn->addFnAttr(Out.str());
7574     }
7575   }
7576 }
7577 
7578 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7579                                               llvm::Function *Fn) {
7580   ASTContext &C = CGM.getContext();
7581   FD = FD->getCanonicalDecl();
7582   // Map params to their positions in function decl.
7583   llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7584   if (isa<CXXMethodDecl>(FD))
7585     ParamPositions.insert({FD, 0});
7586   unsigned ParamPos = ParamPositions.size();
7587   for (auto *P : FD->parameters()) {
7588     ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7589     ++ParamPos;
7590   }
7591   for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7592     llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7593     // Mark uniform parameters.
7594     for (auto *E : Attr->uniforms()) {
7595       E = E->IgnoreParenImpCasts();
7596       unsigned Pos;
7597       if (isa<CXXThisExpr>(E))
7598         Pos = ParamPositions[FD];
7599       else {
7600         auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7601                         ->getCanonicalDecl();
7602         Pos = ParamPositions[PVD];
7603       }
7604       ParamAttrs[Pos].Kind = Uniform;
7605     }
7606     // Get alignment info.
7607     auto NI = Attr->alignments_begin();
7608     for (auto *E : Attr->aligneds()) {
7609       E = E->IgnoreParenImpCasts();
7610       unsigned Pos;
7611       QualType ParmTy;
7612       if (isa<CXXThisExpr>(E)) {
7613         Pos = ParamPositions[FD];
7614         ParmTy = E->getType();
7615       } else {
7616         auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7617                         ->getCanonicalDecl();
7618         Pos = ParamPositions[PVD];
7619         ParmTy = PVD->getType();
7620       }
7621       ParamAttrs[Pos].Alignment =
7622           (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7623                 : llvm::APSInt::getUnsigned(
7624                       C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7625                           .getQuantity());
7626       ++NI;
7627     }
7628     // Mark linear parameters.
7629     auto SI = Attr->steps_begin();
7630     auto MI = Attr->modifiers_begin();
7631     for (auto *E : Attr->linears()) {
7632       E = E->IgnoreParenImpCasts();
7633       unsigned Pos;
7634       if (isa<CXXThisExpr>(E))
7635         Pos = ParamPositions[FD];
7636       else {
7637         auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7638                         ->getCanonicalDecl();
7639         Pos = ParamPositions[PVD];
7640       }
7641       auto &ParamAttr = ParamAttrs[Pos];
7642       ParamAttr.Kind = Linear;
7643       if (*SI) {
7644         if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7645                                   Expr::SE_AllowSideEffects)) {
7646           if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7647             if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7648               ParamAttr.Kind = LinearWithVarStride;
7649               ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7650                   ParamPositions[StridePVD->getCanonicalDecl()]);
7651             }
7652           }
7653         }
7654       }
7655       ++SI;
7656       ++MI;
7657     }
7658     llvm::APSInt VLENVal;
7659     if (const Expr *VLEN = Attr->getSimdlen())
7660       VLENVal = VLEN->EvaluateKnownConstInt(C);
7661     OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7662     if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7663         CGM.getTriple().getArch() == llvm::Triple::x86_64)
7664       emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7665   }
7666 }
7667 
7668 namespace {
7669 /// Cleanup action for doacross support.
7670 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7671 public:
7672   static const int DoacrossFinArgs = 2;
7673 
7674 private:
7675   llvm::Value *RTLFn;
7676   llvm::Value *Args[DoacrossFinArgs];
7677 
7678 public:
7679   DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7680       : RTLFn(RTLFn) {
7681     assert(CallArgs.size() == DoacrossFinArgs);
7682     std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7683   }
7684   void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7685     if (!CGF.HaveInsertPoint())
7686       return;
7687     CGF.EmitRuntimeCall(RTLFn, Args);
7688   }
7689 };
7690 } // namespace
7691 
7692 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7693                                        const OMPLoopDirective &D) {
7694   if (!CGF.HaveInsertPoint())
7695     return;
7696 
7697   ASTContext &C = CGM.getContext();
7698   QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7699   RecordDecl *RD;
7700   if (KmpDimTy.isNull()) {
7701     // Build struct kmp_dim {  // loop bounds info casted to kmp_int64
7702     //  kmp_int64 lo; // lower
7703     //  kmp_int64 up; // upper
7704     //  kmp_int64 st; // stride
7705     // };
7706     RD = C.buildImplicitRecord("kmp_dim");
7707     RD->startDefinition();
7708     addFieldToRecordDecl(C, RD, Int64Ty);
7709     addFieldToRecordDecl(C, RD, Int64Ty);
7710     addFieldToRecordDecl(C, RD, Int64Ty);
7711     RD->completeDefinition();
7712     KmpDimTy = C.getRecordType(RD);
7713   } else
7714     RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7715 
7716   Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7717   CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7718   enum { LowerFD = 0, UpperFD, StrideFD };
7719   // Fill dims with data.
7720   LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7721   // dims.upper = num_iterations;
7722   LValue UpperLVal =
7723       CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7724   llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7725       CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7726       Int64Ty, D.getNumIterations()->getExprLoc());
7727   CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7728   // dims.stride = 1;
7729   LValue StrideLVal =
7730       CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7731   CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7732                         StrideLVal);
7733 
7734   // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7735   // kmp_int32 num_dims, struct kmp_dim * dims);
7736   llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7737                          getThreadID(CGF, D.getLocStart()),
7738                          llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7739                          CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7740                              DimsAddr.getPointer(), CGM.VoidPtrTy)};
7741 
7742   llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7743   CGF.EmitRuntimeCall(RTLFn, Args);
7744   llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7745       emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7746   llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7747   CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7748                                              llvm::makeArrayRef(FiniArgs));
7749 }
7750 
7751 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7752                                           const OMPDependClause *C) {
7753   QualType Int64Ty =
7754       CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7755   const Expr *CounterVal = C->getCounterValue();
7756   assert(CounterVal);
7757   llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7758                                                  CounterVal->getType(), Int64Ty,
7759                                                  CounterVal->getExprLoc());
7760   Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7761   CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7762   llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7763                          getThreadID(CGF, C->getLocStart()),
7764                          CntAddr.getPointer()};
7765   llvm::Value *RTLFn;
7766   if (C->getDependencyKind() == OMPC_DEPEND_source)
7767     RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7768   else {
7769     assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7770     RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7771   }
7772   CGF.EmitRuntimeCall(RTLFn, Args);
7773 }
7774 
7775 void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7776                                ArrayRef<llvm::Value *> Args,
7777                                SourceLocation Loc) const {
7778   auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7779 
7780   if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
7781     if (Fn->doesNotThrow()) {
7782       CGF.EmitNounwindRuntimeCall(Fn, Args);
7783       return;
7784     }
7785   }
7786   CGF.EmitRuntimeCall(Callee, Args);
7787 }
7788 
7789 void CGOpenMPRuntime::emitOutlinedFunctionCall(
7790     CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7791     ArrayRef<llvm::Value *> Args) const {
7792   assert(Loc.isValid() && "Outlined function call location must be valid.");
7793   emitCall(CGF, OutlinedFn, Args, Loc);
7794 }
7795 
7796 Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7797                                              const VarDecl *NativeParam,
7798                                              const VarDecl *TargetParam) const {
7799   return CGF.GetAddrOfLocalVar(NativeParam);
7800 }
7801