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