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