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