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     Address CapturedVarsAddrs = CGF.CreateDefaultAlignTempAlloca(
1527         llvm::ArrayType::get(CGM.VoidPtrTy, CapturedVars.size()),
1528         "captured_vars_addrs");
1529     // There's something to share.
1530     if (!CapturedVars.empty()) {
1531       // Prepare for parallel region. Indicate the outlined function.
1532       ASTContext &Ctx = CGF.getContext();
1533       unsigned Idx = 0;
1534       for (llvm::Value *V : CapturedVars) {
1535         Address Dst = Bld.CreateConstArrayGEP(CapturedVarsAddrs, Idx);
1536         llvm::Value *PtrV;
1537         if (V->getType()->isIntegerTy())
1538           PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1539         else
1540           PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
1541         CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1542                               Ctx.getPointerType(Ctx.VoidPtrTy));
1543         ++Idx;
1544       }
1545     }
1546 
1547     llvm::Value *IfCondVal = nullptr;
1548     if (IfCond)
1549       IfCondVal = Bld.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.Int32Ty,
1550                                     /* isSigned */ false);
1551     else
1552       IfCondVal = llvm::ConstantInt::get(CGF.Int32Ty, 1);
1553 
1554     assert(IfCondVal && "Expected a value");
1555     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1556     llvm::Value *Args[] = {
1557         RTLoc,
1558         getThreadID(CGF, Loc),
1559         IfCondVal,
1560         llvm::ConstantInt::get(CGF.Int32Ty, -1),
1561         llvm::ConstantInt::get(CGF.Int32Ty, -1),
1562         FnPtr,
1563         ID,
1564         Bld.CreateBitOrPointerCast(CapturedVarsAddrs.getPointer(),
1565                                    CGF.VoidPtrPtrTy),
1566         llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1567     CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1568                             CGM.getModule(), OMPRTL___kmpc_parallel_51),
1569                         Args);
1570   };
1571 
1572   RegionCodeGenTy RCG(ParallelGen);
1573   RCG(CGF);
1574 }
1575 
1576 void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
1577   // Always emit simple barriers!
1578   if (!CGF.HaveInsertPoint())
1579     return;
1580   // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
1581   // This function does not use parameters, so we can emit just default values.
1582   llvm::Value *Args[] = {
1583       llvm::ConstantPointerNull::get(
1584           cast<llvm::PointerType>(getIdentTyPointerTy())),
1585       llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
1586   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1587                           CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
1588                       Args);
1589 }
1590 
1591 void CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
1592                                            SourceLocation Loc,
1593                                            OpenMPDirectiveKind Kind, bool,
1594                                            bool) {
1595   // Always emit simple barriers!
1596   if (!CGF.HaveInsertPoint())
1597     return;
1598   // Build call __kmpc_cancel_barrier(loc, thread_id);
1599   unsigned Flags = getDefaultFlagsForBarriers(Kind);
1600   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1601                          getThreadID(CGF, Loc)};
1602 
1603   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1604                           CGM.getModule(), OMPRTL___kmpc_barrier),
1605                       Args);
1606 }
1607 
1608 void CGOpenMPRuntimeGPU::emitCriticalRegion(
1609     CodeGenFunction &CGF, StringRef CriticalName,
1610     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1611     const Expr *Hint) {
1612   llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1613   llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1614   llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1615   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1616   llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1617 
1618   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1619 
1620   // Get the mask of active threads in the warp.
1621   llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1622       CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
1623   // Fetch team-local id of the thread.
1624   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
1625 
1626   // Get the width of the team.
1627   llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
1628 
1629   // Initialize the counter variable for the loop.
1630   QualType Int32Ty =
1631       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1632   Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1633   LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1634   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1635                         /*isInit=*/true);
1636 
1637   // Block checks if loop counter exceeds upper bound.
1638   CGF.EmitBlock(LoopBB);
1639   llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1640   llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1641   CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1642 
1643   // Block tests which single thread should execute region, and which threads
1644   // should go straight to synchronisation point.
1645   CGF.EmitBlock(TestBB);
1646   CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1647   llvm::Value *CmpThreadToCounter =
1648       CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1649   CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1650 
1651   // Block emits the body of the critical region.
1652   CGF.EmitBlock(BodyBB);
1653 
1654   // Output the critical statement.
1655   CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
1656                                       Hint);
1657 
1658   // After the body surrounded by the critical region, the single executing
1659   // thread will jump to the synchronisation point.
1660   // Block waits for all threads in current team to finish then increments the
1661   // counter variable and returns to the loop.
1662   CGF.EmitBlock(SyncBB);
1663   // Reconverge active threads in the warp.
1664   (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1665                                 CGM.getModule(), OMPRTL___kmpc_syncwarp),
1666                             Mask);
1667 
1668   llvm::Value *IncCounterVal =
1669       CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1670   CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1671   CGF.EmitBranch(LoopBB);
1672 
1673   // Block that is reached when  all threads in the team complete the region.
1674   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1675 }
1676 
1677 /// Cast value to the specified type.
1678 static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
1679                                     QualType ValTy, QualType CastTy,
1680                                     SourceLocation Loc) {
1681   assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
1682          "Cast type must sized.");
1683   assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
1684          "Val type must sized.");
1685   llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
1686   if (ValTy == CastTy)
1687     return Val;
1688   if (CGF.getContext().getTypeSizeInChars(ValTy) ==
1689       CGF.getContext().getTypeSizeInChars(CastTy))
1690     return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
1691   if (CastTy->isIntegerType() && ValTy->isIntegerType())
1692     return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
1693                                      CastTy->hasSignedIntegerRepresentation());
1694   Address CastItem = CGF.CreateMemTemp(CastTy);
1695   Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1696       CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
1697   CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
1698                         LValueBaseInfo(AlignmentSource::Type),
1699                         TBAAAccessInfo());
1700   return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
1701                               LValueBaseInfo(AlignmentSource::Type),
1702                               TBAAAccessInfo());
1703 }
1704 
1705 /// This function creates calls to one of two shuffle functions to copy
1706 /// variables between lanes in a warp.
1707 static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
1708                                                  llvm::Value *Elem,
1709                                                  QualType ElemType,
1710                                                  llvm::Value *Offset,
1711                                                  SourceLocation Loc) {
1712   CodeGenModule &CGM = CGF.CGM;
1713   CGBuilderTy &Bld = CGF.Builder;
1714   CGOpenMPRuntimeGPU &RT =
1715       *(static_cast<CGOpenMPRuntimeGPU *>(&CGM.getOpenMPRuntime()));
1716   llvm::OpenMPIRBuilder &OMPBuilder = RT.getOMPBuilder();
1717 
1718   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
1719   assert(Size.getQuantity() <= 8 &&
1720          "Unsupported bitwidth in shuffle instruction.");
1721 
1722   RuntimeFunction ShuffleFn = Size.getQuantity() <= 4
1723                                   ? OMPRTL___kmpc_shuffle_int32
1724                                   : OMPRTL___kmpc_shuffle_int64;
1725 
1726   // Cast all types to 32- or 64-bit values before calling shuffle routines.
1727   QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
1728       Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
1729   llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
1730   llvm::Value *WarpSize =
1731       Bld.CreateIntCast(RT.getGPUWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
1732 
1733   llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
1734       OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), ShuffleFn),
1735       {ElemCast, Offset, WarpSize});
1736 
1737   return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
1738 }
1739 
1740 static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
1741                             Address DestAddr, QualType ElemType,
1742                             llvm::Value *Offset, SourceLocation Loc) {
1743   CGBuilderTy &Bld = CGF.Builder;
1744 
1745   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
1746   // Create the loop over the big sized data.
1747   // ptr = (void*)Elem;
1748   // ptrEnd = (void*) Elem + 1;
1749   // Step = 8;
1750   // while (ptr + Step < ptrEnd)
1751   //   shuffle((int64_t)*ptr);
1752   // Step = 4;
1753   // while (ptr + Step < ptrEnd)
1754   //   shuffle((int32_t)*ptr);
1755   // ...
1756   Address ElemPtr = DestAddr;
1757   Address Ptr = SrcAddr;
1758   Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
1759       Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
1760   for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
1761     if (Size < CharUnits::fromQuantity(IntSize))
1762       continue;
1763     QualType IntType = CGF.getContext().getIntTypeForBitwidth(
1764         CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
1765         /*Signed=*/1);
1766     llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
1767     Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
1768     ElemPtr =
1769         Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
1770     if (Size.getQuantity() / IntSize > 1) {
1771       llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
1772       llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
1773       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
1774       llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
1775       CGF.EmitBlock(PreCondBB);
1776       llvm::PHINode *PhiSrc =
1777           Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
1778       PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
1779       llvm::PHINode *PhiDest =
1780           Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
1781       PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
1782       Ptr = Address(PhiSrc, Ptr.getAlignment());
1783       ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
1784       llvm::Value *PtrDiff = Bld.CreatePtrDiff(
1785           PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
1786                                    Ptr.getPointer(), CGF.VoidPtrTy));
1787       Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
1788                        ThenBB, ExitBB);
1789       CGF.EmitBlock(ThenBB);
1790       llvm::Value *Res = createRuntimeShuffleFunction(
1791           CGF,
1792           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
1793                                LValueBaseInfo(AlignmentSource::Type),
1794                                TBAAAccessInfo()),
1795           IntType, Offset, Loc);
1796       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
1797                             LValueBaseInfo(AlignmentSource::Type),
1798                             TBAAAccessInfo());
1799       Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
1800       Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
1801       PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
1802       PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
1803       CGF.EmitBranch(PreCondBB);
1804       CGF.EmitBlock(ExitBB);
1805     } else {
1806       llvm::Value *Res = createRuntimeShuffleFunction(
1807           CGF,
1808           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
1809                                LValueBaseInfo(AlignmentSource::Type),
1810                                TBAAAccessInfo()),
1811           IntType, Offset, Loc);
1812       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
1813                             LValueBaseInfo(AlignmentSource::Type),
1814                             TBAAAccessInfo());
1815       Ptr = Bld.CreateConstGEP(Ptr, 1);
1816       ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
1817     }
1818     Size = Size % IntSize;
1819   }
1820 }
1821 
1822 namespace {
1823 enum CopyAction : unsigned {
1824   // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1825   // the warp using shuffle instructions.
1826   RemoteLaneToThread,
1827   // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1828   ThreadCopy,
1829   // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1830   ThreadToScratchpad,
1831   // ScratchpadToThread: Copy from a scratchpad array in global memory
1832   // containing team-reduced data to a thread's stack.
1833   ScratchpadToThread,
1834 };
1835 } // namespace
1836 
1837 struct CopyOptionsTy {
1838   llvm::Value *RemoteLaneOffset;
1839   llvm::Value *ScratchpadIndex;
1840   llvm::Value *ScratchpadWidth;
1841 };
1842 
1843 /// Emit instructions to copy a Reduce list, which contains partially
1844 /// aggregated values, in the specified direction.
1845 static void emitReductionListCopy(
1846     CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1847     ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1848     CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
1849 
1850   CodeGenModule &CGM = CGF.CGM;
1851   ASTContext &C = CGM.getContext();
1852   CGBuilderTy &Bld = CGF.Builder;
1853 
1854   llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1855   llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1856   llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
1857 
1858   // Iterates, element-by-element, through the source Reduce list and
1859   // make a copy.
1860   unsigned Idx = 0;
1861   unsigned Size = Privates.size();
1862   for (const Expr *Private : Privates) {
1863     Address SrcElementAddr = Address::invalid();
1864     Address DestElementAddr = Address::invalid();
1865     Address DestElementPtrAddr = Address::invalid();
1866     // Should we shuffle in an element from a remote lane?
1867     bool ShuffleInElement = false;
1868     // Set to true to update the pointer in the dest Reduce list to a
1869     // newly created element.
1870     bool UpdateDestListPtr = false;
1871     // Increment the src or dest pointer to the scratchpad, for each
1872     // new element.
1873     bool IncrScratchpadSrc = false;
1874     bool IncrScratchpadDest = false;
1875 
1876     switch (Action) {
1877     case RemoteLaneToThread: {
1878       // Step 1.1: Get the address for the src element in the Reduce list.
1879       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1880       SrcElementAddr = CGF.EmitLoadOfPointer(
1881           SrcElementPtrAddr,
1882           C.getPointerType(Private->getType())->castAs<PointerType>());
1883 
1884       // Step 1.2: Create a temporary to store the element in the destination
1885       // Reduce list.
1886       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1887       DestElementAddr =
1888           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1889       ShuffleInElement = true;
1890       UpdateDestListPtr = true;
1891       break;
1892     }
1893     case ThreadCopy: {
1894       // Step 1.1: Get the address for the src element in the Reduce list.
1895       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1896       SrcElementAddr = CGF.EmitLoadOfPointer(
1897           SrcElementPtrAddr,
1898           C.getPointerType(Private->getType())->castAs<PointerType>());
1899 
1900       // Step 1.2: Get the address for dest element.  The destination
1901       // element has already been created on the thread's stack.
1902       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1903       DestElementAddr = CGF.EmitLoadOfPointer(
1904           DestElementPtrAddr,
1905           C.getPointerType(Private->getType())->castAs<PointerType>());
1906       break;
1907     }
1908     case ThreadToScratchpad: {
1909       // Step 1.1: Get the address for the src element in the Reduce list.
1910       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1911       SrcElementAddr = CGF.EmitLoadOfPointer(
1912           SrcElementPtrAddr,
1913           C.getPointerType(Private->getType())->castAs<PointerType>());
1914 
1915       // Step 1.2: Get the address for dest element:
1916       // address = base + index * ElementSizeInChars.
1917       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
1918       llvm::Value *CurrentOffset =
1919           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
1920       llvm::Value *ScratchPadElemAbsolutePtrVal =
1921           Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
1922       ScratchPadElemAbsolutePtrVal =
1923           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1924       DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1925                                 C.getTypeAlignInChars(Private->getType()));
1926       IncrScratchpadDest = true;
1927       break;
1928     }
1929     case ScratchpadToThread: {
1930       // Step 1.1: Get the address for the src element in the scratchpad.
1931       // address = base + index * ElementSizeInChars.
1932       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
1933       llvm::Value *CurrentOffset =
1934           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
1935       llvm::Value *ScratchPadElemAbsolutePtrVal =
1936           Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
1937       ScratchPadElemAbsolutePtrVal =
1938           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1939       SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1940                                C.getTypeAlignInChars(Private->getType()));
1941       IncrScratchpadSrc = true;
1942 
1943       // Step 1.2: Create a temporary to store the element in the destination
1944       // Reduce list.
1945       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1946       DestElementAddr =
1947           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1948       UpdateDestListPtr = true;
1949       break;
1950     }
1951     }
1952 
1953     // Regardless of src and dest of copy, we emit the load of src
1954     // element as this is required in all directions
1955     SrcElementAddr = Bld.CreateElementBitCast(
1956         SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
1957     DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
1958                                                SrcElementAddr.getElementType());
1959 
1960     // Now that all active lanes have read the element in the
1961     // Reduce list, shuffle over the value from the remote lane.
1962     if (ShuffleInElement) {
1963       shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
1964                       RemoteLaneOffset, Private->getExprLoc());
1965     } else {
1966       switch (CGF.getEvaluationKind(Private->getType())) {
1967       case TEK_Scalar: {
1968         llvm::Value *Elem = CGF.EmitLoadOfScalar(
1969             SrcElementAddr, /*Volatile=*/false, Private->getType(),
1970             Private->getExprLoc(), LValueBaseInfo(AlignmentSource::Type),
1971             TBAAAccessInfo());
1972         // Store the source element value to the dest element address.
1973         CGF.EmitStoreOfScalar(
1974             Elem, DestElementAddr, /*Volatile=*/false, Private->getType(),
1975             LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
1976         break;
1977       }
1978       case TEK_Complex: {
1979         CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
1980             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
1981             Private->getExprLoc());
1982         CGF.EmitStoreOfComplex(
1983             Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
1984             /*isInit=*/false);
1985         break;
1986       }
1987       case TEK_Aggregate:
1988         CGF.EmitAggregateCopy(
1989             CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
1990             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
1991             Private->getType(), AggValueSlot::DoesNotOverlap);
1992         break;
1993       }
1994     }
1995 
1996     // Step 3.1: Modify reference in dest Reduce list as needed.
1997     // Modifying the reference in Reduce list to point to the newly
1998     // created element.  The element is live in the current function
1999     // scope and that of functions it invokes (i.e., reduce_function).
2000     // RemoteReduceData[i] = (void*)&RemoteElem
2001     if (UpdateDestListPtr) {
2002       CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2003                                 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2004                             DestElementPtrAddr, /*Volatile=*/false,
2005                             C.VoidPtrTy);
2006     }
2007 
2008     // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2009     // address of the next element in scratchpad memory, unless we're currently
2010     // processing the last one.  Memory alignment is also taken care of here.
2011     if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2012       llvm::Value *ScratchpadBasePtr =
2013           IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
2014       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2015       ScratchpadBasePtr = Bld.CreateNUWAdd(
2016           ScratchpadBasePtr,
2017           Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
2018 
2019       // Take care of global memory alignment for performance
2020       ScratchpadBasePtr = Bld.CreateNUWSub(
2021           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2022       ScratchpadBasePtr = Bld.CreateUDiv(
2023           ScratchpadBasePtr,
2024           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2025       ScratchpadBasePtr = Bld.CreateNUWAdd(
2026           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2027       ScratchpadBasePtr = Bld.CreateNUWMul(
2028           ScratchpadBasePtr,
2029           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2030 
2031       if (IncrScratchpadDest)
2032         DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2033       else /* IncrScratchpadSrc = true */
2034         SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2035     }
2036 
2037     ++Idx;
2038   }
2039 }
2040 
2041 /// This function emits a helper that gathers Reduce lists from the first
2042 /// lane of every active warp to lanes in the first warp.
2043 ///
2044 /// void inter_warp_copy_func(void* reduce_data, num_warps)
2045 ///   shared smem[warp_size];
2046 ///   For all data entries D in reduce_data:
2047 ///     sync
2048 ///     If (I am the first lane in each warp)
2049 ///       Copy my local D to smem[warp_id]
2050 ///     sync
2051 ///     if (I am the first warp)
2052 ///       Copy smem[thread_id] to my local D
2053 static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2054                                               ArrayRef<const Expr *> Privates,
2055                                               QualType ReductionArrayTy,
2056                                               SourceLocation Loc) {
2057   ASTContext &C = CGM.getContext();
2058   llvm::Module &M = CGM.getModule();
2059 
2060   // ReduceList: thread local Reduce list.
2061   // At the stage of the computation when this function is called, partially
2062   // aggregated values reside in the first lane of every active warp.
2063   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2064                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2065   // NumWarps: number of warps active in the parallel region.  This could
2066   // be smaller than 32 (max warps in a CTA) for partial block reduction.
2067   ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2068                                 C.getIntTypeForBitwidth(32, /* Signed */ true),
2069                                 ImplicitParamDecl::Other);
2070   FunctionArgList Args;
2071   Args.push_back(&ReduceListArg);
2072   Args.push_back(&NumWarpsArg);
2073 
2074   const CGFunctionInfo &CGFI =
2075       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2076   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2077                                     llvm::GlobalValue::InternalLinkage,
2078                                     "_omp_reduction_inter_warp_copy_func", &M);
2079   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2080   Fn->setDoesNotRecurse();
2081   CodeGenFunction CGF(CGM);
2082   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2083 
2084   CGBuilderTy &Bld = CGF.Builder;
2085 
2086   // This array is used as a medium to transfer, one reduce element at a time,
2087   // the data from the first lane of every warp to lanes in the first warp
2088   // in order to perform the final step of a reduction in a parallel region
2089   // (reduction across warps).  The array is placed in NVPTX __shared__ memory
2090   // for reduced latency, as well as to have a distinct copy for concurrently
2091   // executing target regions.  The array is declared with common linkage so
2092   // as to be shared across compilation units.
2093   StringRef TransferMediumName =
2094       "__openmp_nvptx_data_transfer_temporary_storage";
2095   llvm::GlobalVariable *TransferMedium =
2096       M.getGlobalVariable(TransferMediumName);
2097   unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
2098   if (!TransferMedium) {
2099     auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
2100     unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2101     TransferMedium = new llvm::GlobalVariable(
2102         M, Ty, /*isConstant=*/false, llvm::GlobalVariable::WeakAnyLinkage,
2103         llvm::UndefValue::get(Ty), TransferMediumName,
2104         /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2105         SharedAddressSpace);
2106     CGM.addCompilerUsedGlobal(TransferMedium);
2107   }
2108 
2109   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2110   // Get the CUDA thread id of the current OpenMP thread on the GPU.
2111   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
2112   // nvptx_lane_id = nvptx_id % warpsize
2113   llvm::Value *LaneID = getNVPTXLaneID(CGF);
2114   // nvptx_warp_id = nvptx_id / warpsize
2115   llvm::Value *WarpID = getNVPTXWarpID(CGF);
2116 
2117   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2118   Address LocalReduceList(
2119       Bld.CreatePointerBitCastOrAddrSpaceCast(
2120           CGF.EmitLoadOfScalar(
2121               AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc,
2122               LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo()),
2123           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2124       CGF.getPointerAlign());
2125 
2126   unsigned Idx = 0;
2127   for (const Expr *Private : Privates) {
2128     //
2129     // Warp master copies reduce element to transfer medium in __shared__
2130     // memory.
2131     //
2132     unsigned RealTySize =
2133         C.getTypeSizeInChars(Private->getType())
2134             .alignTo(C.getTypeAlignInChars(Private->getType()))
2135             .getQuantity();
2136     for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
2137       unsigned NumIters = RealTySize / TySize;
2138       if (NumIters == 0)
2139         continue;
2140       QualType CType = C.getIntTypeForBitwidth(
2141           C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
2142       llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
2143       CharUnits Align = CharUnits::fromQuantity(TySize);
2144       llvm::Value *Cnt = nullptr;
2145       Address CntAddr = Address::invalid();
2146       llvm::BasicBlock *PrecondBB = nullptr;
2147       llvm::BasicBlock *ExitBB = nullptr;
2148       if (NumIters > 1) {
2149         CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
2150         CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
2151                               /*Volatile=*/false, C.IntTy);
2152         PrecondBB = CGF.createBasicBlock("precond");
2153         ExitBB = CGF.createBasicBlock("exit");
2154         llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
2155         // There is no need to emit line number for unconditional branch.
2156         (void)ApplyDebugLocation::CreateEmpty(CGF);
2157         CGF.EmitBlock(PrecondBB);
2158         Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
2159         llvm::Value *Cmp =
2160             Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
2161         Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
2162         CGF.EmitBlock(BodyBB);
2163       }
2164       // kmpc_barrier.
2165       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2166                                              /*EmitChecks=*/false,
2167                                              /*ForceSimpleCall=*/true);
2168       llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2169       llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2170       llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2171 
2172       // if (lane_id == 0)
2173       llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
2174       Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2175       CGF.EmitBlock(ThenBB);
2176 
2177       // Reduce element = LocalReduceList[i]
2178       Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2179       llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2180           ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2181       // elemptr = ((CopyType*)(elemptrptr)) + I
2182       Address ElemPtr = Address(ElemPtrPtr, Align);
2183       ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
2184       if (NumIters > 1) {
2185         ElemPtr = Address(Bld.CreateGEP(ElemPtr.getElementType(),
2186                                         ElemPtr.getPointer(), Cnt),
2187                           ElemPtr.getAlignment());
2188       }
2189 
2190       // Get pointer to location in transfer medium.
2191       // MediumPtr = &medium[warp_id]
2192       llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2193           TransferMedium->getValueType(), TransferMedium,
2194           {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2195       Address MediumPtr(MediumPtrVal, Align);
2196       // Casting to actual data type.
2197       // MediumPtr = (CopyType*)MediumPtrAddr;
2198       MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
2199 
2200       // elem = *elemptr
2201       //*MediumPtr = elem
2202       llvm::Value *Elem = CGF.EmitLoadOfScalar(
2203           ElemPtr, /*Volatile=*/false, CType, Loc,
2204           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2205       // Store the source element value to the dest element address.
2206       CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType,
2207                             LValueBaseInfo(AlignmentSource::Type),
2208                             TBAAAccessInfo());
2209 
2210       Bld.CreateBr(MergeBB);
2211 
2212       CGF.EmitBlock(ElseBB);
2213       Bld.CreateBr(MergeBB);
2214 
2215       CGF.EmitBlock(MergeBB);
2216 
2217       // kmpc_barrier.
2218       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2219                                              /*EmitChecks=*/false,
2220                                              /*ForceSimpleCall=*/true);
2221 
2222       //
2223       // Warp 0 copies reduce element from transfer medium.
2224       //
2225       llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2226       llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2227       llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2228 
2229       Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2230       llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2231           AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
2232 
2233       // Up to 32 threads in warp 0 are active.
2234       llvm::Value *IsActiveThread =
2235           Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2236       Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2237 
2238       CGF.EmitBlock(W0ThenBB);
2239 
2240       // SrcMediumPtr = &medium[tid]
2241       llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2242           TransferMedium->getValueType(), TransferMedium,
2243           {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2244       Address SrcMediumPtr(SrcMediumPtrVal, Align);
2245       // SrcMediumVal = *SrcMediumPtr;
2246       SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
2247 
2248       // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
2249       Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2250       llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2251           TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
2252       Address TargetElemPtr = Address(TargetElemPtrVal, Align);
2253       TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
2254       if (NumIters > 1) {
2255         TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getElementType(),
2256                                               TargetElemPtr.getPointer(), Cnt),
2257                                 TargetElemPtr.getAlignment());
2258       }
2259 
2260       // *TargetElemPtr = SrcMediumVal;
2261       llvm::Value *SrcMediumValue =
2262           CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
2263       CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2264                             CType);
2265       Bld.CreateBr(W0MergeBB);
2266 
2267       CGF.EmitBlock(W0ElseBB);
2268       Bld.CreateBr(W0MergeBB);
2269 
2270       CGF.EmitBlock(W0MergeBB);
2271 
2272       if (NumIters > 1) {
2273         Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
2274         CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
2275         CGF.EmitBranch(PrecondBB);
2276         (void)ApplyDebugLocation::CreateEmpty(CGF);
2277         CGF.EmitBlock(ExitBB);
2278       }
2279       RealTySize %= TySize;
2280     }
2281     ++Idx;
2282   }
2283 
2284   CGF.FinishFunction();
2285   return Fn;
2286 }
2287 
2288 /// Emit a helper that reduces data across two OpenMP threads (lanes)
2289 /// in the same warp.  It uses shuffle instructions to copy over data from
2290 /// a remote lane's stack.  The reduction algorithm performed is specified
2291 /// by the fourth parameter.
2292 ///
2293 /// Algorithm Versions.
2294 /// Full Warp Reduce (argument value 0):
2295 ///   This algorithm assumes that all 32 lanes are active and gathers
2296 ///   data from these 32 lanes, producing a single resultant value.
2297 /// Contiguous Partial Warp Reduce (argument value 1):
2298 ///   This algorithm assumes that only a *contiguous* subset of lanes
2299 ///   are active.  This happens for the last warp in a parallel region
2300 ///   when the user specified num_threads is not an integer multiple of
2301 ///   32.  This contiguous subset always starts with the zeroth lane.
2302 /// Partial Warp Reduce (argument value 2):
2303 ///   This algorithm gathers data from any number of lanes at any position.
2304 /// All reduced values are stored in the lowest possible lane.  The set
2305 /// of problems every algorithm addresses is a super set of those
2306 /// addressable by algorithms with a lower version number.  Overhead
2307 /// increases as algorithm version increases.
2308 ///
2309 /// Terminology
2310 /// Reduce element:
2311 ///   Reduce element refers to the individual data field with primitive
2312 ///   data types to be combined and reduced across threads.
2313 /// Reduce list:
2314 ///   Reduce list refers to a collection of local, thread-private
2315 ///   reduce elements.
2316 /// Remote Reduce list:
2317 ///   Remote Reduce list refers to a collection of remote (relative to
2318 ///   the current thread) reduce elements.
2319 ///
2320 /// We distinguish between three states of threads that are important to
2321 /// the implementation of this function.
2322 /// Alive threads:
2323 ///   Threads in a warp executing the SIMT instruction, as distinguished from
2324 ///   threads that are inactive due to divergent control flow.
2325 /// Active threads:
2326 ///   The minimal set of threads that has to be alive upon entry to this
2327 ///   function.  The computation is correct iff active threads are alive.
2328 ///   Some threads are alive but they are not active because they do not
2329 ///   contribute to the computation in any useful manner.  Turning them off
2330 ///   may introduce control flow overheads without any tangible benefits.
2331 /// Effective threads:
2332 ///   In order to comply with the argument requirements of the shuffle
2333 ///   function, we must keep all lanes holding data alive.  But at most
2334 ///   half of them perform value aggregation; we refer to this half of
2335 ///   threads as effective. The other half is simply handing off their
2336 ///   data.
2337 ///
2338 /// Procedure
2339 /// Value shuffle:
2340 ///   In this step active threads transfer data from higher lane positions
2341 ///   in the warp to lower lane positions, creating Remote Reduce list.
2342 /// Value aggregation:
2343 ///   In this step, effective threads combine their thread local Reduce list
2344 ///   with Remote Reduce list and store the result in the thread local
2345 ///   Reduce list.
2346 /// Value copy:
2347 ///   In this step, we deal with the assumption made by algorithm 2
2348 ///   (i.e. contiguity assumption).  When we have an odd number of lanes
2349 ///   active, say 2k+1, only k threads will be effective and therefore k
2350 ///   new values will be produced.  However, the Reduce list owned by the
2351 ///   (2k+1)th thread is ignored in the value aggregation.  Therefore
2352 ///   we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2353 ///   that the contiguity assumption still holds.
2354 static llvm::Function *emitShuffleAndReduceFunction(
2355     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2356     QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
2357   ASTContext &C = CGM.getContext();
2358 
2359   // Thread local Reduce list used to host the values of data to be reduced.
2360   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2361                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2362   // Current lane id; could be logical.
2363   ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2364                               ImplicitParamDecl::Other);
2365   // Offset of the remote source lane relative to the current lane.
2366   ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2367                                         C.ShortTy, ImplicitParamDecl::Other);
2368   // Algorithm version.  This is expected to be known at compile time.
2369   ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2370                                C.ShortTy, ImplicitParamDecl::Other);
2371   FunctionArgList Args;
2372   Args.push_back(&ReduceListArg);
2373   Args.push_back(&LaneIDArg);
2374   Args.push_back(&RemoteLaneOffsetArg);
2375   Args.push_back(&AlgoVerArg);
2376 
2377   const CGFunctionInfo &CGFI =
2378       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2379   auto *Fn = llvm::Function::Create(
2380       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2381       "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
2382   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2383   Fn->setDoesNotRecurse();
2384 
2385   CodeGenFunction CGF(CGM);
2386   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2387 
2388   CGBuilderTy &Bld = CGF.Builder;
2389 
2390   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2391   Address LocalReduceList(
2392       Bld.CreatePointerBitCastOrAddrSpaceCast(
2393           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2394                                C.VoidPtrTy, SourceLocation()),
2395           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2396       CGF.getPointerAlign());
2397 
2398   Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2399   llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2400       AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2401 
2402   Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2403   llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2404       AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2405 
2406   Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2407   llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2408       AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2409 
2410   // Create a local thread-private variable to host the Reduce list
2411   // from a remote lane.
2412   Address RemoteReduceList =
2413       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2414 
2415   // This loop iterates through the list of reduce elements and copies,
2416   // element by element, from a remote lane in the warp to RemoteReduceList,
2417   // hosted on the thread's stack.
2418   emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2419                         LocalReduceList, RemoteReduceList,
2420                         {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2421                          /*ScratchpadIndex=*/nullptr,
2422                          /*ScratchpadWidth=*/nullptr});
2423 
2424   // The actions to be performed on the Remote Reduce list is dependent
2425   // on the algorithm version.
2426   //
2427   //  if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2428   //  LaneId % 2 == 0 && Offset > 0):
2429   //    do the reduction value aggregation
2430   //
2431   //  The thread local variable Reduce list is mutated in place to host the
2432   //  reduced data, which is the aggregated value produced from local and
2433   //  remote lanes.
2434   //
2435   //  Note that AlgoVer is expected to be a constant integer known at compile
2436   //  time.
2437   //  When AlgoVer==0, the first conjunction evaluates to true, making
2438   //    the entire predicate true during compile time.
2439   //  When AlgoVer==1, the second conjunction has only the second part to be
2440   //    evaluated during runtime.  Other conjunctions evaluates to false
2441   //    during compile time.
2442   //  When AlgoVer==2, the third conjunction has only the second part to be
2443   //    evaluated during runtime.  Other conjunctions evaluates to false
2444   //    during compile time.
2445   llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
2446 
2447   llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2448   llvm::Value *CondAlgo1 = Bld.CreateAnd(
2449       Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2450 
2451   llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2452   llvm::Value *CondAlgo2 = Bld.CreateAnd(
2453       Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
2454   CondAlgo2 = Bld.CreateAnd(
2455       CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2456 
2457   llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
2458   CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2459 
2460   llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2461   llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2462   llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2463   Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2464 
2465   CGF.EmitBlock(ThenBB);
2466   // reduce_function(LocalReduceList, RemoteReduceList)
2467   llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2468       LocalReduceList.getPointer(), CGF.VoidPtrTy);
2469   llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2470       RemoteReduceList.getPointer(), CGF.VoidPtrTy);
2471   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2472       CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
2473   Bld.CreateBr(MergeBB);
2474 
2475   CGF.EmitBlock(ElseBB);
2476   Bld.CreateBr(MergeBB);
2477 
2478   CGF.EmitBlock(MergeBB);
2479 
2480   // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2481   // Reduce list.
2482   Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2483   llvm::Value *CondCopy = Bld.CreateAnd(
2484       Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2485 
2486   llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2487   llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2488   llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2489   Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2490 
2491   CGF.EmitBlock(CpyThenBB);
2492   emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2493                         RemoteReduceList, LocalReduceList);
2494   Bld.CreateBr(CpyMergeBB);
2495 
2496   CGF.EmitBlock(CpyElseBB);
2497   Bld.CreateBr(CpyMergeBB);
2498 
2499   CGF.EmitBlock(CpyMergeBB);
2500 
2501   CGF.FinishFunction();
2502   return Fn;
2503 }
2504 
2505 /// This function emits a helper that copies all the reduction variables from
2506 /// the team into the provided global buffer for the reduction variables.
2507 ///
2508 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2509 ///   For all data entries D in reduce_data:
2510 ///     Copy local D to buffer.D[Idx]
2511 static llvm::Value *emitListToGlobalCopyFunction(
2512     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2513     QualType ReductionArrayTy, SourceLocation Loc,
2514     const RecordDecl *TeamReductionRec,
2515     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2516         &VarFieldMap) {
2517   ASTContext &C = CGM.getContext();
2518 
2519   // Buffer: global reduction buffer.
2520   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2521                               C.VoidPtrTy, ImplicitParamDecl::Other);
2522   // Idx: index of the buffer.
2523   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2524                            ImplicitParamDecl::Other);
2525   // ReduceList: thread local Reduce list.
2526   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2527                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2528   FunctionArgList Args;
2529   Args.push_back(&BufferArg);
2530   Args.push_back(&IdxArg);
2531   Args.push_back(&ReduceListArg);
2532 
2533   const CGFunctionInfo &CGFI =
2534       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2535   auto *Fn = llvm::Function::Create(
2536       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2537       "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
2538   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2539   Fn->setDoesNotRecurse();
2540   CodeGenFunction CGF(CGM);
2541   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2542 
2543   CGBuilderTy &Bld = CGF.Builder;
2544 
2545   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2546   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2547   Address LocalReduceList(
2548       Bld.CreatePointerBitCastOrAddrSpaceCast(
2549           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2550                                C.VoidPtrTy, Loc),
2551           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2552       CGF.getPointerAlign());
2553   QualType StaticTy = C.getRecordType(TeamReductionRec);
2554   llvm::Type *LLVMReductionsBufferTy =
2555       CGM.getTypes().ConvertTypeForMem(StaticTy);
2556   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2557       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2558       LLVMReductionsBufferTy->getPointerTo());
2559   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2560                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2561                                               /*Volatile=*/false, C.IntTy,
2562                                               Loc)};
2563   unsigned Idx = 0;
2564   for (const Expr *Private : Privates) {
2565     // Reduce element = LocalReduceList[i]
2566     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2567     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2568         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2569     // elemptr = ((CopyType*)(elemptrptr)) + I
2570     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2571         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
2572     Address ElemPtr =
2573         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2574     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
2575     // Global = Buffer.VD[Idx];
2576     const FieldDecl *FD = VarFieldMap.lookup(VD);
2577     LValue GlobLVal = CGF.EmitLValueForField(
2578         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2579     Address GlobAddr = GlobLVal.getAddress(CGF);
2580     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2581         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2582     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
2583     switch (CGF.getEvaluationKind(Private->getType())) {
2584     case TEK_Scalar: {
2585       llvm::Value *V = CGF.EmitLoadOfScalar(
2586           ElemPtr, /*Volatile=*/false, Private->getType(), Loc,
2587           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2588       CGF.EmitStoreOfScalar(V, GlobLVal);
2589       break;
2590     }
2591     case TEK_Complex: {
2592       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
2593           CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
2594       CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
2595       break;
2596     }
2597     case TEK_Aggregate:
2598       CGF.EmitAggregateCopy(GlobLVal,
2599                             CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2600                             Private->getType(), AggValueSlot::DoesNotOverlap);
2601       break;
2602     }
2603     ++Idx;
2604   }
2605 
2606   CGF.FinishFunction();
2607   return Fn;
2608 }
2609 
2610 /// This function emits a helper that reduces all the reduction variables from
2611 /// the team into the provided global buffer for the reduction variables.
2612 ///
2613 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
2614 ///  void *GlobPtrs[];
2615 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
2616 ///  ...
2617 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
2618 ///  reduce_function(GlobPtrs, reduce_data);
2619 static llvm::Value *emitListToGlobalReduceFunction(
2620     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2621     QualType ReductionArrayTy, SourceLocation Loc,
2622     const RecordDecl *TeamReductionRec,
2623     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2624         &VarFieldMap,
2625     llvm::Function *ReduceFn) {
2626   ASTContext &C = CGM.getContext();
2627 
2628   // Buffer: global reduction buffer.
2629   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2630                               C.VoidPtrTy, ImplicitParamDecl::Other);
2631   // Idx: index of the buffer.
2632   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2633                            ImplicitParamDecl::Other);
2634   // ReduceList: thread local Reduce list.
2635   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2636                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2637   FunctionArgList Args;
2638   Args.push_back(&BufferArg);
2639   Args.push_back(&IdxArg);
2640   Args.push_back(&ReduceListArg);
2641 
2642   const CGFunctionInfo &CGFI =
2643       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2644   auto *Fn = llvm::Function::Create(
2645       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2646       "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
2647   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2648   Fn->setDoesNotRecurse();
2649   CodeGenFunction CGF(CGM);
2650   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2651 
2652   CGBuilderTy &Bld = CGF.Builder;
2653 
2654   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2655   QualType StaticTy = C.getRecordType(TeamReductionRec);
2656   llvm::Type *LLVMReductionsBufferTy =
2657       CGM.getTypes().ConvertTypeForMem(StaticTy);
2658   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2659       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2660       LLVMReductionsBufferTy->getPointerTo());
2661 
2662   // 1. Build a list of reduction variables.
2663   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2664   Address ReductionList =
2665       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2666   auto IPriv = Privates.begin();
2667   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2668                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2669                                               /*Volatile=*/false, C.IntTy,
2670                                               Loc)};
2671   unsigned Idx = 0;
2672   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
2673     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2674     // Global = Buffer.VD[Idx];
2675     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
2676     const FieldDecl *FD = VarFieldMap.lookup(VD);
2677     LValue GlobLVal = CGF.EmitLValueForField(
2678         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2679     Address GlobAddr = GlobLVal.getAddress(CGF);
2680     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2681         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2682     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
2683     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
2684     if ((*IPriv)->getType()->isVariablyModifiedType()) {
2685       // Store array size.
2686       ++Idx;
2687       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2688       llvm::Value *Size = CGF.Builder.CreateIntCast(
2689           CGF.getVLASize(
2690                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2691               .NumElts,
2692           CGF.SizeTy, /*isSigned=*/false);
2693       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2694                               Elem);
2695     }
2696   }
2697 
2698   // Call reduce_function(GlobalReduceList, ReduceList)
2699   llvm::Value *GlobalReduceList =
2700       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
2701   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2702   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
2703       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
2704   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2705       CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
2706   CGF.FinishFunction();
2707   return Fn;
2708 }
2709 
2710 /// This function emits a helper that copies all the reduction variables from
2711 /// the team into the provided global buffer for the reduction variables.
2712 ///
2713 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2714 ///   For all data entries D in reduce_data:
2715 ///     Copy buffer.D[Idx] to local D;
2716 static llvm::Value *emitGlobalToListCopyFunction(
2717     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2718     QualType ReductionArrayTy, SourceLocation Loc,
2719     const RecordDecl *TeamReductionRec,
2720     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2721         &VarFieldMap) {
2722   ASTContext &C = CGM.getContext();
2723 
2724   // Buffer: global reduction buffer.
2725   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2726                               C.VoidPtrTy, ImplicitParamDecl::Other);
2727   // Idx: index of the buffer.
2728   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2729                            ImplicitParamDecl::Other);
2730   // ReduceList: thread local Reduce list.
2731   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2732                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2733   FunctionArgList Args;
2734   Args.push_back(&BufferArg);
2735   Args.push_back(&IdxArg);
2736   Args.push_back(&ReduceListArg);
2737 
2738   const CGFunctionInfo &CGFI =
2739       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2740   auto *Fn = llvm::Function::Create(
2741       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2742       "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
2743   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2744   Fn->setDoesNotRecurse();
2745   CodeGenFunction CGF(CGM);
2746   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2747 
2748   CGBuilderTy &Bld = CGF.Builder;
2749 
2750   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2751   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2752   Address LocalReduceList(
2753       Bld.CreatePointerBitCastOrAddrSpaceCast(
2754           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2755                                C.VoidPtrTy, Loc),
2756           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2757       CGF.getPointerAlign());
2758   QualType StaticTy = C.getRecordType(TeamReductionRec);
2759   llvm::Type *LLVMReductionsBufferTy =
2760       CGM.getTypes().ConvertTypeForMem(StaticTy);
2761   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2762       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2763       LLVMReductionsBufferTy->getPointerTo());
2764 
2765   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2766                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2767                                               /*Volatile=*/false, C.IntTy,
2768                                               Loc)};
2769   unsigned Idx = 0;
2770   for (const Expr *Private : Privates) {
2771     // Reduce element = LocalReduceList[i]
2772     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2773     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2774         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2775     // elemptr = ((CopyType*)(elemptrptr)) + I
2776     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2777         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
2778     Address ElemPtr =
2779         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2780     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
2781     // Global = Buffer.VD[Idx];
2782     const FieldDecl *FD = VarFieldMap.lookup(VD);
2783     LValue GlobLVal = CGF.EmitLValueForField(
2784         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2785     Address GlobAddr = GlobLVal.getAddress(CGF);
2786     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2787         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2788     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
2789     switch (CGF.getEvaluationKind(Private->getType())) {
2790     case TEK_Scalar: {
2791       llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
2792       CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType(),
2793                             LValueBaseInfo(AlignmentSource::Type),
2794                             TBAAAccessInfo());
2795       break;
2796     }
2797     case TEK_Complex: {
2798       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
2799       CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2800                              /*isInit=*/false);
2801       break;
2802     }
2803     case TEK_Aggregate:
2804       CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2805                             GlobLVal, Private->getType(),
2806                             AggValueSlot::DoesNotOverlap);
2807       break;
2808     }
2809     ++Idx;
2810   }
2811 
2812   CGF.FinishFunction();
2813   return Fn;
2814 }
2815 
2816 /// This function emits a helper that reduces all the reduction variables from
2817 /// the team into the provided global buffer for the reduction variables.
2818 ///
2819 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
2820 ///  void *GlobPtrs[];
2821 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
2822 ///  ...
2823 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
2824 ///  reduce_function(reduce_data, GlobPtrs);
2825 static llvm::Value *emitGlobalToListReduceFunction(
2826     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2827     QualType ReductionArrayTy, SourceLocation Loc,
2828     const RecordDecl *TeamReductionRec,
2829     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2830         &VarFieldMap,
2831     llvm::Function *ReduceFn) {
2832   ASTContext &C = CGM.getContext();
2833 
2834   // Buffer: global reduction buffer.
2835   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2836                               C.VoidPtrTy, ImplicitParamDecl::Other);
2837   // Idx: index of the buffer.
2838   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2839                            ImplicitParamDecl::Other);
2840   // ReduceList: thread local Reduce list.
2841   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2842                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2843   FunctionArgList Args;
2844   Args.push_back(&BufferArg);
2845   Args.push_back(&IdxArg);
2846   Args.push_back(&ReduceListArg);
2847 
2848   const CGFunctionInfo &CGFI =
2849       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2850   auto *Fn = llvm::Function::Create(
2851       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2852       "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
2853   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2854   Fn->setDoesNotRecurse();
2855   CodeGenFunction CGF(CGM);
2856   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2857 
2858   CGBuilderTy &Bld = CGF.Builder;
2859 
2860   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2861   QualType StaticTy = C.getRecordType(TeamReductionRec);
2862   llvm::Type *LLVMReductionsBufferTy =
2863       CGM.getTypes().ConvertTypeForMem(StaticTy);
2864   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2865       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2866       LLVMReductionsBufferTy->getPointerTo());
2867 
2868   // 1. Build a list of reduction variables.
2869   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2870   Address ReductionList =
2871       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2872   auto IPriv = Privates.begin();
2873   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2874                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2875                                               /*Volatile=*/false, C.IntTy,
2876                                               Loc)};
2877   unsigned Idx = 0;
2878   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
2879     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2880     // Global = Buffer.VD[Idx];
2881     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
2882     const FieldDecl *FD = VarFieldMap.lookup(VD);
2883     LValue GlobLVal = CGF.EmitLValueForField(
2884         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2885     Address GlobAddr = GlobLVal.getAddress(CGF);
2886     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2887         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2888     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
2889     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
2890     if ((*IPriv)->getType()->isVariablyModifiedType()) {
2891       // Store array size.
2892       ++Idx;
2893       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2894       llvm::Value *Size = CGF.Builder.CreateIntCast(
2895           CGF.getVLASize(
2896                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2897               .NumElts,
2898           CGF.SizeTy, /*isSigned=*/false);
2899       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2900                               Elem);
2901     }
2902   }
2903 
2904   // Call reduce_function(ReduceList, GlobalReduceList)
2905   llvm::Value *GlobalReduceList =
2906       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
2907   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2908   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
2909       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
2910   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2911       CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
2912   CGF.FinishFunction();
2913   return Fn;
2914 }
2915 
2916 ///
2917 /// Design of OpenMP reductions on the GPU
2918 ///
2919 /// Consider a typical OpenMP program with one or more reduction
2920 /// clauses:
2921 ///
2922 /// float foo;
2923 /// double bar;
2924 /// #pragma omp target teams distribute parallel for \
2925 ///             reduction(+:foo) reduction(*:bar)
2926 /// for (int i = 0; i < N; i++) {
2927 ///   foo += A[i]; bar *= B[i];
2928 /// }
2929 ///
2930 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
2931 /// all teams.  In our OpenMP implementation on the NVPTX device an
2932 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2933 /// within a team are mapped to CUDA threads within a threadblock.
2934 /// Our goal is to efficiently aggregate values across all OpenMP
2935 /// threads such that:
2936 ///
2937 ///   - the compiler and runtime are logically concise, and
2938 ///   - the reduction is performed efficiently in a hierarchical
2939 ///     manner as follows: within OpenMP threads in the same warp,
2940 ///     across warps in a threadblock, and finally across teams on
2941 ///     the NVPTX device.
2942 ///
2943 /// Introduction to Decoupling
2944 ///
2945 /// We would like to decouple the compiler and the runtime so that the
2946 /// latter is ignorant of the reduction variables (number, data types)
2947 /// and the reduction operators.  This allows a simpler interface
2948 /// and implementation while still attaining good performance.
2949 ///
2950 /// Pseudocode for the aforementioned OpenMP program generated by the
2951 /// compiler is as follows:
2952 ///
2953 /// 1. Create private copies of reduction variables on each OpenMP
2954 ///    thread: 'foo_private', 'bar_private'
2955 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2956 ///    to it and writes the result in 'foo_private' and 'bar_private'
2957 ///    respectively.
2958 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
2959 ///    and store the result on the team master:
2960 ///
2961 ///     __kmpc_nvptx_parallel_reduce_nowait_v2(...,
2962 ///        reduceData, shuffleReduceFn, interWarpCpyFn)
2963 ///
2964 ///     where:
2965 ///       struct ReduceData {
2966 ///         double *foo;
2967 ///         double *bar;
2968 ///       } reduceData
2969 ///       reduceData.foo = &foo_private
2970 ///       reduceData.bar = &bar_private
2971 ///
2972 ///     'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2973 ///     auxiliary functions generated by the compiler that operate on
2974 ///     variables of type 'ReduceData'.  They aid the runtime perform
2975 ///     algorithmic steps in a data agnostic manner.
2976 ///
2977 ///     'shuffleReduceFn' is a pointer to a function that reduces data
2978 ///     of type 'ReduceData' across two OpenMP threads (lanes) in the
2979 ///     same warp.  It takes the following arguments as input:
2980 ///
2981 ///     a. variable of type 'ReduceData' on the calling lane,
2982 ///     b. its lane_id,
2983 ///     c. an offset relative to the current lane_id to generate a
2984 ///        remote_lane_id.  The remote lane contains the second
2985 ///        variable of type 'ReduceData' that is to be reduced.
2986 ///     d. an algorithm version parameter determining which reduction
2987 ///        algorithm to use.
2988 ///
2989 ///     'shuffleReduceFn' retrieves data from the remote lane using
2990 ///     efficient GPU shuffle intrinsics and reduces, using the
2991 ///     algorithm specified by the 4th parameter, the two operands
2992 ///     element-wise.  The result is written to the first operand.
2993 ///
2994 ///     Different reduction algorithms are implemented in different
2995 ///     runtime functions, all calling 'shuffleReduceFn' to perform
2996 ///     the essential reduction step.  Therefore, based on the 4th
2997 ///     parameter, this function behaves slightly differently to
2998 ///     cooperate with the runtime to ensure correctness under
2999 ///     different circumstances.
3000 ///
3001 ///     'InterWarpCpyFn' is a pointer to a function that transfers
3002 ///     reduced variables across warps.  It tunnels, through CUDA
3003 ///     shared memory, the thread-private data of type 'ReduceData'
3004 ///     from lane 0 of each warp to a lane in the first warp.
3005 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3006 ///    The last team writes the global reduced value to memory.
3007 ///
3008 ///     ret = __kmpc_nvptx_teams_reduce_nowait(...,
3009 ///             reduceData, shuffleReduceFn, interWarpCpyFn,
3010 ///             scratchpadCopyFn, loadAndReduceFn)
3011 ///
3012 ///     'scratchpadCopyFn' is a helper that stores reduced
3013 ///     data from the team master to a scratchpad array in
3014 ///     global memory.
3015 ///
3016 ///     'loadAndReduceFn' is a helper that loads data from
3017 ///     the scratchpad array and reduces it with the input
3018 ///     operand.
3019 ///
3020 ///     These compiler generated functions hide address
3021 ///     calculation and alignment information from the runtime.
3022 /// 5. if ret == 1:
3023 ///     The team master of the last team stores the reduced
3024 ///     result to the globals in memory.
3025 ///     foo += reduceData.foo; bar *= reduceData.bar
3026 ///
3027 ///
3028 /// Warp Reduction Algorithms
3029 ///
3030 /// On the warp level, we have three algorithms implemented in the
3031 /// OpenMP runtime depending on the number of active lanes:
3032 ///
3033 /// Full Warp Reduction
3034 ///
3035 /// The reduce algorithm within a warp where all lanes are active
3036 /// is implemented in the runtime as follows:
3037 ///
3038 /// full_warp_reduce(void *reduce_data,
3039 ///                  kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3040 ///   for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3041 ///     ShuffleReduceFn(reduce_data, 0, offset, 0);
3042 /// }
3043 ///
3044 /// The algorithm completes in log(2, WARPSIZE) steps.
3045 ///
3046 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3047 /// not used therefore we save instructions by not retrieving lane_id
3048 /// from the corresponding special registers.  The 4th parameter, which
3049 /// represents the version of the algorithm being used, is set to 0 to
3050 /// signify full warp reduction.
3051 ///
3052 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3053 ///
3054 /// #reduce_elem refers to an element in the local lane's data structure
3055 /// #remote_elem is retrieved from a remote lane
3056 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3057 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3058 ///
3059 /// Contiguous Partial Warp Reduction
3060 ///
3061 /// This reduce algorithm is used within a warp where only the first
3062 /// 'n' (n <= WARPSIZE) lanes are active.  It is typically used when the
3063 /// number of OpenMP threads in a parallel region is not a multiple of
3064 /// WARPSIZE.  The algorithm is implemented in the runtime as follows:
3065 ///
3066 /// void
3067 /// contiguous_partial_reduce(void *reduce_data,
3068 ///                           kmp_ShuffleReductFctPtr ShuffleReduceFn,
3069 ///                           int size, int lane_id) {
3070 ///   int curr_size;
3071 ///   int offset;
3072 ///   curr_size = size;
3073 ///   mask = curr_size/2;
3074 ///   while (offset>0) {
3075 ///     ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3076 ///     curr_size = (curr_size+1)/2;
3077 ///     offset = curr_size/2;
3078 ///   }
3079 /// }
3080 ///
3081 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3082 ///
3083 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3084 /// if (lane_id < offset)
3085 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3086 /// else
3087 ///     reduce_elem = remote_elem
3088 ///
3089 /// This algorithm assumes that the data to be reduced are located in a
3090 /// contiguous subset of lanes starting from the first.  When there is
3091 /// an odd number of active lanes, the data in the last lane is not
3092 /// aggregated with any other lane's dat but is instead copied over.
3093 ///
3094 /// Dispersed Partial Warp Reduction
3095 ///
3096 /// This algorithm is used within a warp when any discontiguous subset of
3097 /// lanes are active.  It is used to implement the reduction operation
3098 /// across lanes in an OpenMP simd region or in a nested parallel region.
3099 ///
3100 /// void
3101 /// dispersed_partial_reduce(void *reduce_data,
3102 ///                          kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3103 ///   int size, remote_id;
3104 ///   int logical_lane_id = number_of_active_lanes_before_me() * 2;
3105 ///   do {
3106 ///       remote_id = next_active_lane_id_right_after_me();
3107 ///       # the above function returns 0 of no active lane
3108 ///       # is present right after the current lane.
3109 ///       size = number_of_active_lanes_in_this_warp();
3110 ///       logical_lane_id /= 2;
3111 ///       ShuffleReduceFn(reduce_data, logical_lane_id,
3112 ///                       remote_id-1-threadIdx.x, 2);
3113 ///   } while (logical_lane_id % 2 == 0 && size > 1);
3114 /// }
3115 ///
3116 /// There is no assumption made about the initial state of the reduction.
3117 /// Any number of lanes (>=1) could be active at any position.  The reduction
3118 /// result is returned in the first active lane.
3119 ///
3120 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3121 ///
3122 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3123 /// if (lane_id % 2 == 0 && offset > 0)
3124 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3125 /// else
3126 ///     reduce_elem = remote_elem
3127 ///
3128 ///
3129 /// Intra-Team Reduction
3130 ///
3131 /// This function, as implemented in the runtime call
3132 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
3133 /// threads in a team.  It first reduces within a warp using the
3134 /// aforementioned algorithms.  We then proceed to gather all such
3135 /// reduced values at the first warp.
3136 ///
3137 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
3138 /// data from each of the "warp master" (zeroth lane of each warp, where
3139 /// warp-reduced data is held) to the zeroth warp.  This step reduces (in
3140 /// a mathematical sense) the problem of reduction across warp masters in
3141 /// a block to the problem of warp reduction.
3142 ///
3143 ///
3144 /// Inter-Team Reduction
3145 ///
3146 /// Once a team has reduced its data to a single value, it is stored in
3147 /// a global scratchpad array.  Since each team has a distinct slot, this
3148 /// can be done without locking.
3149 ///
3150 /// The last team to write to the scratchpad array proceeds to reduce the
3151 /// scratchpad array.  One or more workers in the last team use the helper
3152 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3153 /// the k'th worker reduces every k'th element.
3154 ///
3155 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
3156 /// reduce across workers and compute a globally reduced value.
3157 ///
3158 void CGOpenMPRuntimeGPU::emitReduction(
3159     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3160     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3161     ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3162   if (!CGF.HaveInsertPoint())
3163     return;
3164 
3165   bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
3166 #ifndef NDEBUG
3167   bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
3168 #endif
3169 
3170   if (Options.SimpleReduction) {
3171     assert(!TeamsReduction && !ParallelReduction &&
3172            "Invalid reduction selection in emitReduction.");
3173     CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3174                                    ReductionOps, Options);
3175     return;
3176   }
3177 
3178   assert((TeamsReduction || ParallelReduction) &&
3179          "Invalid reduction selection in emitReduction.");
3180 
3181   // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3182   // RedList, shuffle_reduce_func, interwarp_copy_func);
3183   // or
3184   // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
3185   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3186   llvm::Value *ThreadId = getThreadID(CGF, Loc);
3187 
3188   llvm::Value *Res;
3189   ASTContext &C = CGM.getContext();
3190   // 1. Build a list of reduction variables.
3191   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3192   auto Size = RHSExprs.size();
3193   for (const Expr *E : Privates) {
3194     if (E->getType()->isVariablyModifiedType())
3195       // Reserve place for array size.
3196       ++Size;
3197   }
3198   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3199   QualType ReductionArrayTy =
3200       C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
3201                              /*IndexTypeQuals=*/0);
3202   Address ReductionList =
3203       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3204   auto IPriv = Privates.begin();
3205   unsigned Idx = 0;
3206   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3207     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3208     CGF.Builder.CreateStore(
3209         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3210             CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
3211         Elem);
3212     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3213       // Store array size.
3214       ++Idx;
3215       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3216       llvm::Value *Size = CGF.Builder.CreateIntCast(
3217           CGF.getVLASize(
3218                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3219               .NumElts,
3220           CGF.SizeTy, /*isSigned=*/false);
3221       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3222                               Elem);
3223     }
3224   }
3225 
3226   llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3227       ReductionList.getPointer(), CGF.VoidPtrTy);
3228   llvm::Function *ReductionFn = emitReductionFunction(
3229       Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3230       LHSExprs, RHSExprs, ReductionOps);
3231   llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3232   llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3233       CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3234   llvm::Value *InterWarpCopyFn =
3235       emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3236 
3237   if (ParallelReduction) {
3238     llvm::Value *Args[] = {RTLoc,
3239                            ThreadId,
3240                            CGF.Builder.getInt32(RHSExprs.size()),
3241                            ReductionArrayTySize,
3242                            RL,
3243                            ShuffleAndReduceFn,
3244                            InterWarpCopyFn};
3245 
3246     Res = CGF.EmitRuntimeCall(
3247         OMPBuilder.getOrCreateRuntimeFunction(
3248             CGM.getModule(), OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2),
3249         Args);
3250   } else {
3251     assert(TeamsReduction && "expected teams reduction.");
3252     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
3253     llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
3254     int Cnt = 0;
3255     for (const Expr *DRE : Privates) {
3256       PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
3257       ++Cnt;
3258     }
3259     const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
3260         CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
3261         C.getLangOpts().OpenMPCUDAReductionBufNum);
3262     TeamsReductions.push_back(TeamReductionRec);
3263     if (!KernelTeamsReductionPtr) {
3264       KernelTeamsReductionPtr = new llvm::GlobalVariable(
3265           CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
3266           llvm::GlobalValue::InternalLinkage, nullptr,
3267           "_openmp_teams_reductions_buffer_$_$ptr");
3268     }
3269     llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
3270         Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
3271         /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
3272     llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
3273         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
3274     llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
3275         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
3276         ReductionFn);
3277     llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
3278         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
3279     llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
3280         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
3281         ReductionFn);
3282 
3283     llvm::Value *Args[] = {
3284         RTLoc,
3285         ThreadId,
3286         GlobalBufferPtr,
3287         CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
3288         RL,
3289         ShuffleAndReduceFn,
3290         InterWarpCopyFn,
3291         GlobalToBufferCpyFn,
3292         GlobalToBufferRedFn,
3293         BufferToGlobalCpyFn,
3294         BufferToGlobalRedFn};
3295 
3296     Res = CGF.EmitRuntimeCall(
3297         OMPBuilder.getOrCreateRuntimeFunction(
3298             CGM.getModule(), OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2),
3299         Args);
3300   }
3301 
3302   // 5. Build if (res == 1)
3303   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3304   llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3305   llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3306       Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3307   CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
3308 
3309   // 6. Build then branch: where we have reduced values in the master
3310   //    thread in each team.
3311   //    __kmpc_end_reduce{_nowait}(<gtid>);
3312   //    break;
3313   CGF.EmitBlock(ThenBB);
3314 
3315   // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3316   auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
3317                     this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3318     auto IPriv = Privates.begin();
3319     auto ILHS = LHSExprs.begin();
3320     auto IRHS = RHSExprs.begin();
3321     for (const Expr *E : ReductionOps) {
3322       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3323                                   cast<DeclRefExpr>(*IRHS));
3324       ++IPriv;
3325       ++ILHS;
3326       ++IRHS;
3327     }
3328   };
3329   llvm::Value *EndArgs[] = {ThreadId};
3330   RegionCodeGenTy RCG(CodeGen);
3331   NVPTXActionTy Action(
3332       nullptr, llvm::None,
3333       OMPBuilder.getOrCreateRuntimeFunction(
3334           CGM.getModule(), OMPRTL___kmpc_nvptx_end_reduce_nowait),
3335       EndArgs);
3336   RCG.setAction(Action);
3337   RCG(CGF);
3338   // There is no need to emit line number for unconditional branch.
3339   (void)ApplyDebugLocation::CreateEmpty(CGF);
3340   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
3341 }
3342 
3343 const VarDecl *
3344 CGOpenMPRuntimeGPU::translateParameter(const FieldDecl *FD,
3345                                        const VarDecl *NativeParam) const {
3346   if (!NativeParam->getType()->isReferenceType())
3347     return NativeParam;
3348   QualType ArgType = NativeParam->getType();
3349   QualifierCollector QC;
3350   const Type *NonQualTy = QC.strip(ArgType);
3351   QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3352   if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3353     if (Attr->getCaptureKind() == OMPC_map) {
3354       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3355                                                         LangAS::opencl_global);
3356     }
3357   }
3358   ArgType = CGM.getContext().getPointerType(PointeeTy);
3359   QC.addRestrict();
3360   enum { NVPTX_local_addr = 5 };
3361   QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
3362   ArgType = QC.apply(CGM.getContext(), ArgType);
3363   if (isa<ImplicitParamDecl>(NativeParam))
3364     return ImplicitParamDecl::Create(
3365         CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3366         NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
3367   return ParmVarDecl::Create(
3368       CGM.getContext(),
3369       const_cast<DeclContext *>(NativeParam->getDeclContext()),
3370       NativeParam->getBeginLoc(), NativeParam->getLocation(),
3371       NativeParam->getIdentifier(), ArgType,
3372       /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
3373 }
3374 
3375 Address
3376 CGOpenMPRuntimeGPU::getParameterAddress(CodeGenFunction &CGF,
3377                                           const VarDecl *NativeParam,
3378                                           const VarDecl *TargetParam) const {
3379   assert(NativeParam != TargetParam &&
3380          NativeParam->getType()->isReferenceType() &&
3381          "Native arg must not be the same as target arg.");
3382   Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3383   QualType NativeParamType = NativeParam->getType();
3384   QualifierCollector QC;
3385   const Type *NonQualTy = QC.strip(NativeParamType);
3386   QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3387   unsigned NativePointeeAddrSpace =
3388       CGF.getContext().getTargetAddressSpace(NativePointeeTy);
3389   QualType TargetTy = TargetParam->getType();
3390   llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
3391       LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
3392   // First cast to generic.
3393   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3394       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3395                       /*AddrSpace=*/0));
3396   // Cast from generic to native address space.
3397   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3398       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3399                       NativePointeeAddrSpace));
3400   Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3401   CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
3402                         NativeParamType);
3403   return NativeParamAddr;
3404 }
3405 
3406 void CGOpenMPRuntimeGPU::emitOutlinedFunctionCall(
3407     CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
3408     ArrayRef<llvm::Value *> Args) const {
3409   SmallVector<llvm::Value *, 4> TargetArgs;
3410   TargetArgs.reserve(Args.size());
3411   auto *FnType = OutlinedFn.getFunctionType();
3412   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
3413     if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3414       TargetArgs.append(std::next(Args.begin(), I), Args.end());
3415       break;
3416     }
3417     llvm::Type *TargetType = FnType->getParamType(I);
3418     llvm::Value *NativeArg = Args[I];
3419     if (!TargetType->isPointerTy()) {
3420       TargetArgs.emplace_back(NativeArg);
3421       continue;
3422     }
3423     llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3424         NativeArg,
3425         NativeArg->getType()->getPointerElementType()->getPointerTo());
3426     TargetArgs.emplace_back(
3427         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3428   }
3429   CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
3430 }
3431 
3432 /// Emit function which wraps the outline parallel region
3433 /// and controls the arguments which are passed to this function.
3434 /// The wrapper ensures that the outlined function is called
3435 /// with the correct arguments when data is shared.
3436 llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
3437     llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3438   ASTContext &Ctx = CGM.getContext();
3439   const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3440 
3441   // Create a function that takes as argument the source thread.
3442   FunctionArgList WrapperArgs;
3443   QualType Int16QTy =
3444       Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3445   QualType Int32QTy =
3446       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3447   ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
3448                                      /*Id=*/nullptr, Int16QTy,
3449                                      ImplicitParamDecl::Other);
3450   ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
3451                                /*Id=*/nullptr, Int32QTy,
3452                                ImplicitParamDecl::Other);
3453   WrapperArgs.emplace_back(&ParallelLevelArg);
3454   WrapperArgs.emplace_back(&WrapperArg);
3455 
3456   const CGFunctionInfo &CGFI =
3457       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3458 
3459   auto *Fn = llvm::Function::Create(
3460       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3461       Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
3462 
3463   // Ensure we do not inline the function. This is trivially true for the ones
3464   // passed to __kmpc_fork_call but the ones calles in serialized regions
3465   // could be inlined. This is not a perfect but it is closer to the invariant
3466   // we want, namely, every data environment starts with a new function.
3467   // TODO: We should pass the if condition to the runtime function and do the
3468   //       handling there. Much cleaner code.
3469   Fn->addFnAttr(llvm::Attribute::NoInline);
3470 
3471   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3472   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
3473   Fn->setDoesNotRecurse();
3474 
3475   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3476   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3477                     D.getBeginLoc(), D.getBeginLoc());
3478 
3479   const auto *RD = CS.getCapturedRecordDecl();
3480   auto CurField = RD->field_begin();
3481 
3482   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
3483                                                       /*Name=*/".zero.addr");
3484   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
3485   // Get the array of arguments.
3486   SmallVector<llvm::Value *, 8> Args;
3487 
3488   Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3489   Args.emplace_back(ZeroAddr.getPointer());
3490 
3491   CGBuilderTy &Bld = CGF.Builder;
3492   auto CI = CS.capture_begin();
3493 
3494   // Use global memory for data sharing.
3495   // Handle passing of global args to workers.
3496   Address GlobalArgs =
3497       CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3498   llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3499   llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3500   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
3501                           CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
3502                       DataSharingArgs);
3503 
3504   // Retrieve the shared variables from the list of references returned
3505   // by the runtime. Pass the variables to the outlined function.
3506   Address SharedArgListAddress = Address::invalid();
3507   if (CS.capture_size() > 0 ||
3508       isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3509     SharedArgListAddress = CGF.EmitLoadOfPointer(
3510         GlobalArgs, CGF.getContext()
3511                         .getPointerType(CGF.getContext().getPointerType(
3512                             CGF.getContext().VoidPtrTy))
3513                         .castAs<PointerType>());
3514   }
3515   unsigned Idx = 0;
3516   if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3517     Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
3518     Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3519         Src, CGF.SizeTy->getPointerTo());
3520     llvm::Value *LB = CGF.EmitLoadOfScalar(
3521         TypedAddress,
3522         /*Volatile=*/false,
3523         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3524         cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3525     Args.emplace_back(LB);
3526     ++Idx;
3527     Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
3528     TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3529         Src, CGF.SizeTy->getPointerTo());
3530     llvm::Value *UB = CGF.EmitLoadOfScalar(
3531         TypedAddress,
3532         /*Volatile=*/false,
3533         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3534         cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3535     Args.emplace_back(UB);
3536     ++Idx;
3537   }
3538   if (CS.capture_size() > 0) {
3539     ASTContext &CGFContext = CGF.getContext();
3540     for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3541       QualType ElemTy = CurField->getType();
3542       Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
3543       Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3544           Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3545       llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3546                                               /*Volatile=*/false,
3547                                               CGFContext.getPointerType(ElemTy),
3548                                               CI->getLocation());
3549       if (CI->capturesVariableByCopy() &&
3550           !CI->getCapturedVar()->getType()->isAnyPointerType()) {
3551         Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3552                               CI->getLocation());
3553       }
3554       Args.emplace_back(Arg);
3555     }
3556   }
3557 
3558   emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
3559   CGF.FinishFunction();
3560   return Fn;
3561 }
3562 
3563 void CGOpenMPRuntimeGPU::emitFunctionProlog(CodeGenFunction &CGF,
3564                                               const Decl *D) {
3565   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
3566     return;
3567 
3568   assert(D && "Expected function or captured|block decl.");
3569   assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3570          "Function is registered already.");
3571   assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
3572          "Team is set but not processed.");
3573   const Stmt *Body = nullptr;
3574   bool NeedToDelayGlobalization = false;
3575   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3576     Body = FD->getBody();
3577   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3578     Body = BD->getBody();
3579   } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3580     Body = CD->getBody();
3581     NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
3582     if (NeedToDelayGlobalization &&
3583         getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
3584       return;
3585   }
3586   if (!Body)
3587     return;
3588   CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
3589   VarChecker.Visit(Body);
3590   const RecordDecl *GlobalizedVarsRecord =
3591       VarChecker.getGlobalizedRecord(IsInTTDRegion);
3592   TeamAndReductions.first = nullptr;
3593   TeamAndReductions.second.clear();
3594   ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3595       VarChecker.getEscapedVariableLengthDecls();
3596   if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
3597     return;
3598   auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3599   I->getSecond().MappedParams =
3600       std::make_unique<CodeGenFunction::OMPMapVars>();
3601   I->getSecond().EscapedParameters.insert(
3602       VarChecker.getEscapedParameters().begin(),
3603       VarChecker.getEscapedParameters().end());
3604   I->getSecond().EscapedVariableLengthDecls.append(
3605       EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
3606   DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
3607   for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
3608     assert(VD->isCanonicalDecl() && "Expected canonical declaration");
3609     Data.insert(std::make_pair(VD, MappedVarData()));
3610   }
3611   if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
3612     CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
3613     VarChecker.Visit(Body);
3614     I->getSecond().SecondaryLocalVarData.emplace();
3615     DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
3616     for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
3617       assert(VD->isCanonicalDecl() && "Expected canonical declaration");
3618       Data.insert(std::make_pair(VD, MappedVarData()));
3619     }
3620   }
3621   if (!NeedToDelayGlobalization) {
3622     emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
3623     struct GlobalizationScope final : EHScopeStack::Cleanup {
3624       GlobalizationScope() = default;
3625 
3626       void Emit(CodeGenFunction &CGF, Flags flags) override {
3627         static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
3628             .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
3629       }
3630     };
3631     CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
3632   }
3633 }
3634 
3635 Address CGOpenMPRuntimeGPU::getAddressOfLocalVariable(CodeGenFunction &CGF,
3636                                                         const VarDecl *VD) {
3637   if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
3638     const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3639     auto AS = LangAS::Default;
3640     switch (A->getAllocatorType()) {
3641       // Use the default allocator here as by default local vars are
3642       // threadlocal.
3643     case OMPAllocateDeclAttr::OMPNullMemAlloc:
3644     case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
3645     case OMPAllocateDeclAttr::OMPThreadMemAlloc:
3646     case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
3647     case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
3648       // Follow the user decision - use default allocation.
3649       return Address::invalid();
3650     case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
3651       // TODO: implement aupport for user-defined allocators.
3652       return Address::invalid();
3653     case OMPAllocateDeclAttr::OMPConstMemAlloc:
3654       AS = LangAS::cuda_constant;
3655       break;
3656     case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
3657       AS = LangAS::cuda_shared;
3658       break;
3659     case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
3660     case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
3661       break;
3662     }
3663     llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
3664     auto *GV = new llvm::GlobalVariable(
3665         CGM.getModule(), VarTy, /*isConstant=*/false,
3666         llvm::GlobalValue::InternalLinkage, llvm::Constant::getNullValue(VarTy),
3667         VD->getName(),
3668         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3669         CGM.getContext().getTargetAddressSpace(AS));
3670     CharUnits Align = CGM.getContext().getDeclAlign(VD);
3671     GV->setAlignment(Align.getAsAlign());
3672     return Address(
3673         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3674             GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
3675                     VD->getType().getAddressSpace()))),
3676         Align);
3677   }
3678 
3679   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
3680     return Address::invalid();
3681 
3682   VD = VD->getCanonicalDecl();
3683   auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3684   if (I == FunctionGlobalizedDecls.end())
3685     return Address::invalid();
3686   auto VDI = I->getSecond().LocalVarData.find(VD);
3687   if (VDI != I->getSecond().LocalVarData.end())
3688     return VDI->second.PrivateAddr;
3689   if (VD->hasAttrs()) {
3690     for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3691          E(VD->attr_end());
3692          IT != E; ++IT) {
3693       auto VDI = I->getSecond().LocalVarData.find(
3694           cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3695               ->getCanonicalDecl());
3696       if (VDI != I->getSecond().LocalVarData.end())
3697         return VDI->second.PrivateAddr;
3698     }
3699   }
3700 
3701   return Address::invalid();
3702 }
3703 
3704 void CGOpenMPRuntimeGPU::functionFinished(CodeGenFunction &CGF) {
3705   FunctionGlobalizedDecls.erase(CGF.CurFn);
3706   CGOpenMPRuntime::functionFinished(CGF);
3707 }
3708 
3709 void CGOpenMPRuntimeGPU::getDefaultDistScheduleAndChunk(
3710     CodeGenFunction &CGF, const OMPLoopDirective &S,
3711     OpenMPDistScheduleClauseKind &ScheduleKind,
3712     llvm::Value *&Chunk) const {
3713   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
3714   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
3715     ScheduleKind = OMPC_DIST_SCHEDULE_static;
3716     Chunk = CGF.EmitScalarConversion(
3717         RT.getGPUNumThreads(CGF),
3718         CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3719         S.getIterationVariable()->getType(), S.getBeginLoc());
3720     return;
3721   }
3722   CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
3723       CGF, S, ScheduleKind, Chunk);
3724 }
3725 
3726 void CGOpenMPRuntimeGPU::getDefaultScheduleAndChunk(
3727     CodeGenFunction &CGF, const OMPLoopDirective &S,
3728     OpenMPScheduleClauseKind &ScheduleKind,
3729     const Expr *&ChunkExpr) const {
3730   ScheduleKind = OMPC_SCHEDULE_static;
3731   // Chunk size is 1 in this case.
3732   llvm::APInt ChunkSize(32, 1);
3733   ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
3734       CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3735       SourceLocation());
3736 }
3737 
3738 void CGOpenMPRuntimeGPU::adjustTargetSpecificDataForLambdas(
3739     CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
3740   assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
3741          " Expected target-based directive.");
3742   const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
3743   for (const CapturedStmt::Capture &C : CS->captures()) {
3744     // Capture variables captured by reference in lambdas for target-based
3745     // directives.
3746     if (!C.capturesVariable())
3747       continue;
3748     const VarDecl *VD = C.getCapturedVar();
3749     const auto *RD = VD->getType()
3750                          .getCanonicalType()
3751                          .getNonReferenceType()
3752                          ->getAsCXXRecordDecl();
3753     if (!RD || !RD->isLambda())
3754       continue;
3755     Address VDAddr = CGF.GetAddrOfLocalVar(VD);
3756     LValue VDLVal;
3757     if (VD->getType().getCanonicalType()->isReferenceType())
3758       VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
3759     else
3760       VDLVal = CGF.MakeAddrLValue(
3761           VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
3762     llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3763     FieldDecl *ThisCapture = nullptr;
3764     RD->getCaptureFields(Captures, ThisCapture);
3765     if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
3766       LValue ThisLVal =
3767           CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
3768       llvm::Value *CXXThis = CGF.LoadCXXThis();
3769       CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
3770     }
3771     for (const LambdaCapture &LC : RD->captures()) {
3772       if (LC.getCaptureKind() != LCK_ByRef)
3773         continue;
3774       const VarDecl *VD = LC.getCapturedVar();
3775       if (!CS->capturesVariable(VD))
3776         continue;
3777       auto It = Captures.find(VD);
3778       assert(It != Captures.end() && "Found lambda capture without field.");
3779       LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
3780       Address VDAddr = CGF.GetAddrOfLocalVar(VD);
3781       if (VD->getType().getCanonicalType()->isReferenceType())
3782         VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
3783                                                VD->getType().getCanonicalType())
3784                      .getAddress(CGF);
3785       CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
3786     }
3787   }
3788 }
3789 
3790 bool CGOpenMPRuntimeGPU::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
3791                                                             LangAS &AS) {
3792   if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
3793     return false;
3794   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3795   switch(A->getAllocatorType()) {
3796   case OMPAllocateDeclAttr::OMPNullMemAlloc:
3797   case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
3798   // Not supported, fallback to the default mem space.
3799   case OMPAllocateDeclAttr::OMPThreadMemAlloc:
3800   case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
3801   case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
3802   case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
3803   case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
3804     AS = LangAS::Default;
3805     return true;
3806   case OMPAllocateDeclAttr::OMPConstMemAlloc:
3807     AS = LangAS::cuda_constant;
3808     return true;
3809   case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
3810     AS = LangAS::cuda_shared;
3811     return true;
3812   case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
3813     llvm_unreachable("Expected predefined allocator for the variables with the "
3814                      "static storage.");
3815   }
3816   return false;
3817 }
3818 
3819 // Get current CudaArch and ignore any unknown values
3820 static CudaArch getCudaArch(CodeGenModule &CGM) {
3821   if (!CGM.getTarget().hasFeature("ptx"))
3822     return CudaArch::UNKNOWN;
3823   for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
3824     if (Feature.getValue()) {
3825       CudaArch Arch = StringToCudaArch(Feature.getKey());
3826       if (Arch != CudaArch::UNKNOWN)
3827         return Arch;
3828     }
3829   }
3830   return CudaArch::UNKNOWN;
3831 }
3832 
3833 /// Check to see if target architecture supports unified addressing which is
3834 /// a restriction for OpenMP requires clause "unified_shared_memory".
3835 void CGOpenMPRuntimeGPU::processRequiresDirective(
3836     const OMPRequiresDecl *D) {
3837   for (const OMPClause *Clause : D->clauselists()) {
3838     if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
3839       CudaArch Arch = getCudaArch(CGM);
3840       switch (Arch) {
3841       case CudaArch::SM_20:
3842       case CudaArch::SM_21:
3843       case CudaArch::SM_30:
3844       case CudaArch::SM_32:
3845       case CudaArch::SM_35:
3846       case CudaArch::SM_37:
3847       case CudaArch::SM_50:
3848       case CudaArch::SM_52:
3849       case CudaArch::SM_53: {
3850         SmallString<256> Buffer;
3851         llvm::raw_svector_ostream Out(Buffer);
3852         Out << "Target architecture " << CudaArchToString(Arch)
3853             << " does not support unified addressing";
3854         CGM.Error(Clause->getBeginLoc(), Out.str());
3855         return;
3856       }
3857       case CudaArch::SM_60:
3858       case CudaArch::SM_61:
3859       case CudaArch::SM_62:
3860       case CudaArch::SM_70:
3861       case CudaArch::SM_72:
3862       case CudaArch::SM_75:
3863       case CudaArch::SM_80:
3864       case CudaArch::SM_86:
3865       case CudaArch::GFX600:
3866       case CudaArch::GFX601:
3867       case CudaArch::GFX602:
3868       case CudaArch::GFX700:
3869       case CudaArch::GFX701:
3870       case CudaArch::GFX702:
3871       case CudaArch::GFX703:
3872       case CudaArch::GFX704:
3873       case CudaArch::GFX705:
3874       case CudaArch::GFX801:
3875       case CudaArch::GFX802:
3876       case CudaArch::GFX803:
3877       case CudaArch::GFX805:
3878       case CudaArch::GFX810:
3879       case CudaArch::GFX900:
3880       case CudaArch::GFX902:
3881       case CudaArch::GFX904:
3882       case CudaArch::GFX906:
3883       case CudaArch::GFX908:
3884       case CudaArch::GFX909:
3885       case CudaArch::GFX90a:
3886       case CudaArch::GFX90c:
3887       case CudaArch::GFX1010:
3888       case CudaArch::GFX1011:
3889       case CudaArch::GFX1012:
3890       case CudaArch::GFX1013:
3891       case CudaArch::GFX1030:
3892       case CudaArch::GFX1031:
3893       case CudaArch::GFX1032:
3894       case CudaArch::GFX1033:
3895       case CudaArch::GFX1034:
3896       case CudaArch::GFX1035:
3897       case CudaArch::UNUSED:
3898       case CudaArch::UNKNOWN:
3899         break;
3900       case CudaArch::LAST:
3901         llvm_unreachable("Unexpected Cuda arch.");
3902       }
3903     }
3904   }
3905   CGOpenMPRuntime::processRequiresDirective(D);
3906 }
3907 
3908 void CGOpenMPRuntimeGPU::clear() {
3909 
3910   if (!TeamsReductions.empty()) {
3911     ASTContext &C = CGM.getContext();
3912     RecordDecl *StaticRD = C.buildImplicitRecord(
3913         "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
3914     StaticRD->startDefinition();
3915     for (const RecordDecl *TeamReductionRec : TeamsReductions) {
3916       QualType RecTy = C.getRecordType(TeamReductionRec);
3917       auto *Field = FieldDecl::Create(
3918           C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
3919           C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
3920           /*BW=*/nullptr, /*Mutable=*/false,
3921           /*InitStyle=*/ICIS_NoInit);
3922       Field->setAccess(AS_public);
3923       StaticRD->addDecl(Field);
3924     }
3925     StaticRD->completeDefinition();
3926     QualType StaticTy = C.getRecordType(StaticRD);
3927     llvm::Type *LLVMReductionsBufferTy =
3928         CGM.getTypes().ConvertTypeForMem(StaticTy);
3929     // FIXME: nvlink does not handle weak linkage correctly (object with the
3930     // different size are reported as erroneous).
3931     // Restore CommonLinkage as soon as nvlink is fixed.
3932     auto *GV = new llvm::GlobalVariable(
3933         CGM.getModule(), LLVMReductionsBufferTy,
3934         /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
3935         llvm::Constant::getNullValue(LLVMReductionsBufferTy),
3936         "_openmp_teams_reductions_buffer_$_");
3937     KernelTeamsReductionPtr->setInitializer(
3938         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
3939                                                              CGM.VoidPtrTy));
3940   }
3941   CGOpenMPRuntime::clear();
3942 }
3943