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