1 //===---- CGOpenMPRuntimeGPU.cpp - Interface to OpenMP GPU Runtimes ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides a generalized class for OpenMP runtime code generation
10 // specialized by GPU targets NVPTX and AMDGCN.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGOpenMPRuntimeGPU.h"
15 #include "CGOpenMPRuntimeNVPTX.h"
16 #include "CodeGenFunction.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtOpenMP.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/Basic/Cuda.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
24 #include "llvm/IR/IntrinsicsNVPTX.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 using namespace llvm::omp;
29 
30 namespace {
31 enum OpenMPRTLFunctionNVPTX {
32   /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
33   /// int16_t RequiresOMPRuntime);
34   OMPRTL_NVPTX__kmpc_kernel_init,
35   /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
36   OMPRTL_NVPTX__kmpc_kernel_deinit,
37   /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
38   /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
39   OMPRTL_NVPTX__kmpc_spmd_kernel_init,
40   /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
41   OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
42   /// Call to void __kmpc_kernel_prepare_parallel(void
43   /// *outlined_function);
44   OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
45   /// Call to bool __kmpc_kernel_parallel(void **outlined_function);
46   OMPRTL_NVPTX__kmpc_kernel_parallel,
47   /// Call to void __kmpc_kernel_end_parallel();
48   OMPRTL_NVPTX__kmpc_kernel_end_parallel,
49   /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
50   /// global_tid);
51   OMPRTL_NVPTX__kmpc_serialized_parallel,
52   /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
53   /// global_tid);
54   OMPRTL_NVPTX__kmpc_end_serialized_parallel,
55   /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
56   /// int16_t lane_offset, int16_t warp_size);
57   OMPRTL_NVPTX__kmpc_shuffle_int32,
58   /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
59   /// int16_t lane_offset, int16_t warp_size);
60   OMPRTL_NVPTX__kmpc_shuffle_int64,
61   /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
62   /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
63   /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
64   /// lane_offset, int16_t shortCircuit),
65   /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
66   OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
67   /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
68   /// global_tid, void *global_buffer, int32_t num_of_records, void*
69   /// reduce_data,
70   /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
71   /// lane_offset, int16_t shortCircuit),
72   /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
73   /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
74   /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
75   /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
76   /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
77   /// *buffer, int idx, void *reduce_data));
78   OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
79   /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
80   OMPRTL_NVPTX__kmpc_end_reduce_nowait,
81   /// Call to void __kmpc_data_sharing_init_stack();
82   OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
83   /// Call to void __kmpc_data_sharing_init_stack_spmd();
84   OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
85   /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
86   /// int16_t UseSharedMemory);
87   OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
88   /// Call to void* __kmpc_data_sharing_push_stack(size_t size, int16_t
89   /// UseSharedMemory);
90   OMPRTL_NVPTX__kmpc_data_sharing_push_stack,
91   /// Call to void __kmpc_data_sharing_pop_stack(void *a);
92   OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
93   /// Call to void __kmpc_begin_sharing_variables(void ***args,
94   /// size_t n_args);
95   OMPRTL_NVPTX__kmpc_begin_sharing_variables,
96   /// Call to void __kmpc_end_sharing_variables();
97   OMPRTL_NVPTX__kmpc_end_sharing_variables,
98   /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
99   OMPRTL_NVPTX__kmpc_get_shared_variables,
100   /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
101   /// global_tid);
102   OMPRTL_NVPTX__kmpc_parallel_level,
103   /// Call to int8_t __kmpc_is_spmd_exec_mode();
104   OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
105   /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
106   /// const void *buf, size_t size, int16_t is_shared, const void **res);
107   OMPRTL_NVPTX__kmpc_get_team_static_memory,
108   /// Call to void __kmpc_restore_team_static_memory(int16_t
109   /// isSPMDExecutionMode, int16_t is_shared);
110   OMPRTL_NVPTX__kmpc_restore_team_static_memory,
111   /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
112   OMPRTL__kmpc_barrier,
113   /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
114   /// global_tid);
115   OMPRTL__kmpc_barrier_simple_spmd,
116   /// Call to int32_t __kmpc_warp_active_thread_mask(void);
117   OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
118   /// Call to void __kmpc_syncwarp(int32_t Mask);
119   OMPRTL_NVPTX__kmpc_syncwarp,
120 };
121 
122 /// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
123 class NVPTXActionTy final : public PrePostActionTy {
124   llvm::FunctionCallee EnterCallee = nullptr;
125   ArrayRef<llvm::Value *> EnterArgs;
126   llvm::FunctionCallee ExitCallee = nullptr;
127   ArrayRef<llvm::Value *> ExitArgs;
128   bool Conditional = false;
129   llvm::BasicBlock *ContBlock = nullptr;
130 
131 public:
132   NVPTXActionTy(llvm::FunctionCallee EnterCallee,
133                 ArrayRef<llvm::Value *> EnterArgs,
134                 llvm::FunctionCallee ExitCallee,
135                 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
136       : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
137         ExitArgs(ExitArgs), Conditional(Conditional) {}
138   void Enter(CodeGenFunction &CGF) override {
139     llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
140     if (Conditional) {
141       llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
142       auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
143       ContBlock = CGF.createBasicBlock("omp_if.end");
144       // Generate the branch (If-stmt)
145       CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
146       CGF.EmitBlock(ThenBlock);
147     }
148   }
149   void Done(CodeGenFunction &CGF) {
150     // Emit the rest of blocks/branches
151     CGF.EmitBranch(ContBlock);
152     CGF.EmitBlock(ContBlock, true);
153   }
154   void Exit(CodeGenFunction &CGF) override {
155     CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
156   }
157 };
158 
159 /// A class to track the execution mode when codegening directives within
160 /// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
161 /// to the target region and used by containing directives such as 'parallel'
162 /// to emit optimized code.
163 class ExecutionRuntimeModesRAII {
164 private:
165   CGOpenMPRuntimeGPU::ExecutionMode SavedExecMode =
166       CGOpenMPRuntimeGPU::EM_Unknown;
167   CGOpenMPRuntimeGPU::ExecutionMode &ExecMode;
168   bool SavedRuntimeMode = false;
169   bool *RuntimeMode = nullptr;
170 
171 public:
172   /// Constructor for Non-SPMD mode.
173   ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode)
174       : ExecMode(ExecMode) {
175     SavedExecMode = ExecMode;
176     ExecMode = CGOpenMPRuntimeGPU::EM_NonSPMD;
177   }
178   /// Constructor for SPMD mode.
179   ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode,
180                             bool &RuntimeMode, bool FullRuntimeMode)
181       : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
182     SavedExecMode = ExecMode;
183     SavedRuntimeMode = RuntimeMode;
184     ExecMode = CGOpenMPRuntimeGPU::EM_SPMD;
185     RuntimeMode = FullRuntimeMode;
186   }
187   ~ExecutionRuntimeModesRAII() {
188     ExecMode = SavedExecMode;
189     if (RuntimeMode)
190       *RuntimeMode = SavedRuntimeMode;
191   }
192 };
193 
194 /// GPU Configuration:  This information can be derived from cuda registers,
195 /// however, providing compile time constants helps generate more efficient
196 /// code.  For all practical purposes this is fine because the configuration
197 /// is the same for all known NVPTX architectures.
198 enum MachineConfiguration : unsigned {
199   /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
200   /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
201   /// and GV_Warp_Size_Log2_Mask.
202 
203   /// Global memory alignment for performance.
204   GlobalMemoryAlignment = 128,
205 
206   /// Maximal size of the shared memory buffer.
207   SharedMemorySize = 128,
208 };
209 
210 static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
211   RefExpr = RefExpr->IgnoreParens();
212   if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
213     const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
214     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
215       Base = TempASE->getBase()->IgnoreParenImpCasts();
216     RefExpr = Base;
217   } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
218     const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
219     while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
220       Base = TempOASE->getBase()->IgnoreParenImpCasts();
221     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
222       Base = TempASE->getBase()->IgnoreParenImpCasts();
223     RefExpr = Base;
224   }
225   RefExpr = RefExpr->IgnoreParenImpCasts();
226   if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
227     return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
228   const auto *ME = cast<MemberExpr>(RefExpr);
229   return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
230 }
231 
232 
233 static RecordDecl *buildRecordForGlobalizedVars(
234     ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
235     ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
236     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
237         &MappedDeclsFields, int BufSize) {
238   using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
239   if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
240     return nullptr;
241   SmallVector<VarsDataTy, 4> GlobalizedVars;
242   for (const ValueDecl *D : EscapedDecls)
243     GlobalizedVars.emplace_back(
244         CharUnits::fromQuantity(std::max(
245             C.getDeclAlign(D).getQuantity(),
246             static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
247         D);
248   for (const ValueDecl *D : EscapedDeclsForTeams)
249     GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
250   llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
251     return L.first > R.first;
252   });
253 
254   // Build struct _globalized_locals_ty {
255   //         /*  globalized vars  */[WarSize] align (max(decl_align,
256   //         GlobalMemoryAlignment))
257   //         /*  globalized vars  */ for EscapedDeclsForTeams
258   //       };
259   RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
260   GlobalizedRD->startDefinition();
261   llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
262       EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
263   for (const auto &Pair : GlobalizedVars) {
264     const ValueDecl *VD = Pair.second;
265     QualType Type = VD->getType();
266     if (Type->isLValueReferenceType())
267       Type = C.getPointerType(Type.getNonReferenceType());
268     else
269       Type = Type.getNonReferenceType();
270     SourceLocation Loc = VD->getLocation();
271     FieldDecl *Field;
272     if (SingleEscaped.count(VD)) {
273       Field = FieldDecl::Create(
274           C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
275           C.getTrivialTypeSourceInfo(Type, SourceLocation()),
276           /*BW=*/nullptr, /*Mutable=*/false,
277           /*InitStyle=*/ICIS_NoInit);
278       Field->setAccess(AS_public);
279       if (VD->hasAttrs()) {
280         for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
281              E(VD->getAttrs().end());
282              I != E; ++I)
283           Field->addAttr(*I);
284       }
285     } else {
286       llvm::APInt ArraySize(32, BufSize);
287       Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
288                                     0);
289       Field = FieldDecl::Create(
290           C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
291           C.getTrivialTypeSourceInfo(Type, SourceLocation()),
292           /*BW=*/nullptr, /*Mutable=*/false,
293           /*InitStyle=*/ICIS_NoInit);
294       Field->setAccess(AS_public);
295       llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
296                                      static_cast<CharUnits::QuantityType>(
297                                          GlobalMemoryAlignment)));
298       Field->addAttr(AlignedAttr::CreateImplicit(
299           C, /*IsAlignmentExpr=*/true,
300           IntegerLiteral::Create(C, Align,
301                                  C.getIntTypeForBitwidth(32, /*Signed=*/0),
302                                  SourceLocation()),
303           {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
304     }
305     GlobalizedRD->addDecl(Field);
306     MappedDeclsFields.try_emplace(VD, Field);
307   }
308   GlobalizedRD->completeDefinition();
309   return GlobalizedRD;
310 }
311 
312 /// Get the list of variables that can escape their declaration context.
313 class CheckVarsEscapingDeclContext final
314     : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
315   CodeGenFunction &CGF;
316   llvm::SetVector<const ValueDecl *> EscapedDecls;
317   llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
318   llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
319   RecordDecl *GlobalizedRD = nullptr;
320   llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
321   bool AllEscaped = false;
322   bool IsForCombinedParallelRegion = false;
323 
324   void markAsEscaped(const ValueDecl *VD) {
325     // Do not globalize declare target variables.
326     if (!isa<VarDecl>(VD) ||
327         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
328       return;
329     VD = cast<ValueDecl>(VD->getCanonicalDecl());
330     // Use user-specified allocation.
331     if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
332       return;
333     // Variables captured by value must be globalized.
334     if (auto *CSI = CGF.CapturedStmtInfo) {
335       if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
336         // Check if need to capture the variable that was already captured by
337         // value in the outer region.
338         if (!IsForCombinedParallelRegion) {
339           if (!FD->hasAttrs())
340             return;
341           const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
342           if (!Attr)
343             return;
344           if (((Attr->getCaptureKind() != OMPC_map) &&
345                !isOpenMPPrivate(Attr->getCaptureKind())) ||
346               ((Attr->getCaptureKind() == OMPC_map) &&
347                !FD->getType()->isAnyPointerType()))
348             return;
349         }
350         if (!FD->getType()->isReferenceType()) {
351           assert(!VD->getType()->isVariablyModifiedType() &&
352                  "Parameter captured by value with variably modified type");
353           EscapedParameters.insert(VD);
354         } else if (!IsForCombinedParallelRegion) {
355           return;
356         }
357       }
358     }
359     if ((!CGF.CapturedStmtInfo ||
360          (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
361         VD->getType()->isReferenceType())
362       // Do not globalize variables with reference type.
363       return;
364     if (VD->getType()->isVariablyModifiedType())
365       EscapedVariableLengthDecls.insert(VD);
366     else
367       EscapedDecls.insert(VD);
368   }
369 
370   void VisitValueDecl(const ValueDecl *VD) {
371     if (VD->getType()->isLValueReferenceType())
372       markAsEscaped(VD);
373     if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
374       if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
375         const bool SavedAllEscaped = AllEscaped;
376         AllEscaped = VD->getType()->isLValueReferenceType();
377         Visit(VarD->getInit());
378         AllEscaped = SavedAllEscaped;
379       }
380     }
381   }
382   void VisitOpenMPCapturedStmt(const CapturedStmt *S,
383                                ArrayRef<OMPClause *> Clauses,
384                                bool IsCombinedParallelRegion) {
385     if (!S)
386       return;
387     for (const CapturedStmt::Capture &C : S->captures()) {
388       if (C.capturesVariable() && !C.capturesVariableByCopy()) {
389         const ValueDecl *VD = C.getCapturedVar();
390         bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
391         if (IsCombinedParallelRegion) {
392           // Check if the variable is privatized in the combined construct and
393           // those private copies must be shared in the inner parallel
394           // directive.
395           IsForCombinedParallelRegion = false;
396           for (const OMPClause *C : Clauses) {
397             if (!isOpenMPPrivate(C->getClauseKind()) ||
398                 C->getClauseKind() == OMPC_reduction ||
399                 C->getClauseKind() == OMPC_linear ||
400                 C->getClauseKind() == OMPC_private)
401               continue;
402             ArrayRef<const Expr *> Vars;
403             if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
404               Vars = PC->getVarRefs();
405             else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
406               Vars = PC->getVarRefs();
407             else
408               llvm_unreachable("Unexpected clause.");
409             for (const auto *E : Vars) {
410               const Decl *D =
411                   cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
412               if (D == VD->getCanonicalDecl()) {
413                 IsForCombinedParallelRegion = true;
414                 break;
415               }
416             }
417             if (IsForCombinedParallelRegion)
418               break;
419           }
420         }
421         markAsEscaped(VD);
422         if (isa<OMPCapturedExprDecl>(VD))
423           VisitValueDecl(VD);
424         IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
425       }
426     }
427   }
428 
429   void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
430     assert(!GlobalizedRD &&
431            "Record for globalized variables is built already.");
432     ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
433     unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
434     if (IsInTTDRegion)
435       EscapedDeclsForTeams = EscapedDecls.getArrayRef();
436     else
437       EscapedDeclsForParallel = EscapedDecls.getArrayRef();
438     GlobalizedRD = ::buildRecordForGlobalizedVars(
439         CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
440         MappedDeclsFields, WarpSize);
441   }
442 
443 public:
444   CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
445                                ArrayRef<const ValueDecl *> TeamsReductions)
446       : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
447   }
448   virtual ~CheckVarsEscapingDeclContext() = default;
449   void VisitDeclStmt(const DeclStmt *S) {
450     if (!S)
451       return;
452     for (const Decl *D : S->decls())
453       if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
454         VisitValueDecl(VD);
455   }
456   void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
457     if (!D)
458       return;
459     if (!D->hasAssociatedStmt())
460       return;
461     if (const auto *S =
462             dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
463       // Do not analyze directives that do not actually require capturing,
464       // like `omp for` or `omp simd` directives.
465       llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
466       getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
467       if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
468         VisitStmt(S->getCapturedStmt());
469         return;
470       }
471       VisitOpenMPCapturedStmt(
472           S, D->clauses(),
473           CaptureRegions.back() == OMPD_parallel &&
474               isOpenMPDistributeDirective(D->getDirectiveKind()));
475     }
476   }
477   void VisitCapturedStmt(const CapturedStmt *S) {
478     if (!S)
479       return;
480     for (const CapturedStmt::Capture &C : S->captures()) {
481       if (C.capturesVariable() && !C.capturesVariableByCopy()) {
482         const ValueDecl *VD = C.getCapturedVar();
483         markAsEscaped(VD);
484         if (isa<OMPCapturedExprDecl>(VD))
485           VisitValueDecl(VD);
486       }
487     }
488   }
489   void VisitLambdaExpr(const LambdaExpr *E) {
490     if (!E)
491       return;
492     for (const LambdaCapture &C : E->captures()) {
493       if (C.capturesVariable()) {
494         if (C.getCaptureKind() == LCK_ByRef) {
495           const ValueDecl *VD = C.getCapturedVar();
496           markAsEscaped(VD);
497           if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
498             VisitValueDecl(VD);
499         }
500       }
501     }
502   }
503   void VisitBlockExpr(const BlockExpr *E) {
504     if (!E)
505       return;
506     for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
507       if (C.isByRef()) {
508         const VarDecl *VD = C.getVariable();
509         markAsEscaped(VD);
510         if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
511           VisitValueDecl(VD);
512       }
513     }
514   }
515   void VisitCallExpr(const CallExpr *E) {
516     if (!E)
517       return;
518     for (const Expr *Arg : E->arguments()) {
519       if (!Arg)
520         continue;
521       if (Arg->isLValue()) {
522         const bool SavedAllEscaped = AllEscaped;
523         AllEscaped = true;
524         Visit(Arg);
525         AllEscaped = SavedAllEscaped;
526       } else {
527         Visit(Arg);
528       }
529     }
530     Visit(E->getCallee());
531   }
532   void VisitDeclRefExpr(const DeclRefExpr *E) {
533     if (!E)
534       return;
535     const ValueDecl *VD = E->getDecl();
536     if (AllEscaped)
537       markAsEscaped(VD);
538     if (isa<OMPCapturedExprDecl>(VD))
539       VisitValueDecl(VD);
540     else if (const auto *VarD = dyn_cast<VarDecl>(VD))
541       if (VarD->isInitCapture())
542         VisitValueDecl(VD);
543   }
544   void VisitUnaryOperator(const UnaryOperator *E) {
545     if (!E)
546       return;
547     if (E->getOpcode() == UO_AddrOf) {
548       const bool SavedAllEscaped = AllEscaped;
549       AllEscaped = true;
550       Visit(E->getSubExpr());
551       AllEscaped = SavedAllEscaped;
552     } else {
553       Visit(E->getSubExpr());
554     }
555   }
556   void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
557     if (!E)
558       return;
559     if (E->getCastKind() == CK_ArrayToPointerDecay) {
560       const bool SavedAllEscaped = AllEscaped;
561       AllEscaped = true;
562       Visit(E->getSubExpr());
563       AllEscaped = SavedAllEscaped;
564     } else {
565       Visit(E->getSubExpr());
566     }
567   }
568   void VisitExpr(const Expr *E) {
569     if (!E)
570       return;
571     bool SavedAllEscaped = AllEscaped;
572     if (!E->isLValue())
573       AllEscaped = false;
574     for (const Stmt *Child : E->children())
575       if (Child)
576         Visit(Child);
577     AllEscaped = SavedAllEscaped;
578   }
579   void VisitStmt(const Stmt *S) {
580     if (!S)
581       return;
582     for (const Stmt *Child : S->children())
583       if (Child)
584         Visit(Child);
585   }
586 
587   /// Returns the record that handles all the escaped local variables and used
588   /// instead of their original storage.
589   const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
590     if (!GlobalizedRD)
591       buildRecordForGlobalizedVars(IsInTTDRegion);
592     return GlobalizedRD;
593   }
594 
595   /// Returns the field in the globalized record for the escaped variable.
596   const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
597     assert(GlobalizedRD &&
598            "Record for globalized variables must be generated already.");
599     auto I = MappedDeclsFields.find(VD);
600     if (I == MappedDeclsFields.end())
601       return nullptr;
602     return I->getSecond();
603   }
604 
605   /// Returns the list of the escaped local variables/parameters.
606   ArrayRef<const ValueDecl *> getEscapedDecls() const {
607     return EscapedDecls.getArrayRef();
608   }
609 
610   /// Checks if the escaped local variable is actually a parameter passed by
611   /// value.
612   const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
613     return EscapedParameters;
614   }
615 
616   /// Returns the list of the escaped variables with the variably modified
617   /// types.
618   ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
619     return EscapedVariableLengthDecls.getArrayRef();
620   }
621 };
622 } // anonymous namespace
623 
624 /// Get the id of the warp in the block.
625 /// We assume that the warp size is 32, which is always the case
626 /// on the NVPTX device, to generate more efficient code.
627 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
628   CGBuilderTy &Bld = CGF.Builder;
629   unsigned LaneIDBits =
630       CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
631   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
632   return Bld.CreateAShr(RT.getGPUThreadID(CGF), LaneIDBits, "nvptx_warp_id");
633 }
634 
635 /// Get the id of the current lane in the Warp.
636 /// We assume that the warp size is 32, which is always the case
637 /// on the NVPTX device, to generate more efficient code.
638 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
639   CGBuilderTy &Bld = CGF.Builder;
640   unsigned LaneIDMask = CGF.getContext().getTargetInfo().getGridValue(
641       llvm::omp::GV_Warp_Size_Log2_Mask);
642   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
643   return Bld.CreateAnd(RT.getGPUThreadID(CGF), Bld.getInt32(LaneIDMask),
644                        "nvptx_lane_id");
645 }
646 
647 /// Get the value of the thread_limit clause in the teams directive.
648 /// For the 'generic' execution mode, the runtime encodes thread_limit in
649 /// the launch parameters, always starting thread_limit+warpSize threads per
650 /// CTA. The threads in the last warp are reserved for master execution.
651 /// For the 'spmd' execution mode, all threads in a CTA are part of the team.
652 static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
653                                    bool IsInSPMDExecutionMode = false) {
654   CGBuilderTy &Bld = CGF.Builder;
655   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
656   return IsInSPMDExecutionMode
657              ? RT.getGPUNumThreads(CGF)
658              : Bld.CreateNUWSub(RT.getGPUNumThreads(CGF),
659                                 RT.getGPUWarpSize(CGF), "thread_limit");
660 }
661 
662 /// Get the thread id of the OMP master thread.
663 /// The master thread id is the first thread (lane) of the last warp in the
664 /// GPU block.  Warp size is assumed to be some power of 2.
665 /// Thread id is 0 indexed.
666 /// E.g: If NumThreads is 33, master id is 32.
667 ///      If NumThreads is 64, master id is 32.
668 ///      If NumThreads is 1024, master id is 992.
669 static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
670   CGBuilderTy &Bld = CGF.Builder;
671   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
672   llvm::Value *NumThreads = RT.getGPUNumThreads(CGF);
673   // We assume that the warp size is a power of 2.
674   llvm::Value *Mask = Bld.CreateNUWSub(RT.getGPUWarpSize(CGF), Bld.getInt32(1));
675 
676   return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
677                        Bld.CreateNot(Mask), "master_tid");
678 }
679 
680 CGOpenMPRuntimeGPU::WorkerFunctionState::WorkerFunctionState(
681     CodeGenModule &CGM, SourceLocation Loc)
682     : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
683       Loc(Loc) {
684   createWorkerFunction(CGM);
685 }
686 
687 void CGOpenMPRuntimeGPU::WorkerFunctionState::createWorkerFunction(
688     CodeGenModule &CGM) {
689   // Create an worker function with no arguments.
690 
691   WorkerFn = llvm::Function::Create(
692       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
693       /*placeholder=*/"_worker", &CGM.getModule());
694   CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
695   WorkerFn->setDoesNotRecurse();
696 }
697 
698 CGOpenMPRuntimeGPU::ExecutionMode
699 CGOpenMPRuntimeGPU::getExecutionMode() const {
700   return CurrentExecutionMode;
701 }
702 
703 static CGOpenMPRuntimeGPU::DataSharingMode
704 getDataSharingMode(CodeGenModule &CGM) {
705   return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeGPU::CUDA
706                                           : CGOpenMPRuntimeGPU::Generic;
707 }
708 
709 /// Check for inner (nested) SPMD construct, if any
710 static bool hasNestedSPMDDirective(ASTContext &Ctx,
711                                    const OMPExecutableDirective &D) {
712   const auto *CS = D.getInnermostCapturedStmt();
713   const auto *Body =
714       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
715   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
716 
717   if (const auto *NestedDir =
718           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
719     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
720     switch (D.getDirectiveKind()) {
721     case OMPD_target:
722       if (isOpenMPParallelDirective(DKind))
723         return true;
724       if (DKind == OMPD_teams) {
725         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
726             /*IgnoreCaptured=*/true);
727         if (!Body)
728           return false;
729         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
730         if (const auto *NND =
731                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
732           DKind = NND->getDirectiveKind();
733           if (isOpenMPParallelDirective(DKind))
734             return true;
735         }
736       }
737       return false;
738     case OMPD_target_teams:
739       return isOpenMPParallelDirective(DKind);
740     case OMPD_target_simd:
741     case OMPD_target_parallel:
742     case OMPD_target_parallel_for:
743     case OMPD_target_parallel_for_simd:
744     case OMPD_target_teams_distribute:
745     case OMPD_target_teams_distribute_simd:
746     case OMPD_target_teams_distribute_parallel_for:
747     case OMPD_target_teams_distribute_parallel_for_simd:
748     case OMPD_parallel:
749     case OMPD_for:
750     case OMPD_parallel_for:
751     case OMPD_parallel_master:
752     case OMPD_parallel_sections:
753     case OMPD_for_simd:
754     case OMPD_parallel_for_simd:
755     case OMPD_cancel:
756     case OMPD_cancellation_point:
757     case OMPD_ordered:
758     case OMPD_threadprivate:
759     case OMPD_allocate:
760     case OMPD_task:
761     case OMPD_simd:
762     case OMPD_sections:
763     case OMPD_section:
764     case OMPD_single:
765     case OMPD_master:
766     case OMPD_critical:
767     case OMPD_taskyield:
768     case OMPD_barrier:
769     case OMPD_taskwait:
770     case OMPD_taskgroup:
771     case OMPD_atomic:
772     case OMPD_flush:
773     case OMPD_depobj:
774     case OMPD_scan:
775     case OMPD_teams:
776     case OMPD_target_data:
777     case OMPD_target_exit_data:
778     case OMPD_target_enter_data:
779     case OMPD_distribute:
780     case OMPD_distribute_simd:
781     case OMPD_distribute_parallel_for:
782     case OMPD_distribute_parallel_for_simd:
783     case OMPD_teams_distribute:
784     case OMPD_teams_distribute_simd:
785     case OMPD_teams_distribute_parallel_for:
786     case OMPD_teams_distribute_parallel_for_simd:
787     case OMPD_target_update:
788     case OMPD_declare_simd:
789     case OMPD_declare_variant:
790     case OMPD_begin_declare_variant:
791     case OMPD_end_declare_variant:
792     case OMPD_declare_target:
793     case OMPD_end_declare_target:
794     case OMPD_declare_reduction:
795     case OMPD_declare_mapper:
796     case OMPD_taskloop:
797     case OMPD_taskloop_simd:
798     case OMPD_master_taskloop:
799     case OMPD_master_taskloop_simd:
800     case OMPD_parallel_master_taskloop:
801     case OMPD_parallel_master_taskloop_simd:
802     case OMPD_requires:
803     case OMPD_unknown:
804     default:
805       llvm_unreachable("Unexpected directive.");
806     }
807   }
808 
809   return false;
810 }
811 
812 static bool supportsSPMDExecutionMode(ASTContext &Ctx,
813                                       const OMPExecutableDirective &D) {
814   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
815   switch (DirectiveKind) {
816   case OMPD_target:
817   case OMPD_target_teams:
818     return hasNestedSPMDDirective(Ctx, D);
819   case OMPD_target_parallel:
820   case OMPD_target_parallel_for:
821   case OMPD_target_parallel_for_simd:
822   case OMPD_target_teams_distribute_parallel_for:
823   case OMPD_target_teams_distribute_parallel_for_simd:
824   case OMPD_target_simd:
825   case OMPD_target_teams_distribute_simd:
826     return true;
827   case OMPD_target_teams_distribute:
828     return false;
829   case OMPD_parallel:
830   case OMPD_for:
831   case OMPD_parallel_for:
832   case OMPD_parallel_master:
833   case OMPD_parallel_sections:
834   case OMPD_for_simd:
835   case OMPD_parallel_for_simd:
836   case OMPD_cancel:
837   case OMPD_cancellation_point:
838   case OMPD_ordered:
839   case OMPD_threadprivate:
840   case OMPD_allocate:
841   case OMPD_task:
842   case OMPD_simd:
843   case OMPD_sections:
844   case OMPD_section:
845   case OMPD_single:
846   case OMPD_master:
847   case OMPD_critical:
848   case OMPD_taskyield:
849   case OMPD_barrier:
850   case OMPD_taskwait:
851   case OMPD_taskgroup:
852   case OMPD_atomic:
853   case OMPD_flush:
854   case OMPD_depobj:
855   case OMPD_scan:
856   case OMPD_teams:
857   case OMPD_target_data:
858   case OMPD_target_exit_data:
859   case OMPD_target_enter_data:
860   case OMPD_distribute:
861   case OMPD_distribute_simd:
862   case OMPD_distribute_parallel_for:
863   case OMPD_distribute_parallel_for_simd:
864   case OMPD_teams_distribute:
865   case OMPD_teams_distribute_simd:
866   case OMPD_teams_distribute_parallel_for:
867   case OMPD_teams_distribute_parallel_for_simd:
868   case OMPD_target_update:
869   case OMPD_declare_simd:
870   case OMPD_declare_variant:
871   case OMPD_begin_declare_variant:
872   case OMPD_end_declare_variant:
873   case OMPD_declare_target:
874   case OMPD_end_declare_target:
875   case OMPD_declare_reduction:
876   case OMPD_declare_mapper:
877   case OMPD_taskloop:
878   case OMPD_taskloop_simd:
879   case OMPD_master_taskloop:
880   case OMPD_master_taskloop_simd:
881   case OMPD_parallel_master_taskloop:
882   case OMPD_parallel_master_taskloop_simd:
883   case OMPD_requires:
884   case OMPD_unknown:
885   default:
886     break;
887   }
888   llvm_unreachable(
889       "Unknown programming model for OpenMP directive on NVPTX target.");
890 }
891 
892 /// Check if the directive is loops based and has schedule clause at all or has
893 /// static scheduling.
894 static bool hasStaticScheduling(const OMPExecutableDirective &D) {
895   assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
896          isOpenMPLoopDirective(D.getDirectiveKind()) &&
897          "Expected loop-based directive.");
898   return !D.hasClausesOfKind<OMPOrderedClause>() &&
899          (!D.hasClausesOfKind<OMPScheduleClause>() ||
900           llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
901                        [](const OMPScheduleClause *C) {
902                          return C->getScheduleKind() == OMPC_SCHEDULE_static;
903                        }));
904 }
905 
906 /// Check for inner (nested) lightweight runtime construct, if any
907 static bool hasNestedLightweightDirective(ASTContext &Ctx,
908                                           const OMPExecutableDirective &D) {
909   assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
910   const auto *CS = D.getInnermostCapturedStmt();
911   const auto *Body =
912       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
913   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
914 
915   if (const auto *NestedDir =
916           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
917     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
918     switch (D.getDirectiveKind()) {
919     case OMPD_target:
920       if (isOpenMPParallelDirective(DKind) &&
921           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
922           hasStaticScheduling(*NestedDir))
923         return true;
924       if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
925         return true;
926       if (DKind == OMPD_parallel) {
927         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
928             /*IgnoreCaptured=*/true);
929         if (!Body)
930           return false;
931         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
932         if (const auto *NND =
933                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
934           DKind = NND->getDirectiveKind();
935           if (isOpenMPWorksharingDirective(DKind) &&
936               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
937             return true;
938         }
939       } else if (DKind == OMPD_teams) {
940         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
941             /*IgnoreCaptured=*/true);
942         if (!Body)
943           return false;
944         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
945         if (const auto *NND =
946                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
947           DKind = NND->getDirectiveKind();
948           if (isOpenMPParallelDirective(DKind) &&
949               isOpenMPWorksharingDirective(DKind) &&
950               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
951             return true;
952           if (DKind == OMPD_parallel) {
953             Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
954                 /*IgnoreCaptured=*/true);
955             if (!Body)
956               return false;
957             ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
958             if (const auto *NND =
959                     dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
960               DKind = NND->getDirectiveKind();
961               if (isOpenMPWorksharingDirective(DKind) &&
962                   isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
963                 return true;
964             }
965           }
966         }
967       }
968       return false;
969     case OMPD_target_teams:
970       if (isOpenMPParallelDirective(DKind) &&
971           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
972           hasStaticScheduling(*NestedDir))
973         return true;
974       if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
975         return true;
976       if (DKind == OMPD_parallel) {
977         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
978             /*IgnoreCaptured=*/true);
979         if (!Body)
980           return false;
981         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
982         if (const auto *NND =
983                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
984           DKind = NND->getDirectiveKind();
985           if (isOpenMPWorksharingDirective(DKind) &&
986               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
987             return true;
988         }
989       }
990       return false;
991     case OMPD_target_parallel:
992       if (DKind == OMPD_simd)
993         return true;
994       return isOpenMPWorksharingDirective(DKind) &&
995              isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
996     case OMPD_target_teams_distribute:
997     case OMPD_target_simd:
998     case OMPD_target_parallel_for:
999     case OMPD_target_parallel_for_simd:
1000     case OMPD_target_teams_distribute_simd:
1001     case OMPD_target_teams_distribute_parallel_for:
1002     case OMPD_target_teams_distribute_parallel_for_simd:
1003     case OMPD_parallel:
1004     case OMPD_for:
1005     case OMPD_parallel_for:
1006     case OMPD_parallel_master:
1007     case OMPD_parallel_sections:
1008     case OMPD_for_simd:
1009     case OMPD_parallel_for_simd:
1010     case OMPD_cancel:
1011     case OMPD_cancellation_point:
1012     case OMPD_ordered:
1013     case OMPD_threadprivate:
1014     case OMPD_allocate:
1015     case OMPD_task:
1016     case OMPD_simd:
1017     case OMPD_sections:
1018     case OMPD_section:
1019     case OMPD_single:
1020     case OMPD_master:
1021     case OMPD_critical:
1022     case OMPD_taskyield:
1023     case OMPD_barrier:
1024     case OMPD_taskwait:
1025     case OMPD_taskgroup:
1026     case OMPD_atomic:
1027     case OMPD_flush:
1028     case OMPD_depobj:
1029     case OMPD_scan:
1030     case OMPD_teams:
1031     case OMPD_target_data:
1032     case OMPD_target_exit_data:
1033     case OMPD_target_enter_data:
1034     case OMPD_distribute:
1035     case OMPD_distribute_simd:
1036     case OMPD_distribute_parallel_for:
1037     case OMPD_distribute_parallel_for_simd:
1038     case OMPD_teams_distribute:
1039     case OMPD_teams_distribute_simd:
1040     case OMPD_teams_distribute_parallel_for:
1041     case OMPD_teams_distribute_parallel_for_simd:
1042     case OMPD_target_update:
1043     case OMPD_declare_simd:
1044     case OMPD_declare_variant:
1045     case OMPD_begin_declare_variant:
1046     case OMPD_end_declare_variant:
1047     case OMPD_declare_target:
1048     case OMPD_end_declare_target:
1049     case OMPD_declare_reduction:
1050     case OMPD_declare_mapper:
1051     case OMPD_taskloop:
1052     case OMPD_taskloop_simd:
1053     case OMPD_master_taskloop:
1054     case OMPD_master_taskloop_simd:
1055     case OMPD_parallel_master_taskloop:
1056     case OMPD_parallel_master_taskloop_simd:
1057     case OMPD_requires:
1058     case OMPD_unknown:
1059     default:
1060       llvm_unreachable("Unexpected directive.");
1061     }
1062   }
1063 
1064   return false;
1065 }
1066 
1067 /// Checks if the construct supports lightweight runtime. It must be SPMD
1068 /// construct + inner loop-based construct with static scheduling.
1069 static bool supportsLightweightRuntime(ASTContext &Ctx,
1070                                        const OMPExecutableDirective &D) {
1071   if (!supportsSPMDExecutionMode(Ctx, D))
1072     return false;
1073   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1074   switch (DirectiveKind) {
1075   case OMPD_target:
1076   case OMPD_target_teams:
1077   case OMPD_target_parallel:
1078     return hasNestedLightweightDirective(Ctx, D);
1079   case OMPD_target_parallel_for:
1080   case OMPD_target_parallel_for_simd:
1081   case OMPD_target_teams_distribute_parallel_for:
1082   case OMPD_target_teams_distribute_parallel_for_simd:
1083     // (Last|First)-privates must be shared in parallel region.
1084     return hasStaticScheduling(D);
1085   case OMPD_target_simd:
1086   case OMPD_target_teams_distribute_simd:
1087     return true;
1088   case OMPD_target_teams_distribute:
1089     return false;
1090   case OMPD_parallel:
1091   case OMPD_for:
1092   case OMPD_parallel_for:
1093   case OMPD_parallel_master:
1094   case OMPD_parallel_sections:
1095   case OMPD_for_simd:
1096   case OMPD_parallel_for_simd:
1097   case OMPD_cancel:
1098   case OMPD_cancellation_point:
1099   case OMPD_ordered:
1100   case OMPD_threadprivate:
1101   case OMPD_allocate:
1102   case OMPD_task:
1103   case OMPD_simd:
1104   case OMPD_sections:
1105   case OMPD_section:
1106   case OMPD_single:
1107   case OMPD_master:
1108   case OMPD_critical:
1109   case OMPD_taskyield:
1110   case OMPD_barrier:
1111   case OMPD_taskwait:
1112   case OMPD_taskgroup:
1113   case OMPD_atomic:
1114   case OMPD_flush:
1115   case OMPD_depobj:
1116   case OMPD_scan:
1117   case OMPD_teams:
1118   case OMPD_target_data:
1119   case OMPD_target_exit_data:
1120   case OMPD_target_enter_data:
1121   case OMPD_distribute:
1122   case OMPD_distribute_simd:
1123   case OMPD_distribute_parallel_for:
1124   case OMPD_distribute_parallel_for_simd:
1125   case OMPD_teams_distribute:
1126   case OMPD_teams_distribute_simd:
1127   case OMPD_teams_distribute_parallel_for:
1128   case OMPD_teams_distribute_parallel_for_simd:
1129   case OMPD_target_update:
1130   case OMPD_declare_simd:
1131   case OMPD_declare_variant:
1132   case OMPD_begin_declare_variant:
1133   case OMPD_end_declare_variant:
1134   case OMPD_declare_target:
1135   case OMPD_end_declare_target:
1136   case OMPD_declare_reduction:
1137   case OMPD_declare_mapper:
1138   case OMPD_taskloop:
1139   case OMPD_taskloop_simd:
1140   case OMPD_master_taskloop:
1141   case OMPD_master_taskloop_simd:
1142   case OMPD_parallel_master_taskloop:
1143   case OMPD_parallel_master_taskloop_simd:
1144   case OMPD_requires:
1145   case OMPD_unknown:
1146   default:
1147     break;
1148   }
1149   llvm_unreachable(
1150       "Unknown programming model for OpenMP directive on NVPTX target.");
1151 }
1152 
1153 void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
1154                                              StringRef ParentName,
1155                                              llvm::Function *&OutlinedFn,
1156                                              llvm::Constant *&OutlinedFnID,
1157                                              bool IsOffloadEntry,
1158                                              const RegionCodeGenTy &CodeGen) {
1159   ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
1160   EntryFunctionState EST;
1161   WorkerFunctionState WST(CGM, D.getBeginLoc());
1162   Work.clear();
1163   WrapperFunctionsMap.clear();
1164 
1165   // Emit target region as a standalone region.
1166   class NVPTXPrePostActionTy : public PrePostActionTy {
1167     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1168     CGOpenMPRuntimeGPU::WorkerFunctionState &WST;
1169 
1170   public:
1171     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST,
1172                          CGOpenMPRuntimeGPU::WorkerFunctionState &WST)
1173         : EST(EST), WST(WST) {}
1174     void Enter(CodeGenFunction &CGF) override {
1175       auto &RT =
1176           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1177       RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1178       // Skip target region initialization.
1179       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1180     }
1181     void Exit(CodeGenFunction &CGF) override {
1182       auto &RT =
1183           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1184       RT.clearLocThreadIdInsertPt(CGF);
1185       RT.emitNonSPMDEntryFooter(CGF, EST);
1186     }
1187   } Action(EST, WST);
1188   CodeGen.setAction(Action);
1189   IsInTTDRegion = true;
1190   // Reserve place for the globalized memory.
1191   GlobalizedRecords.emplace_back();
1192   if (!KernelStaticGlobalized) {
1193     KernelStaticGlobalized = new llvm::GlobalVariable(
1194         CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1195         llvm::GlobalValue::InternalLinkage,
1196         llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1197         "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1198         llvm::GlobalValue::NotThreadLocal,
1199         CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1200   }
1201   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1202                                    IsOffloadEntry, CodeGen);
1203   IsInTTDRegion = false;
1204 
1205   // Now change the name of the worker function to correspond to this target
1206   // region's entry function.
1207   WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
1208 
1209   // Create the worker function
1210   emitWorkerFunction(WST);
1211 }
1212 
1213 // Setup NVPTX threads for master-worker OpenMP scheme.
1214 void CGOpenMPRuntimeGPU::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
1215                                                   EntryFunctionState &EST,
1216                                                   WorkerFunctionState &WST) {
1217   CGBuilderTy &Bld = CGF.Builder;
1218 
1219   llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1220   llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1221   llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1222   EST.ExitBB = CGF.createBasicBlock(".exit");
1223 
1224   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1225   llvm::Value *IsWorker =
1226       Bld.CreateICmpULT(RT.getGPUThreadID(CGF), getThreadLimit(CGF));
1227   Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1228 
1229   CGF.EmitBlock(WorkerBB);
1230   emitCall(CGF, WST.Loc, WST.WorkerFn);
1231   CGF.EmitBranch(EST.ExitBB);
1232 
1233   CGF.EmitBlock(MasterCheckBB);
1234   llvm::Value *IsMaster =
1235       Bld.CreateICmpEQ(RT.getGPUThreadID(CGF), getMasterThreadID(CGF));
1236   Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1237 
1238   CGF.EmitBlock(MasterBB);
1239   IsInTargetMasterThreadRegion = true;
1240   // SEQUENTIAL (MASTER) REGION START
1241   // First action in sequential region:
1242   // Initialize the state of the OpenMP runtime library on the GPU.
1243   // TODO: Optimize runtime initialization and pass in correct value.
1244   llvm::Value *Args[] = {getThreadLimit(CGF),
1245                          Bld.getInt16(/*RequiresOMPRuntime=*/1)};
1246   CGF.EmitRuntimeCall(
1247       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
1248 
1249   // For data sharing, we need to initialize the stack.
1250   CGF.EmitRuntimeCall(
1251       createNVPTXRuntimeFunction(
1252           OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1253 
1254   emitGenericVarsProlog(CGF, WST.Loc);
1255 }
1256 
1257 void CGOpenMPRuntimeGPU::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
1258                                                   EntryFunctionState &EST) {
1259   IsInTargetMasterThreadRegion = false;
1260   if (!CGF.HaveInsertPoint())
1261     return;
1262 
1263   emitGenericVarsEpilog(CGF);
1264 
1265   if (!EST.ExitBB)
1266     EST.ExitBB = CGF.createBasicBlock(".exit");
1267 
1268   llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1269   CGF.EmitBranch(TerminateBB);
1270 
1271   CGF.EmitBlock(TerminateBB);
1272   // Signal termination condition.
1273   // TODO: Optimize runtime initialization and pass in correct value.
1274   llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
1275   CGF.EmitRuntimeCall(
1276       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
1277   // Barrier to terminate worker threads.
1278   syncCTAThreads(CGF);
1279   // Master thread jumps to exit point.
1280   CGF.EmitBranch(EST.ExitBB);
1281 
1282   CGF.EmitBlock(EST.ExitBB);
1283   EST.ExitBB = nullptr;
1284 }
1285 
1286 void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
1287                                           StringRef ParentName,
1288                                           llvm::Function *&OutlinedFn,
1289                                           llvm::Constant *&OutlinedFnID,
1290                                           bool IsOffloadEntry,
1291                                           const RegionCodeGenTy &CodeGen) {
1292   ExecutionRuntimeModesRAII ModeRAII(
1293       CurrentExecutionMode, RequiresFullRuntime,
1294       CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1295           !supportsLightweightRuntime(CGM.getContext(), D));
1296   EntryFunctionState EST;
1297 
1298   // Emit target region as a standalone region.
1299   class NVPTXPrePostActionTy : public PrePostActionTy {
1300     CGOpenMPRuntimeGPU &RT;
1301     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1302     const OMPExecutableDirective &D;
1303 
1304   public:
1305     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
1306                          CGOpenMPRuntimeGPU::EntryFunctionState &EST,
1307                          const OMPExecutableDirective &D)
1308         : RT(RT), EST(EST), D(D) {}
1309     void Enter(CodeGenFunction &CGF) override {
1310       RT.emitSPMDEntryHeader(CGF, EST, D);
1311       // Skip target region initialization.
1312       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1313     }
1314     void Exit(CodeGenFunction &CGF) override {
1315       RT.clearLocThreadIdInsertPt(CGF);
1316       RT.emitSPMDEntryFooter(CGF, EST);
1317     }
1318   } Action(*this, EST, D);
1319   CodeGen.setAction(Action);
1320   IsInTTDRegion = true;
1321   // Reserve place for the globalized memory.
1322   GlobalizedRecords.emplace_back();
1323   if (!KernelStaticGlobalized) {
1324     KernelStaticGlobalized = new llvm::GlobalVariable(
1325         CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1326         llvm::GlobalValue::InternalLinkage,
1327         llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1328         "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1329         llvm::GlobalValue::NotThreadLocal,
1330         CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1331   }
1332   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1333                                    IsOffloadEntry, CodeGen);
1334   IsInTTDRegion = false;
1335 }
1336 
1337 void CGOpenMPRuntimeGPU::emitSPMDEntryHeader(
1338     CodeGenFunction &CGF, EntryFunctionState &EST,
1339     const OMPExecutableDirective &D) {
1340   CGBuilderTy &Bld = CGF.Builder;
1341 
1342   // Setup BBs in entry function.
1343   llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1344   EST.ExitBB = CGF.createBasicBlock(".exit");
1345 
1346   llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1347                          /*RequiresOMPRuntime=*/
1348                          Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1349                          /*RequiresDataSharing=*/Bld.getInt16(0)};
1350   CGF.EmitRuntimeCall(
1351       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
1352 
1353   if (RequiresFullRuntime) {
1354     // For data sharing, we need to initialize the stack.
1355     CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1356         OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1357   }
1358 
1359   CGF.EmitBranch(ExecuteBB);
1360 
1361   CGF.EmitBlock(ExecuteBB);
1362 
1363   IsInTargetMasterThreadRegion = true;
1364 }
1365 
1366 void CGOpenMPRuntimeGPU::emitSPMDEntryFooter(CodeGenFunction &CGF,
1367                                                EntryFunctionState &EST) {
1368   IsInTargetMasterThreadRegion = false;
1369   if (!CGF.HaveInsertPoint())
1370     return;
1371 
1372   if (!EST.ExitBB)
1373     EST.ExitBB = CGF.createBasicBlock(".exit");
1374 
1375   llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1376   CGF.EmitBranch(OMPDeInitBB);
1377 
1378   CGF.EmitBlock(OMPDeInitBB);
1379   // DeInitialize the OMP state in the runtime; called by all active threads.
1380   llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1381                          CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
1382   CGF.EmitRuntimeCall(
1383       createNVPTXRuntimeFunction(
1384           OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
1385   CGF.EmitBranch(EST.ExitBB);
1386 
1387   CGF.EmitBlock(EST.ExitBB);
1388   EST.ExitBB = nullptr;
1389 }
1390 
1391 // Create a unique global variable to indicate the execution mode of this target
1392 // region. The execution mode is either 'generic', or 'spmd' depending on the
1393 // target directive. This variable is picked up by the offload library to setup
1394 // the device appropriately before kernel launch. If the execution mode is
1395 // 'generic', the runtime reserves one warp for the master, otherwise, all
1396 // warps participate in parallel work.
1397 static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
1398                                      bool Mode) {
1399   auto *GVMode =
1400       new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1401                                llvm::GlobalValue::WeakAnyLinkage,
1402                                llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1403                                Twine(Name, "_exec_mode"));
1404   CGM.addCompilerUsedGlobal(GVMode);
1405 }
1406 
1407 void CGOpenMPRuntimeGPU::emitWorkerFunction(WorkerFunctionState &WST) {
1408   ASTContext &Ctx = CGM.getContext();
1409 
1410   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1411   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
1412                     WST.Loc, WST.Loc);
1413   emitWorkerLoop(CGF, WST);
1414   CGF.FinishFunction();
1415 }
1416 
1417 void CGOpenMPRuntimeGPU::emitWorkerLoop(CodeGenFunction &CGF,
1418                                           WorkerFunctionState &WST) {
1419   //
1420   // The workers enter this loop and wait for parallel work from the master.
1421   // When the master encounters a parallel region it sets up the work + variable
1422   // arguments, and wakes up the workers.  The workers first check to see if
1423   // they are required for the parallel region, i.e., within the # of requested
1424   // parallel threads.  The activated workers load the variable arguments and
1425   // execute the parallel work.
1426   //
1427 
1428   CGBuilderTy &Bld = CGF.Builder;
1429 
1430   llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1431   llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1432   llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1433   llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1434   llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1435   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1436 
1437   CGF.EmitBranch(AwaitBB);
1438 
1439   // Workers wait for work from master.
1440   CGF.EmitBlock(AwaitBB);
1441   // Wait for parallel work
1442   syncCTAThreads(CGF);
1443 
1444   Address WorkFn =
1445       CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1446   Address ExecStatus =
1447       CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1448   CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1449   CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1450 
1451   // TODO: Optimize runtime initialization and pass in correct value.
1452   llvm::Value *Args[] = {WorkFn.getPointer()};
1453   llvm::Value *Ret = CGF.EmitRuntimeCall(
1454       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1455   Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
1456 
1457   // On termination condition (workid == 0), exit loop.
1458   llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1459   llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
1460   Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1461 
1462   // Activate requested workers.
1463   CGF.EmitBlock(SelectWorkersBB);
1464   llvm::Value *IsActive =
1465       Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1466   Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
1467 
1468   // Signal start of parallel region.
1469   CGF.EmitBlock(ExecuteBB);
1470   // Skip initialization.
1471   setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1472 
1473   // Process work items: outlined parallel functions.
1474   for (llvm::Function *W : Work) {
1475     // Try to match this outlined function.
1476     llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
1477 
1478     llvm::Value *WorkFnMatch =
1479         Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1480 
1481     llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1482     llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1483     Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1484 
1485     // Execute this outlined function.
1486     CGF.EmitBlock(ExecuteFNBB);
1487 
1488     // Insert call to work function via shared wrapper. The shared
1489     // wrapper takes two arguments:
1490     //   - the parallelism level;
1491     //   - the thread ID;
1492     emitCall(CGF, WST.Loc, W,
1493              {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1494 
1495     // Go to end of parallel region.
1496     CGF.EmitBranch(TerminateBB);
1497 
1498     CGF.EmitBlock(CheckNextBB);
1499   }
1500   // Default case: call to outlined function through pointer if the target
1501   // region makes a declare target call that may contain an orphaned parallel
1502   // directive.
1503   auto *ParallelFnTy =
1504       llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1505                               /*isVarArg=*/false);
1506   llvm::Value *WorkFnCast =
1507       Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
1508   // Insert call to work function via shared wrapper. The shared
1509   // wrapper takes two arguments:
1510   //   - the parallelism level;
1511   //   - the thread ID;
1512   emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
1513            {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1514   // Go to end of parallel region.
1515   CGF.EmitBranch(TerminateBB);
1516 
1517   // Signal end of parallel region.
1518   CGF.EmitBlock(TerminateBB);
1519   CGF.EmitRuntimeCall(
1520       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1521       llvm::None);
1522   CGF.EmitBranch(BarrierBB);
1523 
1524   // All active and inactive workers wait at a barrier after parallel region.
1525   CGF.EmitBlock(BarrierBB);
1526   // Barrier after parallel region.
1527   syncCTAThreads(CGF);
1528   CGF.EmitBranch(AwaitBB);
1529 
1530   // Exit target region.
1531   CGF.EmitBlock(ExitBB);
1532   // Skip initialization.
1533   clearLocThreadIdInsertPt(CGF);
1534 }
1535 
1536 /// Returns specified OpenMP runtime function for the current OpenMP
1537 /// implementation.  Specialized for the NVPTX device.
1538 /// \param Function OpenMP runtime function.
1539 /// \return Specified function.
1540 llvm::FunctionCallee
1541 CGOpenMPRuntimeGPU::createNVPTXRuntimeFunction(unsigned Function) {
1542   llvm::FunctionCallee RTLFn = nullptr;
1543   switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1544   case OMPRTL_NVPTX__kmpc_kernel_init: {
1545     // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1546     // RequiresOMPRuntime);
1547     llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
1548     auto *FnTy =
1549         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1550     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1551     break;
1552   }
1553   case OMPRTL_NVPTX__kmpc_kernel_deinit: {
1554     // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1555     llvm::Type *TypeParams[] = {CGM.Int16Ty};
1556     auto *FnTy =
1557         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1558     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1559     break;
1560   }
1561   case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1562     // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
1563     // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
1564     llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
1565     auto *FnTy =
1566         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1568     break;
1569   }
1570   case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1571     // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1572     llvm::Type *TypeParams[] = {CGM.Int16Ty};
1573     auto *FnTy =
1574         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1575     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
1576     break;
1577   }
1578   case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1579     /// Build void __kmpc_kernel_prepare_parallel(
1580     /// void *outlined_function);
1581     llvm::Type *TypeParams[] = {CGM.Int8PtrTy};
1582     auto *FnTy =
1583         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1584     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1585     break;
1586   }
1587   case OMPRTL_NVPTX__kmpc_kernel_parallel: {
1588     /// Build bool __kmpc_kernel_parallel(void **outlined_function);
1589     llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy};
1590     llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1591     auto *FnTy =
1592         llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1593     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1594     break;
1595   }
1596   case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1597     /// Build void __kmpc_kernel_end_parallel();
1598     auto *FnTy =
1599         llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1600     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1601     break;
1602   }
1603   case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1604     // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1605     // global_tid);
1606     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1607     auto *FnTy =
1608         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1609     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1610     break;
1611   }
1612   case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1613     // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1614     // global_tid);
1615     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1616     auto *FnTy =
1617         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1618     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1619     break;
1620   }
1621   case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1622     // Build int32_t __kmpc_shuffle_int32(int32_t element,
1623     // int16_t lane_offset, int16_t warp_size);
1624     llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
1625     auto *FnTy =
1626         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1627     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1628     break;
1629   }
1630   case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1631     // Build int64_t __kmpc_shuffle_int64(int64_t element,
1632     // int16_t lane_offset, int16_t warp_size);
1633     llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
1634     auto *FnTy =
1635         llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1636     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1637     break;
1638   }
1639   case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
1640     // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1641     // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1642     // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1643     // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1644     // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
1645     llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1646                                              CGM.Int16Ty, CGM.Int16Ty};
1647     auto *ShuffleReduceFnTy =
1648         llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1649                                 /*isVarArg=*/false);
1650     llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1651     auto *InterWarpCopyFnTy =
1652         llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1653                                 /*isVarArg=*/false);
1654     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1655                                 CGM.Int32Ty,
1656                                 CGM.Int32Ty,
1657                                 CGM.SizeTy,
1658                                 CGM.VoidPtrTy,
1659                                 ShuffleReduceFnTy->getPointerTo(),
1660                                 InterWarpCopyFnTy->getPointerTo()};
1661     auto *FnTy =
1662         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1663     RTLFn = CGM.CreateRuntimeFunction(
1664         FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
1665     break;
1666   }
1667   case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1668     // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1669     llvm::Type *TypeParams[] = {CGM.Int32Ty};
1670     auto *FnTy =
1671         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1672     RTLFn = CGM.CreateRuntimeFunction(
1673         FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1674     break;
1675   }
1676   case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1677     // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1678     // global_tid, void *global_buffer, int32_t num_of_records, void*
1679     // reduce_data,
1680     // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1681     // lane_offset, int16_t shortCircuit),
1682     // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1683     // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1684     // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1685     // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1686     // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1687     // *buffer, int idx, void *reduce_data));
1688     llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1689                                              CGM.Int16Ty, CGM.Int16Ty};
1690     auto *ShuffleReduceFnTy =
1691         llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1692                                 /*isVarArg=*/false);
1693     llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1694     auto *InterWarpCopyFnTy =
1695         llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1696                                 /*isVarArg=*/false);
1697     llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1698                                           CGM.VoidPtrTy};
1699     auto *GlobalListFnTy =
1700         llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1701                                 /*isVarArg=*/false);
1702     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1703                                 CGM.Int32Ty,
1704                                 CGM.VoidPtrTy,
1705                                 CGM.Int32Ty,
1706                                 CGM.VoidPtrTy,
1707                                 ShuffleReduceFnTy->getPointerTo(),
1708                                 InterWarpCopyFnTy->getPointerTo(),
1709                                 GlobalListFnTy->getPointerTo(),
1710                                 GlobalListFnTy->getPointerTo(),
1711                                 GlobalListFnTy->getPointerTo(),
1712                                 GlobalListFnTy->getPointerTo()};
1713     auto *FnTy =
1714         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1715     RTLFn = CGM.CreateRuntimeFunction(
1716         FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
1717     break;
1718   }
1719   case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1720     /// Build void __kmpc_data_sharing_init_stack();
1721     auto *FnTy =
1722         llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1723     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1724     break;
1725   }
1726   case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1727     /// Build void __kmpc_data_sharing_init_stack_spmd();
1728     auto *FnTy =
1729         llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1730     RTLFn =
1731         CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
1732     break;
1733   }
1734   case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1735     // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
1736     // int16_t UseSharedMemory);
1737     llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
1738     auto *FnTy =
1739         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1740     RTLFn = CGM.CreateRuntimeFunction(
1741         FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
1742     break;
1743   }
1744   case OMPRTL_NVPTX__kmpc_data_sharing_push_stack: {
1745     // Build void *__kmpc_data_sharing_push_stack(size_t size, int16_t
1746     // UseSharedMemory);
1747     llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
1748     auto *FnTy =
1749         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1750     RTLFn = CGM.CreateRuntimeFunction(
1751         FnTy, /*Name=*/"__kmpc_data_sharing_push_stack");
1752     break;
1753   }
1754   case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1755     // Build void __kmpc_data_sharing_pop_stack(void *a);
1756     llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
1757     auto *FnTy =
1758         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1759     RTLFn = CGM.CreateRuntimeFunction(FnTy,
1760                                       /*Name=*/"__kmpc_data_sharing_pop_stack");
1761     break;
1762   }
1763   case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1764     /// Build void __kmpc_begin_sharing_variables(void ***args,
1765     /// size_t n_args);
1766     llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
1767     auto *FnTy =
1768         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1770     break;
1771   }
1772   case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1773     /// Build void __kmpc_end_sharing_variables();
1774     auto *FnTy =
1775         llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1776     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1777     break;
1778   }
1779   case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1780     /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1781     llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
1782     auto *FnTy =
1783         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1784     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1785     break;
1786   }
1787   case OMPRTL_NVPTX__kmpc_parallel_level: {
1788     // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1789     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1790     auto *FnTy =
1791         llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1792     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1793     break;
1794   }
1795   case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1796     // Build int8_t __kmpc_is_spmd_exec_mode();
1797     auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1798     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1799     break;
1800   }
1801   case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
1802     // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1803     // const void *buf, size_t size, int16_t is_shared, const void **res);
1804     llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1805                                 CGM.Int16Ty, CGM.VoidPtrPtrTy};
1806     auto *FnTy =
1807         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1808     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1809     break;
1810   }
1811   case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
1812     // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1813     // int16_t is_shared);
1814     llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
1815     auto *FnTy =
1816         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1817     RTLFn =
1818         CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1819     break;
1820   }
1821   case OMPRTL__kmpc_barrier: {
1822     // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1823     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1824     auto *FnTy =
1825         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1826     RTLFn =
1827         CGM.CreateConvergentRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1828     break;
1829   }
1830   case OMPRTL__kmpc_barrier_simple_spmd: {
1831     // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1832     // global_tid);
1833     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1834     auto *FnTy =
1835         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1836     RTLFn = CGM.CreateConvergentRuntimeFunction(
1837         FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
1838     break;
1839   }
1840   case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1841     // Build int32_t __kmpc_warp_active_thread_mask(void);
1842     auto *FnTy =
1843         llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1844     RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1845     break;
1846   }
1847   case OMPRTL_NVPTX__kmpc_syncwarp: {
1848     // Build void __kmpc_syncwarp(kmp_int32 Mask);
1849     auto *FnTy =
1850         llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1851     RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_syncwarp");
1852     break;
1853   }
1854   }
1855   return RTLFn;
1856 }
1857 
1858 void CGOpenMPRuntimeGPU::createOffloadEntry(llvm::Constant *ID,
1859                                               llvm::Constant *Addr,
1860                                               uint64_t Size, int32_t,
1861                                               llvm::GlobalValue::LinkageTypes) {
1862   // TODO: Add support for global variables on the device after declare target
1863   // support.
1864   if (!isa<llvm::Function>(Addr))
1865     return;
1866   llvm::Module &M = CGM.getModule();
1867   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1868 
1869   // Get "nvvm.annotations" metadata node
1870   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1871 
1872   llvm::Metadata *MDVals[] = {
1873       llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
1874       llvm::ConstantAsMetadata::get(
1875           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1876   // Append metadata to nvvm.annotations
1877   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1878 }
1879 
1880 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
1881     const OMPExecutableDirective &D, StringRef ParentName,
1882     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
1883     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
1884   if (!IsOffloadEntry) // Nothing to do.
1885     return;
1886 
1887   assert(!ParentName.empty() && "Invalid target region parent name!");
1888 
1889   bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
1890   if (Mode)
1891     emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1892                    CodeGen);
1893   else
1894     emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1895                       CodeGen);
1896 
1897   setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
1898 }
1899 
1900 namespace {
1901 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1902 /// Enum for accesseing the reserved_2 field of the ident_t struct.
1903 enum ModeFlagsTy : unsigned {
1904   /// Bit set to 1 when in SPMD mode.
1905   KMP_IDENT_SPMD_MODE = 0x01,
1906   /// Bit set to 1 when a simplified runtime is used.
1907   KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1908   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1909 };
1910 
1911 /// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1912 static const ModeFlagsTy UndefinedMode =
1913     (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1914 } // anonymous namespace
1915 
1916 unsigned CGOpenMPRuntimeGPU::getDefaultLocationReserved2Flags() const {
1917   switch (getExecutionMode()) {
1918   case EM_SPMD:
1919     if (requiresFullRuntime())
1920       return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1921     return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1922   case EM_NonSPMD:
1923     assert(requiresFullRuntime() && "Expected full runtime.");
1924     return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1925   case EM_Unknown:
1926     return UndefinedMode;
1927   }
1928   llvm_unreachable("Unknown flags are requested.");
1929 }
1930 
1931 CGOpenMPRuntimeGPU::CGOpenMPRuntimeGPU(CodeGenModule &CGM)
1932     : CGOpenMPRuntime(CGM, "_", "$") {
1933   if (!CGM.getLangOpts().OpenMPIsDevice)
1934     llvm_unreachable("OpenMP NVPTX can only handle device code.");
1935 }
1936 
1937 void CGOpenMPRuntimeGPU::emitProcBindClause(CodeGenFunction &CGF,
1938                                               ProcBindKind ProcBind,
1939                                               SourceLocation Loc) {
1940   // Do nothing in case of SPMD mode and L0 parallel.
1941   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1942     return;
1943 
1944   CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1945 }
1946 
1947 void CGOpenMPRuntimeGPU::emitNumThreadsClause(CodeGenFunction &CGF,
1948                                                 llvm::Value *NumThreads,
1949                                                 SourceLocation Loc) {
1950   // Do nothing in case of SPMD mode and L0 parallel.
1951   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1952     return;
1953 
1954   CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1955 }
1956 
1957 void CGOpenMPRuntimeGPU::emitNumTeamsClause(CodeGenFunction &CGF,
1958                                               const Expr *NumTeams,
1959                                               const Expr *ThreadLimit,
1960                                               SourceLocation Loc) {}
1961 
1962 llvm::Function *CGOpenMPRuntimeGPU::emitParallelOutlinedFunction(
1963     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1964     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1965   // Emit target region as a standalone region.
1966   class NVPTXPrePostActionTy : public PrePostActionTy {
1967     bool &IsInParallelRegion;
1968     bool PrevIsInParallelRegion;
1969 
1970   public:
1971     NVPTXPrePostActionTy(bool &IsInParallelRegion)
1972         : IsInParallelRegion(IsInParallelRegion) {}
1973     void Enter(CodeGenFunction &CGF) override {
1974       PrevIsInParallelRegion = IsInParallelRegion;
1975       IsInParallelRegion = true;
1976     }
1977     void Exit(CodeGenFunction &CGF) override {
1978       IsInParallelRegion = PrevIsInParallelRegion;
1979     }
1980   } Action(IsInParallelRegion);
1981   CodeGen.setAction(Action);
1982   bool PrevIsInTTDRegion = IsInTTDRegion;
1983   IsInTTDRegion = false;
1984   bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1985   IsInTargetMasterThreadRegion = false;
1986   auto *OutlinedFun =
1987       cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1988           D, ThreadIDVar, InnermostKind, CodeGen));
1989   if (CGM.getLangOpts().Optimize) {
1990     OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1991     OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1992     OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1993   }
1994   IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
1995   IsInTTDRegion = PrevIsInTTDRegion;
1996   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD &&
1997       !IsInParallelRegion) {
1998     llvm::Function *WrapperFun =
1999         createParallelDataSharingWrapper(OutlinedFun, D);
2000     WrapperFunctionsMap[OutlinedFun] = WrapperFun;
2001   }
2002 
2003   return OutlinedFun;
2004 }
2005 
2006 /// Get list of lastprivate variables from the teams distribute ... or
2007 /// teams {distribute ...} directives.
2008 static void
2009 getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2010                              llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2011   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2012          "expected teams directive.");
2013   const OMPExecutableDirective *Dir = &D;
2014   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
2015     if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
2016             Ctx,
2017             D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2018                 /*IgnoreCaptured=*/true))) {
2019       Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
2020       if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2021         Dir = nullptr;
2022     }
2023   }
2024   if (!Dir)
2025     return;
2026   for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
2027     for (const Expr *E : C->getVarRefs())
2028       Vars.push_back(getPrivateItem(E));
2029   }
2030 }
2031 
2032 /// Get list of reduction variables from the teams ... directives.
2033 static void
2034 getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2035                       llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2036   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2037          "expected teams directive.");
2038   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2039     for (const Expr *E : C->privates())
2040       Vars.push_back(getPrivateItem(E));
2041   }
2042 }
2043 
2044 llvm::Function *CGOpenMPRuntimeGPU::emitTeamsOutlinedFunction(
2045     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2046     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
2047   SourceLocation Loc = D.getBeginLoc();
2048 
2049   const RecordDecl *GlobalizedRD = nullptr;
2050   llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
2051   llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
2052   unsigned WarpSize = CGM.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
2053   // Globalize team reductions variable unconditionally in all modes.
2054   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
2055     getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
2056   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
2057     getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2058     if (!LastPrivatesReductions.empty()) {
2059       GlobalizedRD = ::buildRecordForGlobalizedVars(
2060           CGM.getContext(), llvm::None, LastPrivatesReductions,
2061           MappedDeclsFields, WarpSize);
2062     }
2063   } else if (!LastPrivatesReductions.empty()) {
2064     assert(!TeamAndReductions.first &&
2065            "Previous team declaration is not expected.");
2066     TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2067     std::swap(TeamAndReductions.second, LastPrivatesReductions);
2068   }
2069 
2070   // Emit target region as a standalone region.
2071   class NVPTXPrePostActionTy : public PrePostActionTy {
2072     SourceLocation &Loc;
2073     const RecordDecl *GlobalizedRD;
2074     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2075         &MappedDeclsFields;
2076 
2077   public:
2078     NVPTXPrePostActionTy(
2079         SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2080         llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2081             &MappedDeclsFields)
2082         : Loc(Loc), GlobalizedRD(GlobalizedRD),
2083           MappedDeclsFields(MappedDeclsFields) {}
2084     void Enter(CodeGenFunction &CGF) override {
2085       auto &Rt =
2086           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2087       if (GlobalizedRD) {
2088         auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2089         I->getSecond().GlobalRecord = GlobalizedRD;
2090         I->getSecond().MappedParams =
2091             std::make_unique<CodeGenFunction::OMPMapVars>();
2092         DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2093         for (const auto &Pair : MappedDeclsFields) {
2094           assert(Pair.getFirst()->isCanonicalDecl() &&
2095                  "Expected canonical declaration");
2096           Data.insert(std::make_pair(Pair.getFirst(),
2097                                      MappedVarData(Pair.getSecond(),
2098                                                    /*IsOnePerTeam=*/true)));
2099         }
2100       }
2101       Rt.emitGenericVarsProlog(CGF, Loc);
2102     }
2103     void Exit(CodeGenFunction &CGF) override {
2104       static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
2105           .emitGenericVarsEpilog(CGF);
2106     }
2107   } Action(Loc, GlobalizedRD, MappedDeclsFields);
2108   CodeGen.setAction(Action);
2109   llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2110       D, ThreadIDVar, InnermostKind, CodeGen);
2111   if (CGM.getLangOpts().Optimize) {
2112     OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2113     OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2114     OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2115   }
2116 
2117   return OutlinedFun;
2118 }
2119 
2120 void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
2121                                                  SourceLocation Loc,
2122                                                  bool WithSPMDCheck) {
2123   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
2124       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
2125     return;
2126 
2127   CGBuilderTy &Bld = CGF.Builder;
2128 
2129   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2130   if (I == FunctionGlobalizedDecls.end())
2131     return;
2132   if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
2133     QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
2134     QualType SecGlobalRecTy;
2135 
2136     // Recover pointer to this function's global record. The runtime will
2137     // handle the specifics of the allocation of the memory.
2138     // Use actual memory size of the record including the padding
2139     // for alignment purposes.
2140     unsigned Alignment =
2141         CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2142     unsigned GlobalRecordSize =
2143         CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
2144     GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2145 
2146     llvm::PointerType *GlobalRecPtrTy =
2147         CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
2148     llvm::Value *GlobalRecCastAddr;
2149     llvm::Value *IsTTD = nullptr;
2150     if (!IsInTTDRegion &&
2151         (WithSPMDCheck ||
2152          getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
2153       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2154       llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2155       llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2156       if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2157         llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2158         llvm::Value *ThreadID = getThreadID(CGF, Loc);
2159         llvm::Value *PL = CGF.EmitRuntimeCall(
2160             createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2161             {RTLoc, ThreadID});
2162         IsTTD = Bld.CreateIsNull(PL);
2163       }
2164       llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2165           createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2166       Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2167       // There is no need to emit line number for unconditional branch.
2168       (void)ApplyDebugLocation::CreateEmpty(CGF);
2169       CGF.EmitBlock(SPMDBB);
2170       Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2171                                CharUnits::fromQuantity(Alignment));
2172       CGF.EmitBranch(ExitBB);
2173       // There is no need to emit line number for unconditional branch.
2174       (void)ApplyDebugLocation::CreateEmpty(CGF);
2175       CGF.EmitBlock(NonSPMDBB);
2176       llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2177       if (const RecordDecl *SecGlobalizedVarsRecord =
2178               I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2179         SecGlobalRecTy =
2180             CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2181 
2182         // Recover pointer to this function's global record. The runtime will
2183         // handle the specifics of the allocation of the memory.
2184         // Use actual memory size of the record including the padding
2185         // for alignment purposes.
2186         unsigned Alignment =
2187             CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2188         unsigned GlobalRecordSize =
2189             CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2190         GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2191         Size = Bld.CreateSelect(
2192             IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2193       }
2194       // TODO: allow the usage of shared memory to be controlled by
2195       // the user, for now, default to global.
2196       llvm::Value *GlobalRecordSizeArg[] = {
2197           Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2198       llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2199           createNVPTXRuntimeFunction(
2200               OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2201           GlobalRecordSizeArg);
2202       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2203           GlobalRecValue, GlobalRecPtrTy);
2204       CGF.EmitBlock(ExitBB);
2205       auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
2206                                 /*NumReservedValues=*/2, "_select_stack");
2207       Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2208       Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2209       GlobalRecCastAddr = Phi;
2210       I->getSecond().GlobalRecordAddr = Phi;
2211       I->getSecond().IsInSPMDModeFlag = IsSPMD;
2212     } else if (!CGM.getLangOpts().OpenMPCUDATargetParallel && IsInTTDRegion) {
2213       assert(GlobalizedRecords.back().Records.size() < 2 &&
2214              "Expected less than 2 globalized records: one for target and one "
2215              "for teams.");
2216       unsigned Offset = 0;
2217       for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2218         QualType RDTy = CGM.getContext().getRecordType(RD);
2219         unsigned Alignment =
2220             CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2221         unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2222         Offset =
2223             llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2224       }
2225       unsigned Alignment =
2226           CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2227       Offset = llvm::alignTo(Offset, Alignment);
2228       GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2229       ++GlobalizedRecords.back().RegionCounter;
2230       if (GlobalizedRecords.back().Records.size() == 1) {
2231         assert(KernelStaticGlobalized &&
2232                "Kernel static pointer must be initialized already.");
2233         auto *UseSharedMemory = new llvm::GlobalVariable(
2234             CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2235             llvm::GlobalValue::InternalLinkage, nullptr,
2236             "_openmp_static_kernel$is_shared");
2237         UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2238         QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2239             /*DestWidth=*/16, /*Signed=*/0);
2240         llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2241             Address(UseSharedMemory,
2242                     CGM.getContext().getTypeAlignInChars(Int16Ty)),
2243             /*Volatile=*/false, Int16Ty, Loc);
2244         auto *StaticGlobalized = new llvm::GlobalVariable(
2245             CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
2246             llvm::GlobalValue::CommonLinkage, nullptr);
2247         auto *RecSize = new llvm::GlobalVariable(
2248             CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2249             llvm::GlobalValue::InternalLinkage, nullptr,
2250             "_openmp_static_kernel$size");
2251         RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2252         llvm::Value *Ld = CGF.EmitLoadOfScalar(
2253             Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
2254             CGM.getContext().getSizeType(), Loc);
2255         llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2256             KernelStaticGlobalized, CGM.VoidPtrPtrTy);
2257         llvm::Value *GlobalRecordSizeArg[] = {
2258             llvm::ConstantInt::get(
2259                 CGM.Int16Ty,
2260                 getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD ? 1 : 0),
2261             StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
2262         CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2263                                 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2264                             GlobalRecordSizeArg);
2265         GlobalizedRecords.back().Buffer = StaticGlobalized;
2266         GlobalizedRecords.back().RecSize = RecSize;
2267         GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2268         GlobalizedRecords.back().Loc = Loc;
2269       }
2270       assert(KernelStaticGlobalized && "Global address must be set already.");
2271       Address FrameAddr = CGF.EmitLoadOfPointer(
2272           Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2273           CGM.getContext()
2274               .getPointerType(CGM.getContext().VoidPtrTy)
2275               .castAs<PointerType>());
2276       llvm::Value *GlobalRecValue =
2277           Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
2278       I->getSecond().GlobalRecordAddr = GlobalRecValue;
2279       I->getSecond().IsInSPMDModeFlag = nullptr;
2280       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2281           GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
2282     } else {
2283       // TODO: allow the usage of shared memory to be controlled by
2284       // the user, for now, default to global.
2285       bool UseSharedMemory =
2286           IsInTTDRegion && GlobalRecordSize <= SharedMemorySize;
2287       llvm::Value *GlobalRecordSizeArg[] = {
2288           llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2289           CGF.Builder.getInt16(UseSharedMemory ? 1 : 0)};
2290       llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2291           createNVPTXRuntimeFunction(
2292               IsInTTDRegion
2293                   ? OMPRTL_NVPTX__kmpc_data_sharing_push_stack
2294                   : OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2295           GlobalRecordSizeArg);
2296       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2297           GlobalRecValue, GlobalRecPtrTy);
2298       I->getSecond().GlobalRecordAddr = GlobalRecValue;
2299       I->getSecond().IsInSPMDModeFlag = nullptr;
2300     }
2301     LValue Base =
2302         CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
2303 
2304     // Emit the "global alloca" which is a GEP from the global declaration
2305     // record using the pointer returned by the runtime.
2306     LValue SecBase;
2307     decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2308     if (IsTTD) {
2309       SecIt = I->getSecond().SecondaryLocalVarData->begin();
2310       llvm::PointerType *SecGlobalRecPtrTy =
2311           CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2312       SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2313           Bld.CreatePointerBitCastOrAddrSpaceCast(
2314               I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2315           SecGlobalRecTy);
2316     }
2317     for (auto &Rec : I->getSecond().LocalVarData) {
2318       bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2319       llvm::Value *ParValue;
2320       if (EscapedParam) {
2321         const auto *VD = cast<VarDecl>(Rec.first);
2322         LValue ParLVal =
2323             CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2324         ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2325       }
2326       LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2327       // Emit VarAddr basing on lane-id if required.
2328       QualType VarTy;
2329       if (Rec.second.IsOnePerTeam) {
2330         VarTy = Rec.second.FD->getType();
2331       } else {
2332         llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2333             VarAddr.getAddress(CGF).getPointer(),
2334             {Bld.getInt32(0), getNVPTXLaneID(CGF)});
2335         VarTy =
2336             Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
2337         VarAddr = CGF.MakeAddrLValue(
2338             Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2339             AlignmentSource::Decl);
2340       }
2341       Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
2342       if (!IsInTTDRegion &&
2343           (WithSPMDCheck ||
2344            getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
2345         assert(I->getSecond().IsInSPMDModeFlag &&
2346                "Expected unknown execution mode or required SPMD check.");
2347         if (IsTTD) {
2348           assert(SecIt->second.IsOnePerTeam &&
2349                  "Secondary glob data must be one per team.");
2350           LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2351           VarAddr.setAddress(
2352               Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(CGF),
2353                                        VarAddr.getPointer(CGF)),
2354                       VarAddr.getAlignment()));
2355           Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
2356         }
2357         Address GlobalPtr = Rec.second.PrivateAddr;
2358         Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2359         Rec.second.PrivateAddr = Address(
2360             Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2361                              LocalAddr.getPointer(), GlobalPtr.getPointer()),
2362             LocalAddr.getAlignment());
2363       }
2364       if (EscapedParam) {
2365         const auto *VD = cast<VarDecl>(Rec.first);
2366         CGF.EmitStoreOfScalar(ParValue, VarAddr);
2367         I->getSecond().MappedParams->setVarAddr(CGF, VD,
2368                                                 VarAddr.getAddress(CGF));
2369       }
2370       if (IsTTD)
2371         ++SecIt;
2372     }
2373   }
2374   for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2375     // Recover pointer to this function's global record. The runtime will
2376     // handle the specifics of the allocation of the memory.
2377     // Use actual memory size of the record including the padding
2378     // for alignment purposes.
2379     CGBuilderTy &Bld = CGF.Builder;
2380     llvm::Value *Size = CGF.getTypeSize(VD->getType());
2381     CharUnits Align = CGM.getContext().getDeclAlign(VD);
2382     Size = Bld.CreateNUWAdd(
2383         Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2384     llvm::Value *AlignVal =
2385         llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2386     Size = Bld.CreateUDiv(Size, AlignVal);
2387     Size = Bld.CreateNUWMul(Size, AlignVal);
2388     // TODO: allow the usage of shared memory to be controlled by
2389     // the user, for now, default to global.
2390     llvm::Value *GlobalRecordSizeArg[] = {
2391         Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2392     llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2393         createNVPTXRuntimeFunction(
2394             OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2395         GlobalRecordSizeArg);
2396     llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2397         GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2398     LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2399                                      CGM.getContext().getDeclAlign(VD),
2400                                      AlignmentSource::Decl);
2401     I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2402                                             Base.getAddress(CGF));
2403     I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
2404   }
2405   I->getSecond().MappedParams->apply(CGF);
2406 }
2407 
2408 void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF,
2409                                                  bool WithSPMDCheck) {
2410   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
2411       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
2412     return;
2413 
2414   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2415   if (I != FunctionGlobalizedDecls.end()) {
2416     I->getSecond().MappedParams->restore(CGF);
2417     if (!CGF.HaveInsertPoint())
2418       return;
2419     for (llvm::Value *Addr :
2420          llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2421       CGF.EmitRuntimeCall(
2422           createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2423           Addr);
2424     }
2425     if (I->getSecond().GlobalRecordAddr) {
2426       if (!IsInTTDRegion &&
2427           (WithSPMDCheck ||
2428            getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
2429         CGBuilderTy &Bld = CGF.Builder;
2430         llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2431         llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2432         Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2433         // There is no need to emit line number for unconditional branch.
2434         (void)ApplyDebugLocation::CreateEmpty(CGF);
2435         CGF.EmitBlock(NonSPMDBB);
2436         CGF.EmitRuntimeCall(
2437             createNVPTXRuntimeFunction(
2438                 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2439             CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2440         CGF.EmitBlock(ExitBB);
2441       } else if (!CGM.getLangOpts().OpenMPCUDATargetParallel && IsInTTDRegion) {
2442         assert(GlobalizedRecords.back().RegionCounter > 0 &&
2443                "region counter must be > 0.");
2444         --GlobalizedRecords.back().RegionCounter;
2445         // Emit the restore function only in the target region.
2446         if (GlobalizedRecords.back().RegionCounter == 0) {
2447           QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2448               /*DestWidth=*/16, /*Signed=*/0);
2449           llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2450               Address(GlobalizedRecords.back().UseSharedMemory,
2451                       CGM.getContext().getTypeAlignInChars(Int16Ty)),
2452               /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
2453           llvm::Value *Args[] = {
2454               llvm::ConstantInt::get(
2455                   CGM.Int16Ty,
2456                   getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD ? 1 : 0),
2457               IsInSharedMemory};
2458           CGF.EmitRuntimeCall(
2459               createNVPTXRuntimeFunction(
2460                   OMPRTL_NVPTX__kmpc_restore_team_static_memory),
2461               Args);
2462         }
2463       } else {
2464         CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2465                                 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2466                             I->getSecond().GlobalRecordAddr);
2467       }
2468     }
2469   }
2470 }
2471 
2472 void CGOpenMPRuntimeGPU::emitTeamsCall(CodeGenFunction &CGF,
2473                                          const OMPExecutableDirective &D,
2474                                          SourceLocation Loc,
2475                                          llvm::Function *OutlinedFn,
2476                                          ArrayRef<llvm::Value *> CapturedVars) {
2477   if (!CGF.HaveInsertPoint())
2478     return;
2479 
2480   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2481                                                       /*Name=*/".zero.addr");
2482   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2483   llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2484   OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
2485   OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2486   OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2487   emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2488 }
2489 
2490 void CGOpenMPRuntimeGPU::emitParallelCall(
2491     CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2492     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2493   if (!CGF.HaveInsertPoint())
2494     return;
2495 
2496   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
2497     emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2498   else
2499     emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2500 }
2501 
2502 void CGOpenMPRuntimeGPU::emitNonSPMDParallelCall(
2503     CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2504     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2505   llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
2506 
2507   // Force inline this outlined function at its call site.
2508   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2509 
2510   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2511                                                       /*Name=*/".zero.addr");
2512   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2513   // ThreadId for serialized parallels is 0.
2514   Address ThreadIDAddr = ZeroAddr;
2515   auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
2516                        CodeGenFunction &CGF, PrePostActionTy &Action) {
2517     Action.Enter(CGF);
2518 
2519     Address ZeroAddr =
2520         CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2521                                          /*Name=*/".bound.zero.addr");
2522     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2523     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2524     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2525     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2526     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2527     emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2528   };
2529   auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2530                                         PrePostActionTy &) {
2531 
2532     RegionCodeGenTy RCG(CodeGen);
2533     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2534     llvm::Value *ThreadID = getThreadID(CGF, Loc);
2535     llvm::Value *Args[] = {RTLoc, ThreadID};
2536 
2537     NVPTXActionTy Action(
2538         createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2539         Args,
2540         createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2541         Args);
2542     RCG.setAction(Action);
2543     RCG(CGF);
2544   };
2545 
2546   auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2547                                                   PrePostActionTy &Action) {
2548     CGBuilderTy &Bld = CGF.Builder;
2549     llvm::Function *WFn = WrapperFunctionsMap[Fn];
2550     assert(WFn && "Wrapper function does not exist!");
2551     llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2552 
2553     // Prepare for parallel region. Indicate the outlined function.
2554     llvm::Value *Args[] = {ID};
2555     CGF.EmitRuntimeCall(
2556         createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2557         Args);
2558 
2559     // Create a private scope that will globalize the arguments
2560     // passed from the outside of the target region.
2561     CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2562 
2563     // There's something to share.
2564     if (!CapturedVars.empty()) {
2565       // Prepare for parallel region. Indicate the outlined function.
2566       Address SharedArgs =
2567           CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2568       llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2569 
2570       llvm::Value *DataSharingArgs[] = {
2571           SharedArgsPtr,
2572           llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2573       CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2574                               OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2575                           DataSharingArgs);
2576 
2577       // Store variable address in a list of references to pass to workers.
2578       unsigned Idx = 0;
2579       ASTContext &Ctx = CGF.getContext();
2580       Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2581           SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2582                           .castAs<PointerType>());
2583       for (llvm::Value *V : CapturedVars) {
2584         Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
2585         llvm::Value *PtrV;
2586         if (V->getType()->isIntegerTy())
2587           PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2588         else
2589           PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
2590         CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2591                               Ctx.getPointerType(Ctx.VoidPtrTy));
2592         ++Idx;
2593       }
2594     }
2595 
2596     // Activate workers. This barrier is used by the master to signal
2597     // work for the workers.
2598     syncCTAThreads(CGF);
2599 
2600     // OpenMP [2.5, Parallel Construct, p.49]
2601     // There is an implied barrier at the end of a parallel region. After the
2602     // end of a parallel region, only the master thread of the team resumes
2603     // execution of the enclosing task region.
2604     //
2605     // The master waits at this barrier until all workers are done.
2606     syncCTAThreads(CGF);
2607 
2608     if (!CapturedVars.empty())
2609       CGF.EmitRuntimeCall(
2610           createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2611 
2612     // Remember for post-processing in worker loop.
2613     Work.emplace_back(WFn);
2614   };
2615 
2616   auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2617                              CodeGenFunction &CGF, PrePostActionTy &Action) {
2618     if (IsInParallelRegion) {
2619       SeqGen(CGF, Action);
2620     } else if (IsInTargetMasterThreadRegion) {
2621       L0ParallelGen(CGF, Action);
2622     } else {
2623       // Check for master and then parallelism:
2624       // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
2625       //   Serialized execution.
2626       // } else {
2627       //   Worker call.
2628       // }
2629       CGBuilderTy &Bld = CGF.Builder;
2630       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2631       llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2632       llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
2633       llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
2634       llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2635           createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2636       Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
2637       // There is no need to emit line number for unconditional branch.
2638       (void)ApplyDebugLocation::CreateEmpty(CGF);
2639       CGF.EmitBlock(ParallelCheckBB);
2640       llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2641       llvm::Value *ThreadID = getThreadID(CGF, Loc);
2642       llvm::Value *PL = CGF.EmitRuntimeCall(
2643           createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2644           {RTLoc, ThreadID});
2645       llvm::Value *Res = Bld.CreateIsNotNull(PL);
2646       Bld.CreateCondBr(Res, SeqBB, MasterBB);
2647       CGF.EmitBlock(SeqBB);
2648       SeqGen(CGF, Action);
2649       CGF.EmitBranch(ExitBB);
2650       // There is no need to emit line number for unconditional branch.
2651       (void)ApplyDebugLocation::CreateEmpty(CGF);
2652       CGF.EmitBlock(MasterBB);
2653       L0ParallelGen(CGF, Action);
2654       CGF.EmitBranch(ExitBB);
2655       // There is no need to emit line number for unconditional branch.
2656       (void)ApplyDebugLocation::CreateEmpty(CGF);
2657       // Emit the continuation block for code after the if.
2658       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2659     }
2660   };
2661 
2662   if (IfCond) {
2663     emitIfClause(CGF, IfCond, LNParallelGen, SeqGen);
2664   } else {
2665     CodeGenFunction::RunCleanupsScope Scope(CGF);
2666     RegionCodeGenTy ThenRCG(LNParallelGen);
2667     ThenRCG(CGF);
2668   }
2669 }
2670 
2671 void CGOpenMPRuntimeGPU::emitSPMDParallelCall(
2672     CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2673     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2674   // Just call the outlined function to execute the parallel region.
2675   // OutlinedFn(&GTid, &zero, CapturedStruct);
2676   //
2677   llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2678 
2679   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2680                                                       /*Name=*/".zero.addr");
2681   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2682   // ThreadId for serialized parallels is 0.
2683   Address ThreadIDAddr = ZeroAddr;
2684   auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2685                        CodeGenFunction &CGF, PrePostActionTy &Action) {
2686     Action.Enter(CGF);
2687 
2688     Address ZeroAddr =
2689         CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2690                                          /*Name=*/".bound.zero.addr");
2691     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2692     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2693     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2694     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2695     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2696     emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2697   };
2698   auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2699                                         PrePostActionTy &) {
2700 
2701     RegionCodeGenTy RCG(CodeGen);
2702     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2703     llvm::Value *ThreadID = getThreadID(CGF, Loc);
2704     llvm::Value *Args[] = {RTLoc, ThreadID};
2705 
2706     NVPTXActionTy Action(
2707         createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2708         Args,
2709         createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2710         Args);
2711     RCG.setAction(Action);
2712     RCG(CGF);
2713   };
2714 
2715   if (IsInTargetMasterThreadRegion) {
2716     // In the worker need to use the real thread id.
2717     ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
2718     RegionCodeGenTy RCG(CodeGen);
2719     RCG(CGF);
2720   } else {
2721     // If we are not in the target region, it is definitely L2 parallelism or
2722     // more, because for SPMD mode we always has L1 parallel level, sowe don't
2723     // need to check for orphaned directives.
2724     RegionCodeGenTy RCG(SeqGen);
2725     RCG(CGF);
2726   }
2727 }
2728 
2729 void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
2730   // Always emit simple barriers!
2731   if (!CGF.HaveInsertPoint())
2732     return;
2733   // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2734   // This function does not use parameters, so we can emit just default values.
2735   llvm::Value *Args[] = {
2736       llvm::ConstantPointerNull::get(
2737           cast<llvm::PointerType>(getIdentTyPointerTy())),
2738       llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2739   llvm::CallInst *Call = CGF.EmitRuntimeCall(
2740       createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2741   Call->setConvergent();
2742 }
2743 
2744 void CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
2745                                            SourceLocation Loc,
2746                                            OpenMPDirectiveKind Kind, bool,
2747                                            bool) {
2748   // Always emit simple barriers!
2749   if (!CGF.HaveInsertPoint())
2750     return;
2751   // Build call __kmpc_cancel_barrier(loc, thread_id);
2752   unsigned Flags = getDefaultFlagsForBarriers(Kind);
2753   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2754                          getThreadID(CGF, Loc)};
2755   llvm::CallInst *Call = CGF.EmitRuntimeCall(
2756       createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2757   Call->setConvergent();
2758 }
2759 
2760 void CGOpenMPRuntimeGPU::emitCriticalRegion(
2761     CodeGenFunction &CGF, StringRef CriticalName,
2762     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2763     const Expr *Hint) {
2764   llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2765   llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2766   llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2767   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2768   llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2769 
2770   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2771 
2772   // Get the mask of active threads in the warp.
2773   llvm::Value *Mask = CGF.EmitRuntimeCall(
2774       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
2775   // Fetch team-local id of the thread.
2776   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
2777 
2778   // Get the width of the team.
2779   llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
2780 
2781   // Initialize the counter variable for the loop.
2782   QualType Int32Ty =
2783       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2784   Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2785   LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2786   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2787                         /*isInit=*/true);
2788 
2789   // Block checks if loop counter exceeds upper bound.
2790   CGF.EmitBlock(LoopBB);
2791   llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2792   llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2793   CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2794 
2795   // Block tests which single thread should execute region, and which threads
2796   // should go straight to synchronisation point.
2797   CGF.EmitBlock(TestBB);
2798   CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2799   llvm::Value *CmpThreadToCounter =
2800       CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2801   CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2802 
2803   // Block emits the body of the critical region.
2804   CGF.EmitBlock(BodyBB);
2805 
2806   // Output the critical statement.
2807   CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2808                                       Hint);
2809 
2810   // After the body surrounded by the critical region, the single executing
2811   // thread will jump to the synchronisation point.
2812   // Block waits for all threads in current team to finish then increments the
2813   // counter variable and returns to the loop.
2814   CGF.EmitBlock(SyncBB);
2815   // Reconverge active threads in the warp.
2816   (void)CGF.EmitRuntimeCall(
2817       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
2818 
2819   llvm::Value *IncCounterVal =
2820       CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2821   CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2822   CGF.EmitBranch(LoopBB);
2823 
2824   // Block that is reached when  all threads in the team complete the region.
2825   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2826 }
2827 
2828 /// Cast value to the specified type.
2829 static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2830                                     QualType ValTy, QualType CastTy,
2831                                     SourceLocation Loc) {
2832   assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2833          "Cast type must sized.");
2834   assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2835          "Val type must sized.");
2836   llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2837   if (ValTy == CastTy)
2838     return Val;
2839   if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2840       CGF.getContext().getTypeSizeInChars(CastTy))
2841     return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2842   if (CastTy->isIntegerType() && ValTy->isIntegerType())
2843     return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2844                                      CastTy->hasSignedIntegerRepresentation());
2845   Address CastItem = CGF.CreateMemTemp(CastTy);
2846   Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2847       CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
2848   CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2849   return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
2850 }
2851 
2852 /// This function creates calls to one of two shuffle functions to copy
2853 /// variables between lanes in a warp.
2854 static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
2855                                                  llvm::Value *Elem,
2856                                                  QualType ElemType,
2857                                                  llvm::Value *Offset,
2858                                                  SourceLocation Loc) {
2859   CodeGenModule &CGM = CGF.CGM;
2860   CGBuilderTy &Bld = CGF.Builder;
2861   CGOpenMPRuntimeGPU &RT =
2862       *(static_cast<CGOpenMPRuntimeGPU *>(&CGM.getOpenMPRuntime()));
2863 
2864   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2865   assert(Size.getQuantity() <= 8 &&
2866          "Unsupported bitwidth in shuffle instruction.");
2867 
2868   OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
2869                                          ? OMPRTL_NVPTX__kmpc_shuffle_int32
2870                                          : OMPRTL_NVPTX__kmpc_shuffle_int64;
2871 
2872   // Cast all types to 32- or 64-bit values before calling shuffle routines.
2873   QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2874       Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2875   llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
2876   llvm::Value *WarpSize =
2877       Bld.CreateIntCast(RT.getGPUWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
2878 
2879   llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2880       RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
2881 
2882   return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
2883 }
2884 
2885 static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2886                             Address DestAddr, QualType ElemType,
2887                             llvm::Value *Offset, SourceLocation Loc) {
2888   CGBuilderTy &Bld = CGF.Builder;
2889 
2890   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2891   // Create the loop over the big sized data.
2892   // ptr = (void*)Elem;
2893   // ptrEnd = (void*) Elem + 1;
2894   // Step = 8;
2895   // while (ptr + Step < ptrEnd)
2896   //   shuffle((int64_t)*ptr);
2897   // Step = 4;
2898   // while (ptr + Step < ptrEnd)
2899   //   shuffle((int32_t)*ptr);
2900   // ...
2901   Address ElemPtr = DestAddr;
2902   Address Ptr = SrcAddr;
2903   Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2904       Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
2905   for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2906     if (Size < CharUnits::fromQuantity(IntSize))
2907       continue;
2908     QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2909         CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2910         /*Signed=*/1);
2911     llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2912     Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2913     ElemPtr =
2914         Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2915     if (Size.getQuantity() / IntSize > 1) {
2916       llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2917       llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2918       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2919       llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2920       CGF.EmitBlock(PreCondBB);
2921       llvm::PHINode *PhiSrc =
2922           Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2923       PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2924       llvm::PHINode *PhiDest =
2925           Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2926       PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2927       Ptr = Address(PhiSrc, Ptr.getAlignment());
2928       ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2929       llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2930           PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2931                                    Ptr.getPointer(), CGF.VoidPtrTy));
2932       Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2933                        ThenBB, ExitBB);
2934       CGF.EmitBlock(ThenBB);
2935       llvm::Value *Res = createRuntimeShuffleFunction(
2936           CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2937           IntType, Offset, Loc);
2938       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2939       Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2940       Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2941       PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2942       PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
2943       CGF.EmitBranch(PreCondBB);
2944       CGF.EmitBlock(ExitBB);
2945     } else {
2946       llvm::Value *Res = createRuntimeShuffleFunction(
2947           CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2948           IntType, Offset, Loc);
2949       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2950       Ptr = Bld.CreateConstGEP(Ptr, 1);
2951       ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2952     }
2953     Size = Size % IntSize;
2954   }
2955 }
2956 
2957 namespace {
2958 enum CopyAction : unsigned {
2959   // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2960   // the warp using shuffle instructions.
2961   RemoteLaneToThread,
2962   // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2963   ThreadCopy,
2964   // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2965   ThreadToScratchpad,
2966   // ScratchpadToThread: Copy from a scratchpad array in global memory
2967   // containing team-reduced data to a thread's stack.
2968   ScratchpadToThread,
2969 };
2970 } // namespace
2971 
2972 struct CopyOptionsTy {
2973   llvm::Value *RemoteLaneOffset;
2974   llvm::Value *ScratchpadIndex;
2975   llvm::Value *ScratchpadWidth;
2976 };
2977 
2978 /// Emit instructions to copy a Reduce list, which contains partially
2979 /// aggregated values, in the specified direction.
2980 static void emitReductionListCopy(
2981     CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2982     ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2983     CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
2984 
2985   CodeGenModule &CGM = CGF.CGM;
2986   ASTContext &C = CGM.getContext();
2987   CGBuilderTy &Bld = CGF.Builder;
2988 
2989   llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2990   llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2991   llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
2992 
2993   // Iterates, element-by-element, through the source Reduce list and
2994   // make a copy.
2995   unsigned Idx = 0;
2996   unsigned Size = Privates.size();
2997   for (const Expr *Private : Privates) {
2998     Address SrcElementAddr = Address::invalid();
2999     Address DestElementAddr = Address::invalid();
3000     Address DestElementPtrAddr = Address::invalid();
3001     // Should we shuffle in an element from a remote lane?
3002     bool ShuffleInElement = false;
3003     // Set to true to update the pointer in the dest Reduce list to a
3004     // newly created element.
3005     bool UpdateDestListPtr = false;
3006     // Increment the src or dest pointer to the scratchpad, for each
3007     // new element.
3008     bool IncrScratchpadSrc = false;
3009     bool IncrScratchpadDest = false;
3010 
3011     switch (Action) {
3012     case RemoteLaneToThread: {
3013       // Step 1.1: Get the address for the src element in the Reduce list.
3014       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3015       SrcElementAddr = CGF.EmitLoadOfPointer(
3016           SrcElementPtrAddr,
3017           C.getPointerType(Private->getType())->castAs<PointerType>());
3018 
3019       // Step 1.2: Create a temporary to store the element in the destination
3020       // Reduce list.
3021       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3022       DestElementAddr =
3023           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3024       ShuffleInElement = true;
3025       UpdateDestListPtr = true;
3026       break;
3027     }
3028     case ThreadCopy: {
3029       // Step 1.1: Get the address for the src element in the Reduce list.
3030       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3031       SrcElementAddr = CGF.EmitLoadOfPointer(
3032           SrcElementPtrAddr,
3033           C.getPointerType(Private->getType())->castAs<PointerType>());
3034 
3035       // Step 1.2: Get the address for dest element.  The destination
3036       // element has already been created on the thread's stack.
3037       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3038       DestElementAddr = CGF.EmitLoadOfPointer(
3039           DestElementPtrAddr,
3040           C.getPointerType(Private->getType())->castAs<PointerType>());
3041       break;
3042     }
3043     case ThreadToScratchpad: {
3044       // Step 1.1: Get the address for the src element in the Reduce list.
3045       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
3046       SrcElementAddr = CGF.EmitLoadOfPointer(
3047           SrcElementPtrAddr,
3048           C.getPointerType(Private->getType())->castAs<PointerType>());
3049 
3050       // Step 1.2: Get the address for dest element:
3051       // address = base + index * ElementSizeInChars.
3052       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3053       llvm::Value *CurrentOffset =
3054           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
3055       llvm::Value *ScratchPadElemAbsolutePtrVal =
3056           Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
3057       ScratchPadElemAbsolutePtrVal =
3058           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3059       DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3060                                 C.getTypeAlignInChars(Private->getType()));
3061       IncrScratchpadDest = true;
3062       break;
3063     }
3064     case ScratchpadToThread: {
3065       // Step 1.1: Get the address for the src element in the scratchpad.
3066       // address = base + index * ElementSizeInChars.
3067       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3068       llvm::Value *CurrentOffset =
3069           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
3070       llvm::Value *ScratchPadElemAbsolutePtrVal =
3071           Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
3072       ScratchPadElemAbsolutePtrVal =
3073           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3074       SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3075                                C.getTypeAlignInChars(Private->getType()));
3076       IncrScratchpadSrc = true;
3077 
3078       // Step 1.2: Create a temporary to store the element in the destination
3079       // Reduce list.
3080       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
3081       DestElementAddr =
3082           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3083       UpdateDestListPtr = true;
3084       break;
3085     }
3086     }
3087 
3088     // Regardless of src and dest of copy, we emit the load of src
3089     // element as this is required in all directions
3090     SrcElementAddr = Bld.CreateElementBitCast(
3091         SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
3092     DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3093                                                SrcElementAddr.getElementType());
3094 
3095     // Now that all active lanes have read the element in the
3096     // Reduce list, shuffle over the value from the remote lane.
3097     if (ShuffleInElement) {
3098       shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3099                       RemoteLaneOffset, Private->getExprLoc());
3100     } else {
3101       switch (CGF.getEvaluationKind(Private->getType())) {
3102       case TEK_Scalar: {
3103         llvm::Value *Elem =
3104             CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3105                                  Private->getType(), Private->getExprLoc());
3106         // Store the source element value to the dest element address.
3107         CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3108                               Private->getType());
3109         break;
3110       }
3111       case TEK_Complex: {
3112         CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3113             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3114             Private->getExprLoc());
3115         CGF.EmitStoreOfComplex(
3116             Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3117             /*isInit=*/false);
3118         break;
3119       }
3120       case TEK_Aggregate:
3121         CGF.EmitAggregateCopy(
3122             CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3123             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3124             Private->getType(), AggValueSlot::DoesNotOverlap);
3125         break;
3126       }
3127     }
3128 
3129     // Step 3.1: Modify reference in dest Reduce list as needed.
3130     // Modifying the reference in Reduce list to point to the newly
3131     // created element.  The element is live in the current function
3132     // scope and that of functions it invokes (i.e., reduce_function).
3133     // RemoteReduceData[i] = (void*)&RemoteElem
3134     if (UpdateDestListPtr) {
3135       CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3136                                 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3137                             DestElementPtrAddr, /*Volatile=*/false,
3138                             C.VoidPtrTy);
3139     }
3140 
3141     // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3142     // address of the next element in scratchpad memory, unless we're currently
3143     // processing the last one.  Memory alignment is also taken care of here.
3144     if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3145       llvm::Value *ScratchpadBasePtr =
3146           IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
3147       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3148       ScratchpadBasePtr = Bld.CreateNUWAdd(
3149           ScratchpadBasePtr,
3150           Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
3151 
3152       // Take care of global memory alignment for performance
3153       ScratchpadBasePtr = Bld.CreateNUWSub(
3154           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3155       ScratchpadBasePtr = Bld.CreateUDiv(
3156           ScratchpadBasePtr,
3157           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3158       ScratchpadBasePtr = Bld.CreateNUWAdd(
3159           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3160       ScratchpadBasePtr = Bld.CreateNUWMul(
3161           ScratchpadBasePtr,
3162           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3163 
3164       if (IncrScratchpadDest)
3165         DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3166       else /* IncrScratchpadSrc = true */
3167         SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3168     }
3169 
3170     ++Idx;
3171   }
3172 }
3173 
3174 /// This function emits a helper that gathers Reduce lists from the first
3175 /// lane of every active warp to lanes in the first warp.
3176 ///
3177 /// void inter_warp_copy_func(void* reduce_data, num_warps)
3178 ///   shared smem[warp_size];
3179 ///   For all data entries D in reduce_data:
3180 ///     sync
3181 ///     If (I am the first lane in each warp)
3182 ///       Copy my local D to smem[warp_id]
3183 ///     sync
3184 ///     if (I am the first warp)
3185 ///       Copy smem[thread_id] to my local D
3186 static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3187                                               ArrayRef<const Expr *> Privates,
3188                                               QualType ReductionArrayTy,
3189                                               SourceLocation Loc) {
3190   ASTContext &C = CGM.getContext();
3191   llvm::Module &M = CGM.getModule();
3192 
3193   // ReduceList: thread local Reduce list.
3194   // At the stage of the computation when this function is called, partially
3195   // aggregated values reside in the first lane of every active warp.
3196   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3197                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3198   // NumWarps: number of warps active in the parallel region.  This could
3199   // be smaller than 32 (max warps in a CTA) for partial block reduction.
3200   ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3201                                 C.getIntTypeForBitwidth(32, /* Signed */ true),
3202                                 ImplicitParamDecl::Other);
3203   FunctionArgList Args;
3204   Args.push_back(&ReduceListArg);
3205   Args.push_back(&NumWarpsArg);
3206 
3207   const CGFunctionInfo &CGFI =
3208       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3209   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3210                                     llvm::GlobalValue::InternalLinkage,
3211                                     "_omp_reduction_inter_warp_copy_func", &M);
3212   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3213   Fn->setDoesNotRecurse();
3214   CodeGenFunction CGF(CGM);
3215   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3216 
3217   CGBuilderTy &Bld = CGF.Builder;
3218 
3219   // This array is used as a medium to transfer, one reduce element at a time,
3220   // the data from the first lane of every warp to lanes in the first warp
3221   // in order to perform the final step of a reduction in a parallel region
3222   // (reduction across warps).  The array is placed in NVPTX __shared__ memory
3223   // for reduced latency, as well as to have a distinct copy for concurrently
3224   // executing target regions.  The array is declared with common linkage so
3225   // as to be shared across compilation units.
3226   StringRef TransferMediumName =
3227       "__openmp_nvptx_data_transfer_temporary_storage";
3228   llvm::GlobalVariable *TransferMedium =
3229       M.getGlobalVariable(TransferMediumName);
3230   unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
3231   if (!TransferMedium) {
3232     auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
3233     unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3234     TransferMedium = new llvm::GlobalVariable(
3235         M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
3236         llvm::Constant::getNullValue(Ty), TransferMediumName,
3237         /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3238         SharedAddressSpace);
3239     CGM.addCompilerUsedGlobal(TransferMedium);
3240   }
3241 
3242   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
3243   // Get the CUDA thread id of the current OpenMP thread on the GPU.
3244   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
3245   // nvptx_lane_id = nvptx_id % warpsize
3246   llvm::Value *LaneID = getNVPTXLaneID(CGF);
3247   // nvptx_warp_id = nvptx_id / warpsize
3248   llvm::Value *WarpID = getNVPTXWarpID(CGF);
3249 
3250   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3251   Address LocalReduceList(
3252       Bld.CreatePointerBitCastOrAddrSpaceCast(
3253           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3254                                C.VoidPtrTy, Loc),
3255           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3256       CGF.getPointerAlign());
3257 
3258   unsigned Idx = 0;
3259   for (const Expr *Private : Privates) {
3260     //
3261     // Warp master copies reduce element to transfer medium in __shared__
3262     // memory.
3263     //
3264     unsigned RealTySize =
3265         C.getTypeSizeInChars(Private->getType())
3266             .alignTo(C.getTypeAlignInChars(Private->getType()))
3267             .getQuantity();
3268     for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3269       unsigned NumIters = RealTySize / TySize;
3270       if (NumIters == 0)
3271         continue;
3272       QualType CType = C.getIntTypeForBitwidth(
3273           C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3274       llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3275       CharUnits Align = CharUnits::fromQuantity(TySize);
3276       llvm::Value *Cnt = nullptr;
3277       Address CntAddr = Address::invalid();
3278       llvm::BasicBlock *PrecondBB = nullptr;
3279       llvm::BasicBlock *ExitBB = nullptr;
3280       if (NumIters > 1) {
3281         CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3282         CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3283                               /*Volatile=*/false, C.IntTy);
3284         PrecondBB = CGF.createBasicBlock("precond");
3285         ExitBB = CGF.createBasicBlock("exit");
3286         llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3287         // There is no need to emit line number for unconditional branch.
3288         (void)ApplyDebugLocation::CreateEmpty(CGF);
3289         CGF.EmitBlock(PrecondBB);
3290         Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3291         llvm::Value *Cmp =
3292             Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3293         Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3294         CGF.EmitBlock(BodyBB);
3295       }
3296       // kmpc_barrier.
3297       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3298                                              /*EmitChecks=*/false,
3299                                              /*ForceSimpleCall=*/true);
3300       llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3301       llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3302       llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3303 
3304       // if (lane_id == 0)
3305       llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3306       Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3307       CGF.EmitBlock(ThenBB);
3308 
3309       // Reduce element = LocalReduceList[i]
3310       Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3311       llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3312           ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3313       // elemptr = ((CopyType*)(elemptrptr)) + I
3314       Address ElemPtr = Address(ElemPtrPtr, Align);
3315       ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3316       if (NumIters > 1) {
3317         ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3318                           ElemPtr.getAlignment());
3319       }
3320 
3321       // Get pointer to location in transfer medium.
3322       // MediumPtr = &medium[warp_id]
3323       llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3324           TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3325       Address MediumPtr(MediumPtrVal, Align);
3326       // Casting to actual data type.
3327       // MediumPtr = (CopyType*)MediumPtrAddr;
3328       MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
3329 
3330       // elem = *elemptr
3331       //*MediumPtr = elem
3332       llvm::Value *Elem =
3333           CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
3334       // Store the source element value to the dest element address.
3335       CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
3336 
3337       Bld.CreateBr(MergeBB);
3338 
3339       CGF.EmitBlock(ElseBB);
3340       Bld.CreateBr(MergeBB);
3341 
3342       CGF.EmitBlock(MergeBB);
3343 
3344       // kmpc_barrier.
3345       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3346                                              /*EmitChecks=*/false,
3347                                              /*ForceSimpleCall=*/true);
3348 
3349       //
3350       // Warp 0 copies reduce element from transfer medium.
3351       //
3352       llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3353       llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3354       llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
3355 
3356       Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3357       llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3358           AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3359 
3360       // Up to 32 threads in warp 0 are active.
3361       llvm::Value *IsActiveThread =
3362           Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3363       Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
3364 
3365       CGF.EmitBlock(W0ThenBB);
3366 
3367       // SrcMediumPtr = &medium[tid]
3368       llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3369           TransferMedium,
3370           {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3371       Address SrcMediumPtr(SrcMediumPtrVal, Align);
3372       // SrcMediumVal = *SrcMediumPtr;
3373       SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
3374 
3375       // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3376       Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3377       llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3378           TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3379       Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3380       TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3381       if (NumIters > 1) {
3382         TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3383                                 TargetElemPtr.getAlignment());
3384       }
3385 
3386       // *TargetElemPtr = SrcMediumVal;
3387       llvm::Value *SrcMediumValue =
3388           CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
3389       CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3390                             CType);
3391       Bld.CreateBr(W0MergeBB);
3392 
3393       CGF.EmitBlock(W0ElseBB);
3394       Bld.CreateBr(W0MergeBB);
3395 
3396       CGF.EmitBlock(W0MergeBB);
3397 
3398       if (NumIters > 1) {
3399         Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3400         CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3401         CGF.EmitBranch(PrecondBB);
3402         (void)ApplyDebugLocation::CreateEmpty(CGF);
3403         CGF.EmitBlock(ExitBB);
3404       }
3405       RealTySize %= TySize;
3406     }
3407     ++Idx;
3408   }
3409 
3410   CGF.FinishFunction();
3411   return Fn;
3412 }
3413 
3414 /// Emit a helper that reduces data across two OpenMP threads (lanes)
3415 /// in the same warp.  It uses shuffle instructions to copy over data from
3416 /// a remote lane's stack.  The reduction algorithm performed is specified
3417 /// by the fourth parameter.
3418 ///
3419 /// Algorithm Versions.
3420 /// Full Warp Reduce (argument value 0):
3421 ///   This algorithm assumes that all 32 lanes are active and gathers
3422 ///   data from these 32 lanes, producing a single resultant value.
3423 /// Contiguous Partial Warp Reduce (argument value 1):
3424 ///   This algorithm assumes that only a *contiguous* subset of lanes
3425 ///   are active.  This happens for the last warp in a parallel region
3426 ///   when the user specified num_threads is not an integer multiple of
3427 ///   32.  This contiguous subset always starts with the zeroth lane.
3428 /// Partial Warp Reduce (argument value 2):
3429 ///   This algorithm gathers data from any number of lanes at any position.
3430 /// All reduced values are stored in the lowest possible lane.  The set
3431 /// of problems every algorithm addresses is a super set of those
3432 /// addressable by algorithms with a lower version number.  Overhead
3433 /// increases as algorithm version increases.
3434 ///
3435 /// Terminology
3436 /// Reduce element:
3437 ///   Reduce element refers to the individual data field with primitive
3438 ///   data types to be combined and reduced across threads.
3439 /// Reduce list:
3440 ///   Reduce list refers to a collection of local, thread-private
3441 ///   reduce elements.
3442 /// Remote Reduce list:
3443 ///   Remote Reduce list refers to a collection of remote (relative to
3444 ///   the current thread) reduce elements.
3445 ///
3446 /// We distinguish between three states of threads that are important to
3447 /// the implementation of this function.
3448 /// Alive threads:
3449 ///   Threads in a warp executing the SIMT instruction, as distinguished from
3450 ///   threads that are inactive due to divergent control flow.
3451 /// Active threads:
3452 ///   The minimal set of threads that has to be alive upon entry to this
3453 ///   function.  The computation is correct iff active threads are alive.
3454 ///   Some threads are alive but they are not active because they do not
3455 ///   contribute to the computation in any useful manner.  Turning them off
3456 ///   may introduce control flow overheads without any tangible benefits.
3457 /// Effective threads:
3458 ///   In order to comply with the argument requirements of the shuffle
3459 ///   function, we must keep all lanes holding data alive.  But at most
3460 ///   half of them perform value aggregation; we refer to this half of
3461 ///   threads as effective. The other half is simply handing off their
3462 ///   data.
3463 ///
3464 /// Procedure
3465 /// Value shuffle:
3466 ///   In this step active threads transfer data from higher lane positions
3467 ///   in the warp to lower lane positions, creating Remote Reduce list.
3468 /// Value aggregation:
3469 ///   In this step, effective threads combine their thread local Reduce list
3470 ///   with Remote Reduce list and store the result in the thread local
3471 ///   Reduce list.
3472 /// Value copy:
3473 ///   In this step, we deal with the assumption made by algorithm 2
3474 ///   (i.e. contiguity assumption).  When we have an odd number of lanes
3475 ///   active, say 2k+1, only k threads will be effective and therefore k
3476 ///   new values will be produced.  However, the Reduce list owned by the
3477 ///   (2k+1)th thread is ignored in the value aggregation.  Therefore
3478 ///   we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3479 ///   that the contiguity assumption still holds.
3480 static llvm::Function *emitShuffleAndReduceFunction(
3481     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3482     QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
3483   ASTContext &C = CGM.getContext();
3484 
3485   // Thread local Reduce list used to host the values of data to be reduced.
3486   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3487                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3488   // Current lane id; could be logical.
3489   ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3490                               ImplicitParamDecl::Other);
3491   // Offset of the remote source lane relative to the current lane.
3492   ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3493                                         C.ShortTy, ImplicitParamDecl::Other);
3494   // Algorithm version.  This is expected to be known at compile time.
3495   ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3496                                C.ShortTy, ImplicitParamDecl::Other);
3497   FunctionArgList Args;
3498   Args.push_back(&ReduceListArg);
3499   Args.push_back(&LaneIDArg);
3500   Args.push_back(&RemoteLaneOffsetArg);
3501   Args.push_back(&AlgoVerArg);
3502 
3503   const CGFunctionInfo &CGFI =
3504       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3505   auto *Fn = llvm::Function::Create(
3506       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3507       "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
3508   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3509   Fn->setDoesNotRecurse();
3510   if (CGM.getLangOpts().Optimize) {
3511     Fn->removeFnAttr(llvm::Attribute::NoInline);
3512     Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3513     Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3514   }
3515 
3516   CodeGenFunction CGF(CGM);
3517   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3518 
3519   CGBuilderTy &Bld = CGF.Builder;
3520 
3521   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3522   Address LocalReduceList(
3523       Bld.CreatePointerBitCastOrAddrSpaceCast(
3524           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3525                                C.VoidPtrTy, SourceLocation()),
3526           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3527       CGF.getPointerAlign());
3528 
3529   Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3530   llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3531       AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3532 
3533   Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3534   llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3535       AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3536 
3537   Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3538   llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3539       AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3540 
3541   // Create a local thread-private variable to host the Reduce list
3542   // from a remote lane.
3543   Address RemoteReduceList =
3544       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3545 
3546   // This loop iterates through the list of reduce elements and copies,
3547   // element by element, from a remote lane in the warp to RemoteReduceList,
3548   // hosted on the thread's stack.
3549   emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3550                         LocalReduceList, RemoteReduceList,
3551                         {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3552                          /*ScratchpadIndex=*/nullptr,
3553                          /*ScratchpadWidth=*/nullptr});
3554 
3555   // The actions to be performed on the Remote Reduce list is dependent
3556   // on the algorithm version.
3557   //
3558   //  if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3559   //  LaneId % 2 == 0 && Offset > 0):
3560   //    do the reduction value aggregation
3561   //
3562   //  The thread local variable Reduce list is mutated in place to host the
3563   //  reduced data, which is the aggregated value produced from local and
3564   //  remote lanes.
3565   //
3566   //  Note that AlgoVer is expected to be a constant integer known at compile
3567   //  time.
3568   //  When AlgoVer==0, the first conjunction evaluates to true, making
3569   //    the entire predicate true during compile time.
3570   //  When AlgoVer==1, the second conjunction has only the second part to be
3571   //    evaluated during runtime.  Other conjunctions evaluates to false
3572   //    during compile time.
3573   //  When AlgoVer==2, the third conjunction has only the second part to be
3574   //    evaluated during runtime.  Other conjunctions evaluates to false
3575   //    during compile time.
3576   llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
3577 
3578   llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3579   llvm::Value *CondAlgo1 = Bld.CreateAnd(
3580       Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3581 
3582   llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3583   llvm::Value *CondAlgo2 = Bld.CreateAnd(
3584       Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
3585   CondAlgo2 = Bld.CreateAnd(
3586       CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3587 
3588   llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
3589   CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3590 
3591   llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3592   llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3593   llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3594   Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3595 
3596   CGF.EmitBlock(ThenBB);
3597   // reduce_function(LocalReduceList, RemoteReduceList)
3598   llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3599       LocalReduceList.getPointer(), CGF.VoidPtrTy);
3600   llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3601       RemoteReduceList.getPointer(), CGF.VoidPtrTy);
3602   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3603       CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
3604   Bld.CreateBr(MergeBB);
3605 
3606   CGF.EmitBlock(ElseBB);
3607   Bld.CreateBr(MergeBB);
3608 
3609   CGF.EmitBlock(MergeBB);
3610 
3611   // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3612   // Reduce list.
3613   Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3614   llvm::Value *CondCopy = Bld.CreateAnd(
3615       Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3616 
3617   llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3618   llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3619   llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3620   Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3621 
3622   CGF.EmitBlock(CpyThenBB);
3623   emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3624                         RemoteReduceList, LocalReduceList);
3625   Bld.CreateBr(CpyMergeBB);
3626 
3627   CGF.EmitBlock(CpyElseBB);
3628   Bld.CreateBr(CpyMergeBB);
3629 
3630   CGF.EmitBlock(CpyMergeBB);
3631 
3632   CGF.FinishFunction();
3633   return Fn;
3634 }
3635 
3636 /// This function emits a helper that copies all the reduction variables from
3637 /// the team into the provided global buffer for the reduction variables.
3638 ///
3639 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3640 ///   For all data entries D in reduce_data:
3641 ///     Copy local D to buffer.D[Idx]
3642 static llvm::Value *emitListToGlobalCopyFunction(
3643     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3644     QualType ReductionArrayTy, SourceLocation Loc,
3645     const RecordDecl *TeamReductionRec,
3646     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3647         &VarFieldMap) {
3648   ASTContext &C = CGM.getContext();
3649 
3650   // Buffer: global reduction buffer.
3651   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3652                               C.VoidPtrTy, ImplicitParamDecl::Other);
3653   // Idx: index of the buffer.
3654   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3655                            ImplicitParamDecl::Other);
3656   // ReduceList: thread local Reduce list.
3657   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3658                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3659   FunctionArgList Args;
3660   Args.push_back(&BufferArg);
3661   Args.push_back(&IdxArg);
3662   Args.push_back(&ReduceListArg);
3663 
3664   const CGFunctionInfo &CGFI =
3665       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3666   auto *Fn = llvm::Function::Create(
3667       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3668       "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3669   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3670   Fn->setDoesNotRecurse();
3671   CodeGenFunction CGF(CGM);
3672   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3673 
3674   CGBuilderTy &Bld = CGF.Builder;
3675 
3676   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3677   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3678   Address LocalReduceList(
3679       Bld.CreatePointerBitCastOrAddrSpaceCast(
3680           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3681                                C.VoidPtrTy, Loc),
3682           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3683       CGF.getPointerAlign());
3684   QualType StaticTy = C.getRecordType(TeamReductionRec);
3685   llvm::Type *LLVMReductionsBufferTy =
3686       CGM.getTypes().ConvertTypeForMem(StaticTy);
3687   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3688       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3689       LLVMReductionsBufferTy->getPointerTo());
3690   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3691                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3692                                               /*Volatile=*/false, C.IntTy,
3693                                               Loc)};
3694   unsigned Idx = 0;
3695   for (const Expr *Private : Privates) {
3696     // Reduce element = LocalReduceList[i]
3697     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3698     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3699         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3700     // elemptr = ((CopyType*)(elemptrptr)) + I
3701     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3702         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3703     Address ElemPtr =
3704         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3705     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3706     // Global = Buffer.VD[Idx];
3707     const FieldDecl *FD = VarFieldMap.lookup(VD);
3708     LValue GlobLVal = CGF.EmitLValueForField(
3709         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3710     llvm::Value *BufferPtr =
3711         Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3712     GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3713     switch (CGF.getEvaluationKind(Private->getType())) {
3714     case TEK_Scalar: {
3715       llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3716                                             Private->getType(), Loc);
3717       CGF.EmitStoreOfScalar(V, GlobLVal);
3718       break;
3719     }
3720     case TEK_Complex: {
3721       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3722           CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3723       CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3724       break;
3725     }
3726     case TEK_Aggregate:
3727       CGF.EmitAggregateCopy(GlobLVal,
3728                             CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3729                             Private->getType(), AggValueSlot::DoesNotOverlap);
3730       break;
3731     }
3732     ++Idx;
3733   }
3734 
3735   CGF.FinishFunction();
3736   return Fn;
3737 }
3738 
3739 /// This function emits a helper that reduces all the reduction variables from
3740 /// the team into the provided global buffer for the reduction variables.
3741 ///
3742 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3743 ///  void *GlobPtrs[];
3744 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
3745 ///  ...
3746 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
3747 ///  reduce_function(GlobPtrs, reduce_data);
3748 static llvm::Value *emitListToGlobalReduceFunction(
3749     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3750     QualType ReductionArrayTy, SourceLocation Loc,
3751     const RecordDecl *TeamReductionRec,
3752     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3753         &VarFieldMap,
3754     llvm::Function *ReduceFn) {
3755   ASTContext &C = CGM.getContext();
3756 
3757   // Buffer: global reduction buffer.
3758   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3759                               C.VoidPtrTy, ImplicitParamDecl::Other);
3760   // Idx: index of the buffer.
3761   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3762                            ImplicitParamDecl::Other);
3763   // ReduceList: thread local Reduce list.
3764   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3765                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3766   FunctionArgList Args;
3767   Args.push_back(&BufferArg);
3768   Args.push_back(&IdxArg);
3769   Args.push_back(&ReduceListArg);
3770 
3771   const CGFunctionInfo &CGFI =
3772       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3773   auto *Fn = llvm::Function::Create(
3774       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3775       "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3776   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3777   Fn->setDoesNotRecurse();
3778   CodeGenFunction CGF(CGM);
3779   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3780 
3781   CGBuilderTy &Bld = CGF.Builder;
3782 
3783   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3784   QualType StaticTy = C.getRecordType(TeamReductionRec);
3785   llvm::Type *LLVMReductionsBufferTy =
3786       CGM.getTypes().ConvertTypeForMem(StaticTy);
3787   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3788       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3789       LLVMReductionsBufferTy->getPointerTo());
3790 
3791   // 1. Build a list of reduction variables.
3792   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3793   Address ReductionList =
3794       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3795   auto IPriv = Privates.begin();
3796   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3797                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3798                                               /*Volatile=*/false, C.IntTy,
3799                                               Loc)};
3800   unsigned Idx = 0;
3801   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3802     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3803     // Global = Buffer.VD[Idx];
3804     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3805     const FieldDecl *FD = VarFieldMap.lookup(VD);
3806     LValue GlobLVal = CGF.EmitLValueForField(
3807         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3808     llvm::Value *BufferPtr =
3809         Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3810     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3811     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3812     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3813       // Store array size.
3814       ++Idx;
3815       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3816       llvm::Value *Size = CGF.Builder.CreateIntCast(
3817           CGF.getVLASize(
3818                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3819               .NumElts,
3820           CGF.SizeTy, /*isSigned=*/false);
3821       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3822                               Elem);
3823     }
3824   }
3825 
3826   // Call reduce_function(GlobalReduceList, ReduceList)
3827   llvm::Value *GlobalReduceList =
3828       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3829   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3830   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3831       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3832   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3833       CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3834   CGF.FinishFunction();
3835   return Fn;
3836 }
3837 
3838 /// This function emits a helper that copies all the reduction variables from
3839 /// the team into the provided global buffer for the reduction variables.
3840 ///
3841 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3842 ///   For all data entries D in reduce_data:
3843 ///     Copy buffer.D[Idx] to local D;
3844 static llvm::Value *emitGlobalToListCopyFunction(
3845     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3846     QualType ReductionArrayTy, SourceLocation Loc,
3847     const RecordDecl *TeamReductionRec,
3848     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3849         &VarFieldMap) {
3850   ASTContext &C = CGM.getContext();
3851 
3852   // Buffer: global reduction buffer.
3853   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3854                               C.VoidPtrTy, ImplicitParamDecl::Other);
3855   // Idx: index of the buffer.
3856   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3857                            ImplicitParamDecl::Other);
3858   // ReduceList: thread local Reduce list.
3859   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3860                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3861   FunctionArgList Args;
3862   Args.push_back(&BufferArg);
3863   Args.push_back(&IdxArg);
3864   Args.push_back(&ReduceListArg);
3865 
3866   const CGFunctionInfo &CGFI =
3867       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3868   auto *Fn = llvm::Function::Create(
3869       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3870       "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3871   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3872   Fn->setDoesNotRecurse();
3873   CodeGenFunction CGF(CGM);
3874   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3875 
3876   CGBuilderTy &Bld = CGF.Builder;
3877 
3878   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3879   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3880   Address LocalReduceList(
3881       Bld.CreatePointerBitCastOrAddrSpaceCast(
3882           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3883                                C.VoidPtrTy, Loc),
3884           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3885       CGF.getPointerAlign());
3886   QualType StaticTy = C.getRecordType(TeamReductionRec);
3887   llvm::Type *LLVMReductionsBufferTy =
3888       CGM.getTypes().ConvertTypeForMem(StaticTy);
3889   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3890       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3891       LLVMReductionsBufferTy->getPointerTo());
3892 
3893   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3894                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3895                                               /*Volatile=*/false, C.IntTy,
3896                                               Loc)};
3897   unsigned Idx = 0;
3898   for (const Expr *Private : Privates) {
3899     // Reduce element = LocalReduceList[i]
3900     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3901     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3902         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3903     // elemptr = ((CopyType*)(elemptrptr)) + I
3904     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3905         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3906     Address ElemPtr =
3907         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3908     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3909     // Global = Buffer.VD[Idx];
3910     const FieldDecl *FD = VarFieldMap.lookup(VD);
3911     LValue GlobLVal = CGF.EmitLValueForField(
3912         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3913     llvm::Value *BufferPtr =
3914         Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
3915     GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3916     switch (CGF.getEvaluationKind(Private->getType())) {
3917     case TEK_Scalar: {
3918       llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3919       CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3920       break;
3921     }
3922     case TEK_Complex: {
3923       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3924       CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3925                              /*isInit=*/false);
3926       break;
3927     }
3928     case TEK_Aggregate:
3929       CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3930                             GlobLVal, Private->getType(),
3931                             AggValueSlot::DoesNotOverlap);
3932       break;
3933     }
3934     ++Idx;
3935   }
3936 
3937   CGF.FinishFunction();
3938   return Fn;
3939 }
3940 
3941 /// This function emits a helper that reduces all the reduction variables from
3942 /// the team into the provided global buffer for the reduction variables.
3943 ///
3944 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3945 ///  void *GlobPtrs[];
3946 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
3947 ///  ...
3948 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
3949 ///  reduce_function(reduce_data, GlobPtrs);
3950 static llvm::Value *emitGlobalToListReduceFunction(
3951     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3952     QualType ReductionArrayTy, SourceLocation Loc,
3953     const RecordDecl *TeamReductionRec,
3954     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3955         &VarFieldMap,
3956     llvm::Function *ReduceFn) {
3957   ASTContext &C = CGM.getContext();
3958 
3959   // Buffer: global reduction buffer.
3960   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3961                               C.VoidPtrTy, ImplicitParamDecl::Other);
3962   // Idx: index of the buffer.
3963   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3964                            ImplicitParamDecl::Other);
3965   // ReduceList: thread local Reduce list.
3966   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3967                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3968   FunctionArgList Args;
3969   Args.push_back(&BufferArg);
3970   Args.push_back(&IdxArg);
3971   Args.push_back(&ReduceListArg);
3972 
3973   const CGFunctionInfo &CGFI =
3974       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3975   auto *Fn = llvm::Function::Create(
3976       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3977       "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3978   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3979   Fn->setDoesNotRecurse();
3980   CodeGenFunction CGF(CGM);
3981   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3982 
3983   CGBuilderTy &Bld = CGF.Builder;
3984 
3985   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3986   QualType StaticTy = C.getRecordType(TeamReductionRec);
3987   llvm::Type *LLVMReductionsBufferTy =
3988       CGM.getTypes().ConvertTypeForMem(StaticTy);
3989   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3990       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3991       LLVMReductionsBufferTy->getPointerTo());
3992 
3993   // 1. Build a list of reduction variables.
3994   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3995   Address ReductionList =
3996       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3997   auto IPriv = Privates.begin();
3998   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3999                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
4000                                               /*Volatile=*/false, C.IntTy,
4001                                               Loc)};
4002   unsigned Idx = 0;
4003   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
4004     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4005     // Global = Buffer.VD[Idx];
4006     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
4007     const FieldDecl *FD = VarFieldMap.lookup(VD);
4008     LValue GlobLVal = CGF.EmitLValueForField(
4009         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
4010     llvm::Value *BufferPtr =
4011         Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
4012     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
4013     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
4014     if ((*IPriv)->getType()->isVariablyModifiedType()) {
4015       // Store array size.
4016       ++Idx;
4017       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4018       llvm::Value *Size = CGF.Builder.CreateIntCast(
4019           CGF.getVLASize(
4020                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4021               .NumElts,
4022           CGF.SizeTy, /*isSigned=*/false);
4023       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4024                               Elem);
4025     }
4026   }
4027 
4028   // Call reduce_function(ReduceList, GlobalReduceList)
4029   llvm::Value *GlobalReduceList =
4030       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
4031   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
4032   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
4033       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4034   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4035       CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4036   CGF.FinishFunction();
4037   return Fn;
4038 }
4039 
4040 ///
4041 /// Design of OpenMP reductions on the GPU
4042 ///
4043 /// Consider a typical OpenMP program with one or more reduction
4044 /// clauses:
4045 ///
4046 /// float foo;
4047 /// double bar;
4048 /// #pragma omp target teams distribute parallel for \
4049 ///             reduction(+:foo) reduction(*:bar)
4050 /// for (int i = 0; i < N; i++) {
4051 ///   foo += A[i]; bar *= B[i];
4052 /// }
4053 ///
4054 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
4055 /// all teams.  In our OpenMP implementation on the NVPTX device an
4056 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4057 /// within a team are mapped to CUDA threads within a threadblock.
4058 /// Our goal is to efficiently aggregate values across all OpenMP
4059 /// threads such that:
4060 ///
4061 ///   - the compiler and runtime are logically concise, and
4062 ///   - the reduction is performed efficiently in a hierarchical
4063 ///     manner as follows: within OpenMP threads in the same warp,
4064 ///     across warps in a threadblock, and finally across teams on
4065 ///     the NVPTX device.
4066 ///
4067 /// Introduction to Decoupling
4068 ///
4069 /// We would like to decouple the compiler and the runtime so that the
4070 /// latter is ignorant of the reduction variables (number, data types)
4071 /// and the reduction operators.  This allows a simpler interface
4072 /// and implementation while still attaining good performance.
4073 ///
4074 /// Pseudocode for the aforementioned OpenMP program generated by the
4075 /// compiler is as follows:
4076 ///
4077 /// 1. Create private copies of reduction variables on each OpenMP
4078 ///    thread: 'foo_private', 'bar_private'
4079 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4080 ///    to it and writes the result in 'foo_private' and 'bar_private'
4081 ///    respectively.
4082 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
4083 ///    and store the result on the team master:
4084 ///
4085 ///     __kmpc_nvptx_parallel_reduce_nowait_v2(...,
4086 ///        reduceData, shuffleReduceFn, interWarpCpyFn)
4087 ///
4088 ///     where:
4089 ///       struct ReduceData {
4090 ///         double *foo;
4091 ///         double *bar;
4092 ///       } reduceData
4093 ///       reduceData.foo = &foo_private
4094 ///       reduceData.bar = &bar_private
4095 ///
4096 ///     'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4097 ///     auxiliary functions generated by the compiler that operate on
4098 ///     variables of type 'ReduceData'.  They aid the runtime perform
4099 ///     algorithmic steps in a data agnostic manner.
4100 ///
4101 ///     'shuffleReduceFn' is a pointer to a function that reduces data
4102 ///     of type 'ReduceData' across two OpenMP threads (lanes) in the
4103 ///     same warp.  It takes the following arguments as input:
4104 ///
4105 ///     a. variable of type 'ReduceData' on the calling lane,
4106 ///     b. its lane_id,
4107 ///     c. an offset relative to the current lane_id to generate a
4108 ///        remote_lane_id.  The remote lane contains the second
4109 ///        variable of type 'ReduceData' that is to be reduced.
4110 ///     d. an algorithm version parameter determining which reduction
4111 ///        algorithm to use.
4112 ///
4113 ///     'shuffleReduceFn' retrieves data from the remote lane using
4114 ///     efficient GPU shuffle intrinsics and reduces, using the
4115 ///     algorithm specified by the 4th parameter, the two operands
4116 ///     element-wise.  The result is written to the first operand.
4117 ///
4118 ///     Different reduction algorithms are implemented in different
4119 ///     runtime functions, all calling 'shuffleReduceFn' to perform
4120 ///     the essential reduction step.  Therefore, based on the 4th
4121 ///     parameter, this function behaves slightly differently to
4122 ///     cooperate with the runtime to ensure correctness under
4123 ///     different circumstances.
4124 ///
4125 ///     'InterWarpCpyFn' is a pointer to a function that transfers
4126 ///     reduced variables across warps.  It tunnels, through CUDA
4127 ///     shared memory, the thread-private data of type 'ReduceData'
4128 ///     from lane 0 of each warp to a lane in the first warp.
4129 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4130 ///    The last team writes the global reduced value to memory.
4131 ///
4132 ///     ret = __kmpc_nvptx_teams_reduce_nowait(...,
4133 ///             reduceData, shuffleReduceFn, interWarpCpyFn,
4134 ///             scratchpadCopyFn, loadAndReduceFn)
4135 ///
4136 ///     'scratchpadCopyFn' is a helper that stores reduced
4137 ///     data from the team master to a scratchpad array in
4138 ///     global memory.
4139 ///
4140 ///     'loadAndReduceFn' is a helper that loads data from
4141 ///     the scratchpad array and reduces it with the input
4142 ///     operand.
4143 ///
4144 ///     These compiler generated functions hide address
4145 ///     calculation and alignment information from the runtime.
4146 /// 5. if ret == 1:
4147 ///     The team master of the last team stores the reduced
4148 ///     result to the globals in memory.
4149 ///     foo += reduceData.foo; bar *= reduceData.bar
4150 ///
4151 ///
4152 /// Warp Reduction Algorithms
4153 ///
4154 /// On the warp level, we have three algorithms implemented in the
4155 /// OpenMP runtime depending on the number of active lanes:
4156 ///
4157 /// Full Warp Reduction
4158 ///
4159 /// The reduce algorithm within a warp where all lanes are active
4160 /// is implemented in the runtime as follows:
4161 ///
4162 /// full_warp_reduce(void *reduce_data,
4163 ///                  kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4164 ///   for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4165 ///     ShuffleReduceFn(reduce_data, 0, offset, 0);
4166 /// }
4167 ///
4168 /// The algorithm completes in log(2, WARPSIZE) steps.
4169 ///
4170 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4171 /// not used therefore we save instructions by not retrieving lane_id
4172 /// from the corresponding special registers.  The 4th parameter, which
4173 /// represents the version of the algorithm being used, is set to 0 to
4174 /// signify full warp reduction.
4175 ///
4176 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4177 ///
4178 /// #reduce_elem refers to an element in the local lane's data structure
4179 /// #remote_elem is retrieved from a remote lane
4180 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4181 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4182 ///
4183 /// Contiguous Partial Warp Reduction
4184 ///
4185 /// This reduce algorithm is used within a warp where only the first
4186 /// 'n' (n <= WARPSIZE) lanes are active.  It is typically used when the
4187 /// number of OpenMP threads in a parallel region is not a multiple of
4188 /// WARPSIZE.  The algorithm is implemented in the runtime as follows:
4189 ///
4190 /// void
4191 /// contiguous_partial_reduce(void *reduce_data,
4192 ///                           kmp_ShuffleReductFctPtr ShuffleReduceFn,
4193 ///                           int size, int lane_id) {
4194 ///   int curr_size;
4195 ///   int offset;
4196 ///   curr_size = size;
4197 ///   mask = curr_size/2;
4198 ///   while (offset>0) {
4199 ///     ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4200 ///     curr_size = (curr_size+1)/2;
4201 ///     offset = curr_size/2;
4202 ///   }
4203 /// }
4204 ///
4205 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4206 ///
4207 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4208 /// if (lane_id < offset)
4209 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
4210 /// else
4211 ///     reduce_elem = remote_elem
4212 ///
4213 /// This algorithm assumes that the data to be reduced are located in a
4214 /// contiguous subset of lanes starting from the first.  When there is
4215 /// an odd number of active lanes, the data in the last lane is not
4216 /// aggregated with any other lane's dat but is instead copied over.
4217 ///
4218 /// Dispersed Partial Warp Reduction
4219 ///
4220 /// This algorithm is used within a warp when any discontiguous subset of
4221 /// lanes are active.  It is used to implement the reduction operation
4222 /// across lanes in an OpenMP simd region or in a nested parallel region.
4223 ///
4224 /// void
4225 /// dispersed_partial_reduce(void *reduce_data,
4226 ///                          kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4227 ///   int size, remote_id;
4228 ///   int logical_lane_id = number_of_active_lanes_before_me() * 2;
4229 ///   do {
4230 ///       remote_id = next_active_lane_id_right_after_me();
4231 ///       # the above function returns 0 of no active lane
4232 ///       # is present right after the current lane.
4233 ///       size = number_of_active_lanes_in_this_warp();
4234 ///       logical_lane_id /= 2;
4235 ///       ShuffleReduceFn(reduce_data, logical_lane_id,
4236 ///                       remote_id-1-threadIdx.x, 2);
4237 ///   } while (logical_lane_id % 2 == 0 && size > 1);
4238 /// }
4239 ///
4240 /// There is no assumption made about the initial state of the reduction.
4241 /// Any number of lanes (>=1) could be active at any position.  The reduction
4242 /// result is returned in the first active lane.
4243 ///
4244 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4245 ///
4246 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4247 /// if (lane_id % 2 == 0 && offset > 0)
4248 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
4249 /// else
4250 ///     reduce_elem = remote_elem
4251 ///
4252 ///
4253 /// Intra-Team Reduction
4254 ///
4255 /// This function, as implemented in the runtime call
4256 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
4257 /// threads in a team.  It first reduces within a warp using the
4258 /// aforementioned algorithms.  We then proceed to gather all such
4259 /// reduced values at the first warp.
4260 ///
4261 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
4262 /// data from each of the "warp master" (zeroth lane of each warp, where
4263 /// warp-reduced data is held) to the zeroth warp.  This step reduces (in
4264 /// a mathematical sense) the problem of reduction across warp masters in
4265 /// a block to the problem of warp reduction.
4266 ///
4267 ///
4268 /// Inter-Team Reduction
4269 ///
4270 /// Once a team has reduced its data to a single value, it is stored in
4271 /// a global scratchpad array.  Since each team has a distinct slot, this
4272 /// can be done without locking.
4273 ///
4274 /// The last team to write to the scratchpad array proceeds to reduce the
4275 /// scratchpad array.  One or more workers in the last team use the helper
4276 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4277 /// the k'th worker reduces every k'th element.
4278 ///
4279 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
4280 /// reduce across workers and compute a globally reduced value.
4281 ///
4282 void CGOpenMPRuntimeGPU::emitReduction(
4283     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4284     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4285     ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4286   if (!CGF.HaveInsertPoint())
4287     return;
4288 
4289   bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
4290 #ifndef NDEBUG
4291   bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
4292 #endif
4293 
4294   if (Options.SimpleReduction) {
4295     assert(!TeamsReduction && !ParallelReduction &&
4296            "Invalid reduction selection in emitReduction.");
4297     CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4298                                    ReductionOps, Options);
4299     return;
4300   }
4301 
4302   assert((TeamsReduction || ParallelReduction) &&
4303          "Invalid reduction selection in emitReduction.");
4304 
4305   // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
4306   // RedList, shuffle_reduce_func, interwarp_copy_func);
4307   // or
4308   // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
4309   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
4310   llvm::Value *ThreadId = getThreadID(CGF, Loc);
4311 
4312   llvm::Value *Res;
4313   ASTContext &C = CGM.getContext();
4314   // 1. Build a list of reduction variables.
4315   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4316   auto Size = RHSExprs.size();
4317   for (const Expr *E : Privates) {
4318     if (E->getType()->isVariablyModifiedType())
4319       // Reserve place for array size.
4320       ++Size;
4321   }
4322   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4323   QualType ReductionArrayTy =
4324       C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
4325                              /*IndexTypeQuals=*/0);
4326   Address ReductionList =
4327       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4328   auto IPriv = Privates.begin();
4329   unsigned Idx = 0;
4330   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4331     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4332     CGF.Builder.CreateStore(
4333         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4334             CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
4335         Elem);
4336     if ((*IPriv)->getType()->isVariablyModifiedType()) {
4337       // Store array size.
4338       ++Idx;
4339       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4340       llvm::Value *Size = CGF.Builder.CreateIntCast(
4341           CGF.getVLASize(
4342                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4343               .NumElts,
4344           CGF.SizeTy, /*isSigned=*/false);
4345       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4346                               Elem);
4347     }
4348   }
4349 
4350   llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4351       ReductionList.getPointer(), CGF.VoidPtrTy);
4352   llvm::Function *ReductionFn = emitReductionFunction(
4353       Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4354       LHSExprs, RHSExprs, ReductionOps);
4355   llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4356   llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4357       CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4358   llvm::Value *InterWarpCopyFn =
4359       emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4360 
4361   if (ParallelReduction) {
4362     llvm::Value *Args[] = {RTLoc,
4363                            ThreadId,
4364                            CGF.Builder.getInt32(RHSExprs.size()),
4365                            ReductionArrayTySize,
4366                            RL,
4367                            ShuffleAndReduceFn,
4368                            InterWarpCopyFn};
4369 
4370     Res = CGF.EmitRuntimeCall(
4371         createNVPTXRuntimeFunction(
4372             OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4373         Args);
4374   } else {
4375     assert(TeamsReduction && "expected teams reduction.");
4376     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4377     llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4378     int Cnt = 0;
4379     for (const Expr *DRE : Privates) {
4380       PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4381       ++Cnt;
4382     }
4383     const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4384         CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4385         C.getLangOpts().OpenMPCUDAReductionBufNum);
4386     TeamsReductions.push_back(TeamReductionRec);
4387     if (!KernelTeamsReductionPtr) {
4388       KernelTeamsReductionPtr = new llvm::GlobalVariable(
4389           CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4390           llvm::GlobalValue::InternalLinkage, nullptr,
4391           "_openmp_teams_reductions_buffer_$_$ptr");
4392     }
4393     llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4394         Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4395         /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4396     llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4397         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4398     llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4399         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4400         ReductionFn);
4401     llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4402         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4403     llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4404         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4405         ReductionFn);
4406 
4407     llvm::Value *Args[] = {
4408         RTLoc,
4409         ThreadId,
4410         GlobalBufferPtr,
4411         CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4412         RL,
4413         ShuffleAndReduceFn,
4414         InterWarpCopyFn,
4415         GlobalToBufferCpyFn,
4416         GlobalToBufferRedFn,
4417         BufferToGlobalCpyFn,
4418         BufferToGlobalRedFn};
4419 
4420     Res = CGF.EmitRuntimeCall(
4421         createNVPTXRuntimeFunction(
4422             OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
4423         Args);
4424   }
4425 
4426   // 5. Build if (res == 1)
4427   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4428   llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4429   llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4430       Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4431   CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
4432 
4433   // 6. Build then branch: where we have reduced values in the master
4434   //    thread in each team.
4435   //    __kmpc_end_reduce{_nowait}(<gtid>);
4436   //    break;
4437   CGF.EmitBlock(ThenBB);
4438 
4439   // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
4440   auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
4441                     this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4442     auto IPriv = Privates.begin();
4443     auto ILHS = LHSExprs.begin();
4444     auto IRHS = RHSExprs.begin();
4445     for (const Expr *E : ReductionOps) {
4446       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4447                                   cast<DeclRefExpr>(*IRHS));
4448       ++IPriv;
4449       ++ILHS;
4450       ++IRHS;
4451     }
4452   };
4453   llvm::Value *EndArgs[] = {ThreadId};
4454   RegionCodeGenTy RCG(CodeGen);
4455   NVPTXActionTy Action(
4456       nullptr, llvm::None,
4457       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4458       EndArgs);
4459   RCG.setAction(Action);
4460   RCG(CGF);
4461   // There is no need to emit line number for unconditional branch.
4462   (void)ApplyDebugLocation::CreateEmpty(CGF);
4463   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
4464 }
4465 
4466 const VarDecl *
4467 CGOpenMPRuntimeGPU::translateParameter(const FieldDecl *FD,
4468                                          const VarDecl *NativeParam) const {
4469   if (!NativeParam->getType()->isReferenceType())
4470     return NativeParam;
4471   QualType ArgType = NativeParam->getType();
4472   QualifierCollector QC;
4473   const Type *NonQualTy = QC.strip(ArgType);
4474   QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4475   if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4476     if (Attr->getCaptureKind() == OMPC_map) {
4477       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4478                                                         LangAS::opencl_global);
4479     } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4480                PointeeTy.isConstant(CGM.getContext())) {
4481       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4482                                                         LangAS::opencl_generic);
4483     }
4484   }
4485   ArgType = CGM.getContext().getPointerType(PointeeTy);
4486   QC.addRestrict();
4487   enum { NVPTX_local_addr = 5 };
4488   QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
4489   ArgType = QC.apply(CGM.getContext(), ArgType);
4490   if (isa<ImplicitParamDecl>(NativeParam))
4491     return ImplicitParamDecl::Create(
4492         CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4493         NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
4494   return ParmVarDecl::Create(
4495       CGM.getContext(),
4496       const_cast<DeclContext *>(NativeParam->getDeclContext()),
4497       NativeParam->getBeginLoc(), NativeParam->getLocation(),
4498       NativeParam->getIdentifier(), ArgType,
4499       /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
4500 }
4501 
4502 Address
4503 CGOpenMPRuntimeGPU::getParameterAddress(CodeGenFunction &CGF,
4504                                           const VarDecl *NativeParam,
4505                                           const VarDecl *TargetParam) const {
4506   assert(NativeParam != TargetParam &&
4507          NativeParam->getType()->isReferenceType() &&
4508          "Native arg must not be the same as target arg.");
4509   Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4510   QualType NativeParamType = NativeParam->getType();
4511   QualifierCollector QC;
4512   const Type *NonQualTy = QC.strip(NativeParamType);
4513   QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4514   unsigned NativePointeeAddrSpace =
4515       CGF.getContext().getTargetAddressSpace(NativePointeeTy);
4516   QualType TargetTy = TargetParam->getType();
4517   llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
4518       LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
4519   // First cast to generic.
4520   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4521       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4522                       /*AddrSpace=*/0));
4523   // Cast from generic to native address space.
4524   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4525       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4526                       NativePointeeAddrSpace));
4527   Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4528   CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
4529                         NativeParamType);
4530   return NativeParamAddr;
4531 }
4532 
4533 void CGOpenMPRuntimeGPU::emitOutlinedFunctionCall(
4534     CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
4535     ArrayRef<llvm::Value *> Args) const {
4536   SmallVector<llvm::Value *, 4> TargetArgs;
4537   TargetArgs.reserve(Args.size());
4538   auto *FnType = OutlinedFn.getFunctionType();
4539   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
4540     if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4541       TargetArgs.append(std::next(Args.begin(), I), Args.end());
4542       break;
4543     }
4544     llvm::Type *TargetType = FnType->getParamType(I);
4545     llvm::Value *NativeArg = Args[I];
4546     if (!TargetType->isPointerTy()) {
4547       TargetArgs.emplace_back(NativeArg);
4548       continue;
4549     }
4550     llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4551         NativeArg,
4552         NativeArg->getType()->getPointerElementType()->getPointerTo());
4553     TargetArgs.emplace_back(
4554         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4555   }
4556   CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
4557 }
4558 
4559 /// Emit function which wraps the outline parallel region
4560 /// and controls the arguments which are passed to this function.
4561 /// The wrapper ensures that the outlined function is called
4562 /// with the correct arguments when data is shared.
4563 llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
4564     llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4565   ASTContext &Ctx = CGM.getContext();
4566   const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4567 
4568   // Create a function that takes as argument the source thread.
4569   FunctionArgList WrapperArgs;
4570   QualType Int16QTy =
4571       Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4572   QualType Int32QTy =
4573       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
4574   ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4575                                      /*Id=*/nullptr, Int16QTy,
4576                                      ImplicitParamDecl::Other);
4577   ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4578                                /*Id=*/nullptr, Int32QTy,
4579                                ImplicitParamDecl::Other);
4580   WrapperArgs.emplace_back(&ParallelLevelArg);
4581   WrapperArgs.emplace_back(&WrapperArg);
4582 
4583   const CGFunctionInfo &CGFI =
4584       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4585 
4586   auto *Fn = llvm::Function::Create(
4587       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4588       Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
4589   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
4590   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
4591   Fn->setDoesNotRecurse();
4592 
4593   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4594   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
4595                     D.getBeginLoc(), D.getBeginLoc());
4596 
4597   const auto *RD = CS.getCapturedRecordDecl();
4598   auto CurField = RD->field_begin();
4599 
4600   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4601                                                       /*Name=*/".zero.addr");
4602   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
4603   // Get the array of arguments.
4604   SmallVector<llvm::Value *, 8> Args;
4605 
4606   Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4607   Args.emplace_back(ZeroAddr.getPointer());
4608 
4609   CGBuilderTy &Bld = CGF.Builder;
4610   auto CI = CS.capture_begin();
4611 
4612   // Use global memory for data sharing.
4613   // Handle passing of global args to workers.
4614   Address GlobalArgs =
4615       CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4616   llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4617   llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4618   CGF.EmitRuntimeCall(
4619       createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4620       DataSharingArgs);
4621 
4622   // Retrieve the shared variables from the list of references returned
4623   // by the runtime. Pass the variables to the outlined function.
4624   Address SharedArgListAddress = Address::invalid();
4625   if (CS.capture_size() > 0 ||
4626       isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4627     SharedArgListAddress = CGF.EmitLoadOfPointer(
4628         GlobalArgs, CGF.getContext()
4629                         .getPointerType(CGF.getContext().getPointerType(
4630                             CGF.getContext().VoidPtrTy))
4631                         .castAs<PointerType>());
4632   }
4633   unsigned Idx = 0;
4634   if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4635     Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4636     Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4637         Src, CGF.SizeTy->getPointerTo());
4638     llvm::Value *LB = CGF.EmitLoadOfScalar(
4639         TypedAddress,
4640         /*Volatile=*/false,
4641         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4642         cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4643     Args.emplace_back(LB);
4644     ++Idx;
4645     Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4646     TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4647         Src, CGF.SizeTy->getPointerTo());
4648     llvm::Value *UB = CGF.EmitLoadOfScalar(
4649         TypedAddress,
4650         /*Volatile=*/false,
4651         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4652         cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4653     Args.emplace_back(UB);
4654     ++Idx;
4655   }
4656   if (CS.capture_size() > 0) {
4657     ASTContext &CGFContext = CGF.getContext();
4658     for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4659       QualType ElemTy = CurField->getType();
4660       Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
4661       Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4662           Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4663       llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4664                                               /*Volatile=*/false,
4665                                               CGFContext.getPointerType(ElemTy),
4666                                               CI->getLocation());
4667       if (CI->capturesVariableByCopy() &&
4668           !CI->getCapturedVar()->getType()->isAnyPointerType()) {
4669         Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4670                               CI->getLocation());
4671       }
4672       Args.emplace_back(Arg);
4673     }
4674   }
4675 
4676   emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
4677   CGF.FinishFunction();
4678   return Fn;
4679 }
4680 
4681 void CGOpenMPRuntimeGPU::emitFunctionProlog(CodeGenFunction &CGF,
4682                                               const Decl *D) {
4683   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
4684     return;
4685 
4686   assert(D && "Expected function or captured|block decl.");
4687   assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4688          "Function is registered already.");
4689   assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4690          "Team is set but not processed.");
4691   const Stmt *Body = nullptr;
4692   bool NeedToDelayGlobalization = false;
4693   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4694     Body = FD->getBody();
4695   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4696     Body = BD->getBody();
4697   } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4698     Body = CD->getBody();
4699     NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
4700     if (NeedToDelayGlobalization &&
4701         getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
4702       return;
4703   }
4704   if (!Body)
4705     return;
4706   CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
4707   VarChecker.Visit(Body);
4708   const RecordDecl *GlobalizedVarsRecord =
4709       VarChecker.getGlobalizedRecord(IsInTTDRegion);
4710   TeamAndReductions.first = nullptr;
4711   TeamAndReductions.second.clear();
4712   ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4713       VarChecker.getEscapedVariableLengthDecls();
4714   if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
4715     return;
4716   auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4717   I->getSecond().MappedParams =
4718       std::make_unique<CodeGenFunction::OMPMapVars>();
4719   I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4720   I->getSecond().EscapedParameters.insert(
4721       VarChecker.getEscapedParameters().begin(),
4722       VarChecker.getEscapedParameters().end());
4723   I->getSecond().EscapedVariableLengthDecls.append(
4724       EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
4725   DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
4726   for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4727     assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4728     const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4729     Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
4730   }
4731   if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
4732     CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
4733     VarChecker.Visit(Body);
4734     I->getSecond().SecondaryGlobalRecord =
4735         VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
4736     I->getSecond().SecondaryLocalVarData.emplace();
4737     DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4738     for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4739       assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4740       const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4741       Data.insert(
4742           std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
4743     }
4744   }
4745   if (!NeedToDelayGlobalization) {
4746     emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
4747     struct GlobalizationScope final : EHScopeStack::Cleanup {
4748       GlobalizationScope() = default;
4749 
4750       void Emit(CodeGenFunction &CGF, Flags flags) override {
4751         static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
4752             .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
4753       }
4754     };
4755     CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
4756   }
4757 }
4758 
4759 Address CGOpenMPRuntimeGPU::getAddressOfLocalVariable(CodeGenFunction &CGF,
4760                                                         const VarDecl *VD) {
4761   if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4762     const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4763     auto AS = LangAS::Default;
4764     switch (A->getAllocatorType()) {
4765       // Use the default allocator here as by default local vars are
4766       // threadlocal.
4767     case OMPAllocateDeclAttr::OMPNullMemAlloc:
4768     case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4769     case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4770     case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4771     case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4772       // Follow the user decision - use default allocation.
4773       return Address::invalid();
4774     case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4775       // TODO: implement aupport for user-defined allocators.
4776       return Address::invalid();
4777     case OMPAllocateDeclAttr::OMPConstMemAlloc:
4778       AS = LangAS::cuda_constant;
4779       break;
4780     case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4781       AS = LangAS::cuda_shared;
4782       break;
4783     case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4784     case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4785       break;
4786     }
4787     llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4788     auto *GV = new llvm::GlobalVariable(
4789         CGM.getModule(), VarTy, /*isConstant=*/false,
4790         llvm::GlobalValue::InternalLinkage, llvm::Constant::getNullValue(VarTy),
4791         VD->getName(),
4792         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4793         CGM.getContext().getTargetAddressSpace(AS));
4794     CharUnits Align = CGM.getContext().getDeclAlign(VD);
4795     GV->setAlignment(Align.getAsAlign());
4796     return Address(
4797         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4798             GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
4799                     VD->getType().getAddressSpace()))),
4800         Align);
4801   }
4802 
4803   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
4804     return Address::invalid();
4805 
4806   VD = VD->getCanonicalDecl();
4807   auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4808   if (I == FunctionGlobalizedDecls.end())
4809     return Address::invalid();
4810   auto VDI = I->getSecond().LocalVarData.find(VD);
4811   if (VDI != I->getSecond().LocalVarData.end())
4812     return VDI->second.PrivateAddr;
4813   if (VD->hasAttrs()) {
4814     for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4815          E(VD->attr_end());
4816          IT != E; ++IT) {
4817       auto VDI = I->getSecond().LocalVarData.find(
4818           cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4819               ->getCanonicalDecl());
4820       if (VDI != I->getSecond().LocalVarData.end())
4821         return VDI->second.PrivateAddr;
4822     }
4823   }
4824 
4825   return Address::invalid();
4826 }
4827 
4828 void CGOpenMPRuntimeGPU::functionFinished(CodeGenFunction &CGF) {
4829   FunctionGlobalizedDecls.erase(CGF.CurFn);
4830   CGOpenMPRuntime::functionFinished(CGF);
4831 }
4832 
4833 void CGOpenMPRuntimeGPU::getDefaultDistScheduleAndChunk(
4834     CodeGenFunction &CGF, const OMPLoopDirective &S,
4835     OpenMPDistScheduleClauseKind &ScheduleKind,
4836     llvm::Value *&Chunk) const {
4837   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
4838   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
4839     ScheduleKind = OMPC_DIST_SCHEDULE_static;
4840     Chunk = CGF.EmitScalarConversion(
4841         RT.getGPUNumThreads(CGF),
4842         CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4843         S.getIterationVariable()->getType(), S.getBeginLoc());
4844     return;
4845   }
4846   CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4847       CGF, S, ScheduleKind, Chunk);
4848 }
4849 
4850 void CGOpenMPRuntimeGPU::getDefaultScheduleAndChunk(
4851     CodeGenFunction &CGF, const OMPLoopDirective &S,
4852     OpenMPScheduleClauseKind &ScheduleKind,
4853     const Expr *&ChunkExpr) const {
4854   ScheduleKind = OMPC_SCHEDULE_static;
4855   // Chunk size is 1 in this case.
4856   llvm::APInt ChunkSize(32, 1);
4857   ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4858       CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4859       SourceLocation());
4860 }
4861 
4862 void CGOpenMPRuntimeGPU::adjustTargetSpecificDataForLambdas(
4863     CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4864   assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4865          " Expected target-based directive.");
4866   const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4867   for (const CapturedStmt::Capture &C : CS->captures()) {
4868     // Capture variables captured by reference in lambdas for target-based
4869     // directives.
4870     if (!C.capturesVariable())
4871       continue;
4872     const VarDecl *VD = C.getCapturedVar();
4873     const auto *RD = VD->getType()
4874                          .getCanonicalType()
4875                          .getNonReferenceType()
4876                          ->getAsCXXRecordDecl();
4877     if (!RD || !RD->isLambda())
4878       continue;
4879     Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4880     LValue VDLVal;
4881     if (VD->getType().getCanonicalType()->isReferenceType())
4882       VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4883     else
4884       VDLVal = CGF.MakeAddrLValue(
4885           VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4886     llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4887     FieldDecl *ThisCapture = nullptr;
4888     RD->getCaptureFields(Captures, ThisCapture);
4889     if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4890       LValue ThisLVal =
4891           CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4892       llvm::Value *CXXThis = CGF.LoadCXXThis();
4893       CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4894     }
4895     for (const LambdaCapture &LC : RD->captures()) {
4896       if (LC.getCaptureKind() != LCK_ByRef)
4897         continue;
4898       const VarDecl *VD = LC.getCapturedVar();
4899       if (!CS->capturesVariable(VD))
4900         continue;
4901       auto It = Captures.find(VD);
4902       assert(It != Captures.end() && "Found lambda capture without field.");
4903       LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4904       Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4905       if (VD->getType().getCanonicalType()->isReferenceType())
4906         VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4907                                                VD->getType().getCanonicalType())
4908                      .getAddress(CGF);
4909       CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4910     }
4911   }
4912 }
4913 
4914 unsigned CGOpenMPRuntimeGPU::getDefaultFirstprivateAddressSpace() const {
4915   return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4916 }
4917 
4918 bool CGOpenMPRuntimeGPU::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4919                                                             LangAS &AS) {
4920   if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4921     return false;
4922   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4923   switch(A->getAllocatorType()) {
4924   case OMPAllocateDeclAttr::OMPNullMemAlloc:
4925   case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4926   // Not supported, fallback to the default mem space.
4927   case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4928   case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4929   case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4930   case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4931   case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4932     AS = LangAS::Default;
4933     return true;
4934   case OMPAllocateDeclAttr::OMPConstMemAlloc:
4935     AS = LangAS::cuda_constant;
4936     return true;
4937   case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4938     AS = LangAS::cuda_shared;
4939     return true;
4940   case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4941     llvm_unreachable("Expected predefined allocator for the variables with the "
4942                      "static storage.");
4943   }
4944   return false;
4945 }
4946 
4947 // Get current CudaArch and ignore any unknown values
4948 static CudaArch getCudaArch(CodeGenModule &CGM) {
4949   if (!CGM.getTarget().hasFeature("ptx"))
4950     return CudaArch::UNKNOWN;
4951   for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
4952     if (Feature.getValue()) {
4953       CudaArch Arch = StringToCudaArch(Feature.getKey());
4954       if (Arch != CudaArch::UNKNOWN)
4955         return Arch;
4956     }
4957   }
4958   return CudaArch::UNKNOWN;
4959 }
4960 
4961 /// Check to see if target architecture supports unified addressing which is
4962 /// a restriction for OpenMP requires clause "unified_shared_memory".
4963 void CGOpenMPRuntimeGPU::processRequiresDirective(
4964     const OMPRequiresDecl *D) {
4965   for (const OMPClause *Clause : D->clauselists()) {
4966     if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4967       CudaArch Arch = getCudaArch(CGM);
4968       switch (Arch) {
4969       case CudaArch::SM_20:
4970       case CudaArch::SM_21:
4971       case CudaArch::SM_30:
4972       case CudaArch::SM_32:
4973       case CudaArch::SM_35:
4974       case CudaArch::SM_37:
4975       case CudaArch::SM_50:
4976       case CudaArch::SM_52:
4977       case CudaArch::SM_53:
4978       case CudaArch::SM_60:
4979       case CudaArch::SM_61:
4980       case CudaArch::SM_62: {
4981         SmallString<256> Buffer;
4982         llvm::raw_svector_ostream Out(Buffer);
4983         Out << "Target architecture " << CudaArchToString(Arch)
4984             << " does not support unified addressing";
4985         CGM.Error(Clause->getBeginLoc(), Out.str());
4986         return;
4987       }
4988       case CudaArch::SM_70:
4989       case CudaArch::SM_72:
4990       case CudaArch::SM_75:
4991       case CudaArch::SM_80:
4992       case CudaArch::GFX600:
4993       case CudaArch::GFX601:
4994       case CudaArch::GFX700:
4995       case CudaArch::GFX701:
4996       case CudaArch::GFX702:
4997       case CudaArch::GFX703:
4998       case CudaArch::GFX704:
4999       case CudaArch::GFX801:
5000       case CudaArch::GFX802:
5001       case CudaArch::GFX803:
5002       case CudaArch::GFX810:
5003       case CudaArch::GFX900:
5004       case CudaArch::GFX902:
5005       case CudaArch::GFX904:
5006       case CudaArch::GFX906:
5007       case CudaArch::GFX908:
5008       case CudaArch::GFX909:
5009       case CudaArch::GFX1010:
5010       case CudaArch::GFX1011:
5011       case CudaArch::GFX1012:
5012       case CudaArch::GFX1030:
5013       case CudaArch::GFX1031:
5014       case CudaArch::UNKNOWN:
5015         break;
5016       case CudaArch::LAST:
5017         llvm_unreachable("Unexpected Cuda arch.");
5018       }
5019     }
5020   }
5021   CGOpenMPRuntime::processRequiresDirective(D);
5022 }
5023 
5024 /// Get number of SMs and number of blocks per SM.
5025 static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
5026   std::pair<unsigned, unsigned> Data;
5027   if (CGM.getLangOpts().OpenMPCUDANumSMs)
5028     Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
5029   if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5030     Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5031   if (Data.first && Data.second)
5032     return Data;
5033   switch (getCudaArch(CGM)) {
5034   case CudaArch::SM_20:
5035   case CudaArch::SM_21:
5036   case CudaArch::SM_30:
5037   case CudaArch::SM_32:
5038   case CudaArch::SM_35:
5039   case CudaArch::SM_37:
5040   case CudaArch::SM_50:
5041   case CudaArch::SM_52:
5042   case CudaArch::SM_53:
5043     return {16, 16};
5044   case CudaArch::SM_60:
5045   case CudaArch::SM_61:
5046   case CudaArch::SM_62:
5047     return {56, 32};
5048   case CudaArch::SM_70:
5049   case CudaArch::SM_72:
5050   case CudaArch::SM_75:
5051   case CudaArch::SM_80:
5052     return {84, 32};
5053   case CudaArch::GFX600:
5054   case CudaArch::GFX601:
5055   case CudaArch::GFX700:
5056   case CudaArch::GFX701:
5057   case CudaArch::GFX702:
5058   case CudaArch::GFX703:
5059   case CudaArch::GFX704:
5060   case CudaArch::GFX801:
5061   case CudaArch::GFX802:
5062   case CudaArch::GFX803:
5063   case CudaArch::GFX810:
5064   case CudaArch::GFX900:
5065   case CudaArch::GFX902:
5066   case CudaArch::GFX904:
5067   case CudaArch::GFX906:
5068   case CudaArch::GFX908:
5069   case CudaArch::GFX909:
5070   case CudaArch::GFX1010:
5071   case CudaArch::GFX1011:
5072   case CudaArch::GFX1012:
5073   case CudaArch::GFX1030:
5074   case CudaArch::GFX1031:
5075   case CudaArch::UNKNOWN:
5076     break;
5077   case CudaArch::LAST:
5078     llvm_unreachable("Unexpected Cuda arch.");
5079   }
5080   llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5081 }
5082 
5083 void CGOpenMPRuntimeGPU::clear() {
5084   if (!GlobalizedRecords.empty() &&
5085       !CGM.getLangOpts().OpenMPCUDATargetParallel) {
5086     ASTContext &C = CGM.getContext();
5087     llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5088     llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
5089     RecordDecl *StaticRD = C.buildImplicitRecord(
5090         "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5091     StaticRD->startDefinition();
5092     RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5093         "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5094     SharedStaticRD->startDefinition();
5095     for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5096       if (Records.Records.empty())
5097         continue;
5098       unsigned Size = 0;
5099       unsigned RecAlignment = 0;
5100       for (const RecordDecl *RD : Records.Records) {
5101         QualType RDTy = C.getRecordType(RD);
5102         unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
5103         RecAlignment = std::max(RecAlignment, Alignment);
5104         unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
5105         Size =
5106             llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5107       }
5108       Size = llvm::alignTo(Size, RecAlignment);
5109       llvm::APInt ArySize(/*numBits=*/64, Size);
5110       QualType SubTy = C.getConstantArrayType(
5111           C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
5112       const bool UseSharedMemory = Size <= SharedMemorySize;
5113       auto *Field =
5114           FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5115                             SourceLocation(), SourceLocation(), nullptr, SubTy,
5116                             C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5117                             /*BW=*/nullptr, /*Mutable=*/false,
5118                             /*InitStyle=*/ICIS_NoInit);
5119       Field->setAccess(AS_public);
5120       if (UseSharedMemory) {
5121         SharedStaticRD->addDecl(Field);
5122         SharedRecs.push_back(&Records);
5123       } else {
5124         StaticRD->addDecl(Field);
5125         GlobalRecs.push_back(&Records);
5126       }
5127       Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
5128       Records.UseSharedMemory->setInitializer(
5129           llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5130     }
5131     // Allocate SharedMemorySize buffer for the shared memory.
5132     // FIXME: nvlink does not handle weak linkage correctly (object with the
5133     // different size are reported as erroneous).
5134     // Restore this code as sson as nvlink is fixed.
5135     if (!SharedStaticRD->field_empty()) {
5136       llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5137       QualType SubTy = C.getConstantArrayType(
5138           C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
5139       auto *Field = FieldDecl::Create(
5140           C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5141           C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5142           /*BW=*/nullptr, /*Mutable=*/false,
5143           /*InitStyle=*/ICIS_NoInit);
5144       Field->setAccess(AS_public);
5145       SharedStaticRD->addDecl(Field);
5146     }
5147     SharedStaticRD->completeDefinition();
5148     if (!SharedStaticRD->field_empty()) {
5149       QualType StaticTy = C.getRecordType(SharedStaticRD);
5150       llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5151       auto *GV = new llvm::GlobalVariable(
5152           CGM.getModule(), LLVMStaticTy,
5153           /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
5154           llvm::Constant::getNullValue(LLVMStaticTy),
5155           "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5156           llvm::GlobalValue::NotThreadLocal,
5157           C.getTargetAddressSpace(LangAS::cuda_shared));
5158       auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5159           GV, CGM.VoidPtrTy);
5160       for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5161         Rec->Buffer->replaceAllUsesWith(Replacement);
5162         Rec->Buffer->eraseFromParent();
5163       }
5164     }
5165     StaticRD->completeDefinition();
5166     if (!StaticRD->field_empty()) {
5167       QualType StaticTy = C.getRecordType(StaticRD);
5168       std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5169       llvm::APInt Size1(32, SMsBlockPerSM.second);
5170       QualType Arr1Ty =
5171           C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
5172                                  /*IndexTypeQuals=*/0);
5173       llvm::APInt Size2(32, SMsBlockPerSM.first);
5174       QualType Arr2Ty =
5175           C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5176                                  /*IndexTypeQuals=*/0);
5177       llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
5178       // FIXME: nvlink does not handle weak linkage correctly (object with the
5179       // different size are reported as erroneous).
5180       // Restore CommonLinkage as soon as nvlink is fixed.
5181       auto *GV = new llvm::GlobalVariable(
5182           CGM.getModule(), LLVMArr2Ty,
5183           /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
5184           llvm::Constant::getNullValue(LLVMArr2Ty),
5185           "_openmp_static_glob_rd_$_");
5186       auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5187           GV, CGM.VoidPtrTy);
5188       for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5189         Rec->Buffer->replaceAllUsesWith(Replacement);
5190         Rec->Buffer->eraseFromParent();
5191       }
5192     }
5193   }
5194   if (!TeamsReductions.empty()) {
5195     ASTContext &C = CGM.getContext();
5196     RecordDecl *StaticRD = C.buildImplicitRecord(
5197         "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5198     StaticRD->startDefinition();
5199     for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5200       QualType RecTy = C.getRecordType(TeamReductionRec);
5201       auto *Field = FieldDecl::Create(
5202           C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5203           C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5204           /*BW=*/nullptr, /*Mutable=*/false,
5205           /*InitStyle=*/ICIS_NoInit);
5206       Field->setAccess(AS_public);
5207       StaticRD->addDecl(Field);
5208     }
5209     StaticRD->completeDefinition();
5210     QualType StaticTy = C.getRecordType(StaticRD);
5211     llvm::Type *LLVMReductionsBufferTy =
5212         CGM.getTypes().ConvertTypeForMem(StaticTy);
5213     // FIXME: nvlink does not handle weak linkage correctly (object with the
5214     // different size are reported as erroneous).
5215     // Restore CommonLinkage as soon as nvlink is fixed.
5216     auto *GV = new llvm::GlobalVariable(
5217         CGM.getModule(), LLVMReductionsBufferTy,
5218         /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
5219         llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5220         "_openmp_teams_reductions_buffer_$_");
5221     KernelTeamsReductionPtr->setInitializer(
5222         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5223                                                              CGM.VoidPtrTy));
5224   }
5225   CGOpenMPRuntime::clear();
5226 }
5227