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