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