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