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