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