1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
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 contains code to emit OpenMP nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCleanup.h"
14 #include "CGOpenMPRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/Stmt.h"
19 #include "clang/AST/StmtOpenMP.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/Basic/PrettyStackTrace.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 namespace {
26 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
27 /// for captured expressions.
28 class OMPLexicalScope : public CodeGenFunction::LexicalScope {
29   void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30     for (const auto *C : S.clauses()) {
31       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
32         if (const auto *PreInit =
33                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
34           for (const auto *I : PreInit->decls()) {
35             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
36               CGF.EmitVarDecl(cast<VarDecl>(*I));
37             } else {
38               CodeGenFunction::AutoVarEmission Emission =
39                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
40               CGF.EmitAutoVarCleanups(Emission);
41             }
42           }
43         }
44       }
45     }
46   }
47   CodeGenFunction::OMPPrivateScope InlinedShareds;
48 
49   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
50     return CGF.LambdaCaptureFields.lookup(VD) ||
51            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
52            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
53   }
54 
55 public:
56   OMPLexicalScope(
57       CodeGenFunction &CGF, const OMPExecutableDirective &S,
58       const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
59       const bool EmitPreInitStmt = true)
60       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
61         InlinedShareds(CGF) {
62     if (EmitPreInitStmt)
63       emitPreInitStmt(CGF, S);
64     if (!CapturedRegion.hasValue())
65       return;
66     assert(S.hasAssociatedStmt() &&
67            "Expected associated statement for inlined directive.");
68     const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
69     for (const auto &C : CS->captures()) {
70       if (C.capturesVariable() || C.capturesVariableByCopy()) {
71         auto *VD = C.getCapturedVar();
72         assert(VD == VD->getCanonicalDecl() &&
73                "Canonical decl must be captured.");
74         DeclRefExpr DRE(
75             CGF.getContext(), const_cast<VarDecl *>(VD),
76             isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
77                                        InlinedShareds.isGlobalVarCaptured(VD)),
78             VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
79         InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
80           return CGF.EmitLValue(&DRE).getAddress();
81         });
82       }
83     }
84     (void)InlinedShareds.Privatize();
85   }
86 };
87 
88 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
89 /// for captured expressions.
90 class OMPParallelScope final : public OMPLexicalScope {
91   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
92     OpenMPDirectiveKind Kind = S.getDirectiveKind();
93     return !(isOpenMPTargetExecutionDirective(Kind) ||
94              isOpenMPLoopBoundSharingDirective(Kind)) &&
95            isOpenMPParallelDirective(Kind);
96   }
97 
98 public:
99   OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
100       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
101                         EmitPreInitStmt(S)) {}
102 };
103 
104 /// Lexical scope for OpenMP teams construct, that handles correct codegen
105 /// for captured expressions.
106 class OMPTeamsScope final : public OMPLexicalScope {
107   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
108     OpenMPDirectiveKind Kind = S.getDirectiveKind();
109     return !isOpenMPTargetExecutionDirective(Kind) &&
110            isOpenMPTeamsDirective(Kind);
111   }
112 
113 public:
114   OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
115       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
116                         EmitPreInitStmt(S)) {}
117 };
118 
119 /// Private scope for OpenMP loop-based directives, that supports capturing
120 /// of used expression from loop statement.
121 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
122   void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
123     CodeGenFunction::OMPMapVars PreCondVars;
124     llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
125     for (const auto *E : S.counters()) {
126       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
127       EmittedAsPrivate.insert(VD->getCanonicalDecl());
128       (void)PreCondVars.setVarAddr(
129           CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
130     }
131     // Mark private vars as undefs.
132     for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
133       for (const Expr *IRef : C->varlists()) {
134         const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
135         if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
136           (void)PreCondVars.setVarAddr(
137               CGF, OrigVD,
138               Address(llvm::UndefValue::get(
139                           CGF.ConvertTypeForMem(CGF.getContext().getPointerType(
140                               OrigVD->getType().getNonReferenceType()))),
141                       CGF.getContext().getDeclAlign(OrigVD)));
142         }
143       }
144     }
145     (void)PreCondVars.apply(CGF);
146     // Emit init, __range and __end variables for C++ range loops.
147     const Stmt *Body =
148         S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
149     for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) {
150       Body = OMPLoopDirective::tryToFindNextInnerLoop(
151           Body, /*TryImperfectlyNestedLoops=*/true);
152       if (auto *For = dyn_cast<ForStmt>(Body)) {
153         Body = For->getBody();
154       } else {
155         assert(isa<CXXForRangeStmt>(Body) &&
156                "Expected canonical for loop or range-based for loop.");
157         auto *CXXFor = cast<CXXForRangeStmt>(Body);
158         if (const Stmt *Init = CXXFor->getInit())
159           CGF.EmitStmt(Init);
160         CGF.EmitStmt(CXXFor->getRangeStmt());
161         CGF.EmitStmt(CXXFor->getEndStmt());
162         Body = CXXFor->getBody();
163       }
164     }
165     if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
166       for (const auto *I : PreInits->decls())
167         CGF.EmitVarDecl(cast<VarDecl>(*I));
168     }
169     PreCondVars.restore(CGF);
170   }
171 
172 public:
173   OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
174       : CodeGenFunction::RunCleanupsScope(CGF) {
175     emitPreInitStmt(CGF, S);
176   }
177 };
178 
179 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
180   CodeGenFunction::OMPPrivateScope InlinedShareds;
181 
182   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
183     return CGF.LambdaCaptureFields.lookup(VD) ||
184            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
185            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
186             cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
187   }
188 
189 public:
190   OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
191       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
192         InlinedShareds(CGF) {
193     for (const auto *C : S.clauses()) {
194       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
195         if (const auto *PreInit =
196                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
197           for (const auto *I : PreInit->decls()) {
198             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
199               CGF.EmitVarDecl(cast<VarDecl>(*I));
200             } else {
201               CodeGenFunction::AutoVarEmission Emission =
202                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
203               CGF.EmitAutoVarCleanups(Emission);
204             }
205           }
206         }
207       } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
208         for (const Expr *E : UDP->varlists()) {
209           const Decl *D = cast<DeclRefExpr>(E)->getDecl();
210           if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
211             CGF.EmitVarDecl(*OED);
212         }
213       }
214     }
215     if (!isOpenMPSimdDirective(S.getDirectiveKind()))
216       CGF.EmitOMPPrivateClause(S, InlinedShareds);
217     if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
218       if (const Expr *E = TG->getReductionRef())
219         CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
220     }
221     const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
222     while (CS) {
223       for (auto &C : CS->captures()) {
224         if (C.capturesVariable() || C.capturesVariableByCopy()) {
225           auto *VD = C.getCapturedVar();
226           assert(VD == VD->getCanonicalDecl() &&
227                  "Canonical decl must be captured.");
228           DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
229                           isCapturedVar(CGF, VD) ||
230                               (CGF.CapturedStmtInfo &&
231                                InlinedShareds.isGlobalVarCaptured(VD)),
232                           VD->getType().getNonReferenceType(), VK_LValue,
233                           C.getLocation());
234           InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
235             return CGF.EmitLValue(&DRE).getAddress();
236           });
237         }
238       }
239       CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
240     }
241     (void)InlinedShareds.Privatize();
242   }
243 };
244 
245 } // namespace
246 
247 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
248                                          const OMPExecutableDirective &S,
249                                          const RegionCodeGenTy &CodeGen);
250 
251 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
252   if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
253     if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
254       OrigVD = OrigVD->getCanonicalDecl();
255       bool IsCaptured =
256           LambdaCaptureFields.lookup(OrigVD) ||
257           (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
258           (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
259       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
260                       OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
261       return EmitLValue(&DRE);
262     }
263   }
264   return EmitLValue(E);
265 }
266 
267 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
268   ASTContext &C = getContext();
269   llvm::Value *Size = nullptr;
270   auto SizeInChars = C.getTypeSizeInChars(Ty);
271   if (SizeInChars.isZero()) {
272     // getTypeSizeInChars() returns 0 for a VLA.
273     while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
274       VlaSizePair VlaSize = getVLASize(VAT);
275       Ty = VlaSize.Type;
276       Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
277                   : VlaSize.NumElts;
278     }
279     SizeInChars = C.getTypeSizeInChars(Ty);
280     if (SizeInChars.isZero())
281       return llvm::ConstantInt::get(SizeTy, /*V=*/0);
282     return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
283   }
284   return CGM.getSize(SizeInChars);
285 }
286 
287 void CodeGenFunction::GenerateOpenMPCapturedVars(
288     const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
289   const RecordDecl *RD = S.getCapturedRecordDecl();
290   auto CurField = RD->field_begin();
291   auto CurCap = S.captures().begin();
292   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
293                                                  E = S.capture_init_end();
294        I != E; ++I, ++CurField, ++CurCap) {
295     if (CurField->hasCapturedVLAType()) {
296       const VariableArrayType *VAT = CurField->getCapturedVLAType();
297       llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
298       CapturedVars.push_back(Val);
299     } else if (CurCap->capturesThis()) {
300       CapturedVars.push_back(CXXThisValue);
301     } else if (CurCap->capturesVariableByCopy()) {
302       llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
303 
304       // If the field is not a pointer, we need to save the actual value
305       // and load it as a void pointer.
306       if (!CurField->getType()->isAnyPointerType()) {
307         ASTContext &Ctx = getContext();
308         Address DstAddr = CreateMemTemp(
309             Ctx.getUIntPtrType(),
310             Twine(CurCap->getCapturedVar()->getName(), ".casted"));
311         LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
312 
313         llvm::Value *SrcAddrVal = EmitScalarConversion(
314             DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
315             Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
316         LValue SrcLV =
317             MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
318 
319         // Store the value using the source type pointer.
320         EmitStoreThroughLValue(RValue::get(CV), SrcLV);
321 
322         // Load the value using the destination type pointer.
323         CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
324       }
325       CapturedVars.push_back(CV);
326     } else {
327       assert(CurCap->capturesVariable() && "Expected capture by reference.");
328       CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
329     }
330   }
331 }
332 
333 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
334                                     QualType DstType, StringRef Name,
335                                     LValue AddrLV) {
336   ASTContext &Ctx = CGF.getContext();
337 
338   llvm::Value *CastedPtr = CGF.EmitScalarConversion(
339       AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
340       Ctx.getPointerType(DstType), Loc);
341   Address TmpAddr =
342       CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
343           .getAddress();
344   return TmpAddr;
345 }
346 
347 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
348   if (T->isLValueReferenceType())
349     return C.getLValueReferenceType(
350         getCanonicalParamType(C, T.getNonReferenceType()),
351         /*SpelledAsLValue=*/false);
352   if (T->isPointerType())
353     return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
354   if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
355     if (const auto *VLA = dyn_cast<VariableArrayType>(A))
356       return getCanonicalParamType(C, VLA->getElementType());
357     if (!A->isVariablyModifiedType())
358       return C.getCanonicalType(T);
359   }
360   return C.getCanonicalParamType(T);
361 }
362 
363 namespace {
364   /// Contains required data for proper outlined function codegen.
365   struct FunctionOptions {
366     /// Captured statement for which the function is generated.
367     const CapturedStmt *S = nullptr;
368     /// true if cast to/from  UIntPtr is required for variables captured by
369     /// value.
370     const bool UIntPtrCastRequired = true;
371     /// true if only casted arguments must be registered as local args or VLA
372     /// sizes.
373     const bool RegisterCastedArgsOnly = false;
374     /// Name of the generated function.
375     const StringRef FunctionName;
376     explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
377                              bool RegisterCastedArgsOnly,
378                              StringRef FunctionName)
379         : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
380           RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
381           FunctionName(FunctionName) {}
382   };
383 }
384 
385 static llvm::Function *emitOutlinedFunctionPrologue(
386     CodeGenFunction &CGF, FunctionArgList &Args,
387     llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
388         &LocalAddrs,
389     llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
390         &VLASizes,
391     llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
392   const CapturedDecl *CD = FO.S->getCapturedDecl();
393   const RecordDecl *RD = FO.S->getCapturedRecordDecl();
394   assert(CD->hasBody() && "missing CapturedDecl body");
395 
396   CXXThisValue = nullptr;
397   // Build the argument list.
398   CodeGenModule &CGM = CGF.CGM;
399   ASTContext &Ctx = CGM.getContext();
400   FunctionArgList TargetArgs;
401   Args.append(CD->param_begin(),
402               std::next(CD->param_begin(), CD->getContextParamPosition()));
403   TargetArgs.append(
404       CD->param_begin(),
405       std::next(CD->param_begin(), CD->getContextParamPosition()));
406   auto I = FO.S->captures().begin();
407   FunctionDecl *DebugFunctionDecl = nullptr;
408   if (!FO.UIntPtrCastRequired) {
409     FunctionProtoType::ExtProtoInfo EPI;
410     QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
411     DebugFunctionDecl = FunctionDecl::Create(
412         Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
413         SourceLocation(), DeclarationName(), FunctionTy,
414         Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
415         /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
416   }
417   for (const FieldDecl *FD : RD->fields()) {
418     QualType ArgType = FD->getType();
419     IdentifierInfo *II = nullptr;
420     VarDecl *CapVar = nullptr;
421 
422     // If this is a capture by copy and the type is not a pointer, the outlined
423     // function argument type should be uintptr and the value properly casted to
424     // uintptr. This is necessary given that the runtime library is only able to
425     // deal with pointers. We can pass in the same way the VLA type sizes to the
426     // outlined function.
427     if (FO.UIntPtrCastRequired &&
428         ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
429          I->capturesVariableArrayType()))
430       ArgType = Ctx.getUIntPtrType();
431 
432     if (I->capturesVariable() || I->capturesVariableByCopy()) {
433       CapVar = I->getCapturedVar();
434       II = CapVar->getIdentifier();
435     } else if (I->capturesThis()) {
436       II = &Ctx.Idents.get("this");
437     } else {
438       assert(I->capturesVariableArrayType());
439       II = &Ctx.Idents.get("vla");
440     }
441     if (ArgType->isVariablyModifiedType())
442       ArgType = getCanonicalParamType(Ctx, ArgType);
443     VarDecl *Arg;
444     if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
445       Arg = ParmVarDecl::Create(
446           Ctx, DebugFunctionDecl,
447           CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
448           CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
449           /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
450     } else {
451       Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
452                                       II, ArgType, ImplicitParamDecl::Other);
453     }
454     Args.emplace_back(Arg);
455     // Do not cast arguments if we emit function with non-original types.
456     TargetArgs.emplace_back(
457         FO.UIntPtrCastRequired
458             ? Arg
459             : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
460     ++I;
461   }
462   Args.append(
463       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
464       CD->param_end());
465   TargetArgs.append(
466       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
467       CD->param_end());
468 
469   // Create the function declaration.
470   const CGFunctionInfo &FuncInfo =
471       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
472   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
473 
474   auto *F =
475       llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
476                              FO.FunctionName, &CGM.getModule());
477   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
478   if (CD->isNothrow())
479     F->setDoesNotThrow();
480   F->setDoesNotRecurse();
481 
482   // Generate the function.
483   CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
484                     FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
485   unsigned Cnt = CD->getContextParamPosition();
486   I = FO.S->captures().begin();
487   for (const FieldDecl *FD : RD->fields()) {
488     // Do not map arguments if we emit function with non-original types.
489     Address LocalAddr(Address::invalid());
490     if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
491       LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
492                                                              TargetArgs[Cnt]);
493     } else {
494       LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
495     }
496     // If we are capturing a pointer by copy we don't need to do anything, just
497     // use the value that we get from the arguments.
498     if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
499       const VarDecl *CurVD = I->getCapturedVar();
500       if (!FO.RegisterCastedArgsOnly)
501         LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
502       ++Cnt;
503       ++I;
504       continue;
505     }
506 
507     LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
508                                         AlignmentSource::Decl);
509     if (FD->hasCapturedVLAType()) {
510       if (FO.UIntPtrCastRequired) {
511         ArgLVal = CGF.MakeAddrLValue(
512             castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
513                                  Args[Cnt]->getName(), ArgLVal),
514             FD->getType(), AlignmentSource::Decl);
515       }
516       llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
517       const VariableArrayType *VAT = FD->getCapturedVLAType();
518       VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
519     } else if (I->capturesVariable()) {
520       const VarDecl *Var = I->getCapturedVar();
521       QualType VarTy = Var->getType();
522       Address ArgAddr = ArgLVal.getAddress();
523       if (ArgLVal.getType()->isLValueReferenceType()) {
524         ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
525       } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
526         assert(ArgLVal.getType()->isPointerType());
527         ArgAddr = CGF.EmitLoadOfPointer(
528             ArgAddr, ArgLVal.getType()->castAs<PointerType>());
529       }
530       if (!FO.RegisterCastedArgsOnly) {
531         LocalAddrs.insert(
532             {Args[Cnt],
533              {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
534       }
535     } else if (I->capturesVariableByCopy()) {
536       assert(!FD->getType()->isAnyPointerType() &&
537              "Not expecting a captured pointer.");
538       const VarDecl *Var = I->getCapturedVar();
539       LocalAddrs.insert({Args[Cnt],
540                          {Var, FO.UIntPtrCastRequired
541                                    ? castValueFromUintptr(
542                                          CGF, I->getLocation(), FD->getType(),
543                                          Args[Cnt]->getName(), ArgLVal)
544                                    : ArgLVal.getAddress()}});
545     } else {
546       // If 'this' is captured, load it into CXXThisValue.
547       assert(I->capturesThis());
548       CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
549       LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
550     }
551     ++Cnt;
552     ++I;
553   }
554 
555   return F;
556 }
557 
558 llvm::Function *
559 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
560   assert(
561       CapturedStmtInfo &&
562       "CapturedStmtInfo should be set when generating the captured function");
563   const CapturedDecl *CD = S.getCapturedDecl();
564   // Build the argument list.
565   bool NeedWrapperFunction =
566       getDebugInfo() &&
567       CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
568   FunctionArgList Args;
569   llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
570   llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
571   SmallString<256> Buffer;
572   llvm::raw_svector_ostream Out(Buffer);
573   Out << CapturedStmtInfo->getHelperName();
574   if (NeedWrapperFunction)
575     Out << "_debug__";
576   FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
577                      Out.str());
578   llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
579                                                    VLASizes, CXXThisValue, FO);
580   CodeGenFunction::OMPPrivateScope LocalScope(*this);
581   for (const auto &LocalAddrPair : LocalAddrs) {
582     if (LocalAddrPair.second.first) {
583       LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
584         return LocalAddrPair.second.second;
585       });
586     }
587   }
588   (void)LocalScope.Privatize();
589   for (const auto &VLASizePair : VLASizes)
590     VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
591   PGO.assignRegionCounters(GlobalDecl(CD), F);
592   CapturedStmtInfo->EmitBody(*this, CD->getBody());
593   (void)LocalScope.ForceCleanup();
594   FinishFunction(CD->getBodyRBrace());
595   if (!NeedWrapperFunction)
596     return F;
597 
598   FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
599                             /*RegisterCastedArgsOnly=*/true,
600                             CapturedStmtInfo->getHelperName());
601   CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
602   WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
603   Args.clear();
604   LocalAddrs.clear();
605   VLASizes.clear();
606   llvm::Function *WrapperF =
607       emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
608                                    WrapperCGF.CXXThisValue, WrapperFO);
609   llvm::SmallVector<llvm::Value *, 4> CallArgs;
610   for (const auto *Arg : Args) {
611     llvm::Value *CallArg;
612     auto I = LocalAddrs.find(Arg);
613     if (I != LocalAddrs.end()) {
614       LValue LV = WrapperCGF.MakeAddrLValue(
615           I->second.second,
616           I->second.first ? I->second.first->getType() : Arg->getType(),
617           AlignmentSource::Decl);
618       CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
619     } else {
620       auto EI = VLASizes.find(Arg);
621       if (EI != VLASizes.end()) {
622         CallArg = EI->second.second;
623       } else {
624         LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
625                                               Arg->getType(),
626                                               AlignmentSource::Decl);
627         CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
628       }
629     }
630     CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
631   }
632   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
633                                                   F, CallArgs);
634   WrapperCGF.FinishFunction();
635   return WrapperF;
636 }
637 
638 //===----------------------------------------------------------------------===//
639 //                              OpenMP Directive Emission
640 //===----------------------------------------------------------------------===//
641 void CodeGenFunction::EmitOMPAggregateAssign(
642     Address DestAddr, Address SrcAddr, QualType OriginalType,
643     const llvm::function_ref<void(Address, Address)> CopyGen) {
644   // Perform element-by-element initialization.
645   QualType ElementTy;
646 
647   // Drill down to the base element type on both arrays.
648   const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
649   llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
650   SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
651 
652   llvm::Value *SrcBegin = SrcAddr.getPointer();
653   llvm::Value *DestBegin = DestAddr.getPointer();
654   // Cast from pointer to array type to pointer to single element.
655   llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
656   // The basic structure here is a while-do loop.
657   llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
658   llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
659   llvm::Value *IsEmpty =
660       Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
661   Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
662 
663   // Enter the loop body, making that address the current address.
664   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
665   EmitBlock(BodyBB);
666 
667   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
668 
669   llvm::PHINode *SrcElementPHI =
670     Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
671   SrcElementPHI->addIncoming(SrcBegin, EntryBB);
672   Address SrcElementCurrent =
673       Address(SrcElementPHI,
674               SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
675 
676   llvm::PHINode *DestElementPHI =
677     Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
678   DestElementPHI->addIncoming(DestBegin, EntryBB);
679   Address DestElementCurrent =
680     Address(DestElementPHI,
681             DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
682 
683   // Emit copy.
684   CopyGen(DestElementCurrent, SrcElementCurrent);
685 
686   // Shift the address forward by one element.
687   llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
688       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
689   llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
690       SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
691   // Check whether we've reached the end.
692   llvm::Value *Done =
693       Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
694   Builder.CreateCondBr(Done, DoneBB, BodyBB);
695   DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
696   SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
697 
698   // Done.
699   EmitBlock(DoneBB, /*IsFinished=*/true);
700 }
701 
702 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
703                                   Address SrcAddr, const VarDecl *DestVD,
704                                   const VarDecl *SrcVD, const Expr *Copy) {
705   if (OriginalType->isArrayType()) {
706     const auto *BO = dyn_cast<BinaryOperator>(Copy);
707     if (BO && BO->getOpcode() == BO_Assign) {
708       // Perform simple memcpy for simple copying.
709       LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
710       LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
711       EmitAggregateAssign(Dest, Src, OriginalType);
712     } else {
713       // For arrays with complex element types perform element by element
714       // copying.
715       EmitOMPAggregateAssign(
716           DestAddr, SrcAddr, OriginalType,
717           [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
718             // Working with the single array element, so have to remap
719             // destination and source variables to corresponding array
720             // elements.
721             CodeGenFunction::OMPPrivateScope Remap(*this);
722             Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
723             Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
724             (void)Remap.Privatize();
725             EmitIgnoredExpr(Copy);
726           });
727     }
728   } else {
729     // Remap pseudo source variable to private copy.
730     CodeGenFunction::OMPPrivateScope Remap(*this);
731     Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
732     Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
733     (void)Remap.Privatize();
734     // Emit copying of the whole variable.
735     EmitIgnoredExpr(Copy);
736   }
737 }
738 
739 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
740                                                 OMPPrivateScope &PrivateScope) {
741   if (!HaveInsertPoint())
742     return false;
743   bool DeviceConstTarget =
744       getLangOpts().OpenMPIsDevice &&
745       isOpenMPTargetExecutionDirective(D.getDirectiveKind());
746   bool FirstprivateIsLastprivate = false;
747   llvm::DenseSet<const VarDecl *> Lastprivates;
748   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
749     for (const auto *D : C->varlists())
750       Lastprivates.insert(
751           cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
752   }
753   llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
754   llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
755   getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
756   // Force emission of the firstprivate copy if the directive does not emit
757   // outlined function, like omp for, omp simd, omp distribute etc.
758   bool MustEmitFirstprivateCopy =
759       CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
760   for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
761     auto IRef = C->varlist_begin();
762     auto InitsRef = C->inits().begin();
763     for (const Expr *IInit : C->private_copies()) {
764       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
765       bool ThisFirstprivateIsLastprivate =
766           Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
767       const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
768       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
769       if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
770           !FD->getType()->isReferenceType() &&
771           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
772         EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
773         ++IRef;
774         ++InitsRef;
775         continue;
776       }
777       // Do not emit copy for firstprivate constant variables in target regions,
778       // captured by reference.
779       if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
780           FD && FD->getType()->isReferenceType() &&
781           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
782         (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,
783                                                                     OrigVD);
784         ++IRef;
785         ++InitsRef;
786         continue;
787       }
788       FirstprivateIsLastprivate =
789           FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
790       if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
791         const auto *VDInit =
792             cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
793         bool IsRegistered;
794         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
795                         /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
796                         (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
797         LValue OriginalLVal;
798         if (!FD) {
799           // Check if the firstprivate variable is just a constant value.
800           ConstantEmission CE = tryEmitAsConstant(&DRE);
801           if (CE && !CE.isReference()) {
802             // Constant value, no need to create a copy.
803             ++IRef;
804             ++InitsRef;
805             continue;
806           }
807           if (CE && CE.isReference()) {
808             OriginalLVal = CE.getReferenceLValue(*this, &DRE);
809           } else {
810             assert(!CE && "Expected non-constant firstprivate.");
811             OriginalLVal = EmitLValue(&DRE);
812           }
813         } else {
814           OriginalLVal = EmitLValue(&DRE);
815         }
816         QualType Type = VD->getType();
817         if (Type->isArrayType()) {
818           // Emit VarDecl with copy init for arrays.
819           // Get the address of the original variable captured in current
820           // captured region.
821           IsRegistered = PrivateScope.addPrivate(
822               OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
823                 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
824                 const Expr *Init = VD->getInit();
825                 if (!isa<CXXConstructExpr>(Init) ||
826                     isTrivialInitializer(Init)) {
827                   // Perform simple memcpy.
828                   LValue Dest =
829                       MakeAddrLValue(Emission.getAllocatedAddress(), Type);
830                   EmitAggregateAssign(Dest, OriginalLVal, Type);
831                 } else {
832                   EmitOMPAggregateAssign(
833                       Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
834                       Type,
835                       [this, VDInit, Init](Address DestElement,
836                                            Address SrcElement) {
837                         // Clean up any temporaries needed by the
838                         // initialization.
839                         RunCleanupsScope InitScope(*this);
840                         // Emit initialization for single element.
841                         setAddrOfLocalVar(VDInit, SrcElement);
842                         EmitAnyExprToMem(Init, DestElement,
843                                          Init->getType().getQualifiers(),
844                                          /*IsInitializer*/ false);
845                         LocalDeclMap.erase(VDInit);
846                       });
847                 }
848                 EmitAutoVarCleanups(Emission);
849                 return Emission.getAllocatedAddress();
850               });
851         } else {
852           Address OriginalAddr = OriginalLVal.getAddress();
853           IsRegistered = PrivateScope.addPrivate(
854               OrigVD, [this, VDInit, OriginalAddr, VD]() {
855                 // Emit private VarDecl with copy init.
856                 // Remap temp VDInit variable to the address of the original
857                 // variable (for proper handling of captured global variables).
858                 setAddrOfLocalVar(VDInit, OriginalAddr);
859                 EmitDecl(*VD);
860                 LocalDeclMap.erase(VDInit);
861                 return GetAddrOfLocalVar(VD);
862               });
863         }
864         assert(IsRegistered &&
865                "firstprivate var already registered as private");
866         // Silence the warning about unused variable.
867         (void)IsRegistered;
868       }
869       ++IRef;
870       ++InitsRef;
871     }
872   }
873   return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
874 }
875 
876 void CodeGenFunction::EmitOMPPrivateClause(
877     const OMPExecutableDirective &D,
878     CodeGenFunction::OMPPrivateScope &PrivateScope) {
879   if (!HaveInsertPoint())
880     return;
881   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
882   for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
883     auto IRef = C->varlist_begin();
884     for (const Expr *IInit : C->private_copies()) {
885       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
886       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
887         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
888         bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
889           // Emit private VarDecl with copy init.
890           EmitDecl(*VD);
891           return GetAddrOfLocalVar(VD);
892         });
893         assert(IsRegistered && "private var already registered as private");
894         // Silence the warning about unused variable.
895         (void)IsRegistered;
896       }
897       ++IRef;
898     }
899   }
900 }
901 
902 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
903   if (!HaveInsertPoint())
904     return false;
905   // threadprivate_var1 = master_threadprivate_var1;
906   // operator=(threadprivate_var2, master_threadprivate_var2);
907   // ...
908   // __kmpc_barrier(&loc, global_tid);
909   llvm::DenseSet<const VarDecl *> CopiedVars;
910   llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
911   for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
912     auto IRef = C->varlist_begin();
913     auto ISrcRef = C->source_exprs().begin();
914     auto IDestRef = C->destination_exprs().begin();
915     for (const Expr *AssignOp : C->assignment_ops()) {
916       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
917       QualType Type = VD->getType();
918       if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
919         // Get the address of the master variable. If we are emitting code with
920         // TLS support, the address is passed from the master as field in the
921         // captured declaration.
922         Address MasterAddr = Address::invalid();
923         if (getLangOpts().OpenMPUseTLS &&
924             getContext().getTargetInfo().isTLSSupported()) {
925           assert(CapturedStmtInfo->lookup(VD) &&
926                  "Copyin threadprivates should have been captured!");
927           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
928                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
929           MasterAddr = EmitLValue(&DRE).getAddress();
930           LocalDeclMap.erase(VD);
931         } else {
932           MasterAddr =
933             Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
934                                         : CGM.GetAddrOfGlobal(VD),
935                     getContext().getDeclAlign(VD));
936         }
937         // Get the address of the threadprivate variable.
938         Address PrivateAddr = EmitLValue(*IRef).getAddress();
939         if (CopiedVars.size() == 1) {
940           // At first check if current thread is a master thread. If it is, no
941           // need to copy data.
942           CopyBegin = createBasicBlock("copyin.not.master");
943           CopyEnd = createBasicBlock("copyin.not.master.end");
944           Builder.CreateCondBr(
945               Builder.CreateICmpNE(
946                   Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
947                   Builder.CreatePtrToInt(PrivateAddr.getPointer(),
948                                          CGM.IntPtrTy)),
949               CopyBegin, CopyEnd);
950           EmitBlock(CopyBegin);
951         }
952         const auto *SrcVD =
953             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
954         const auto *DestVD =
955             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
956         EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
957       }
958       ++IRef;
959       ++ISrcRef;
960       ++IDestRef;
961     }
962   }
963   if (CopyEnd) {
964     // Exit out of copying procedure for non-master thread.
965     EmitBlock(CopyEnd, /*IsFinished=*/true);
966     return true;
967   }
968   return false;
969 }
970 
971 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
972     const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
973   if (!HaveInsertPoint())
974     return false;
975   bool HasAtLeastOneLastprivate = false;
976   llvm::DenseSet<const VarDecl *> SIMDLCVs;
977   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
978     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
979     for (const Expr *C : LoopDirective->counters()) {
980       SIMDLCVs.insert(
981           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
982     }
983   }
984   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
985   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
986     HasAtLeastOneLastprivate = true;
987     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
988         !getLangOpts().OpenMPSimd)
989       break;
990     auto IRef = C->varlist_begin();
991     auto IDestRef = C->destination_exprs().begin();
992     for (const Expr *IInit : C->private_copies()) {
993       // Keep the address of the original variable for future update at the end
994       // of the loop.
995       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
996       // Taskloops do not require additional initialization, it is done in
997       // runtime support library.
998       if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
999         const auto *DestVD =
1000             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1001         PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
1002           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1003                           /*RefersToEnclosingVariableOrCapture=*/
1004                               CapturedStmtInfo->lookup(OrigVD) != nullptr,
1005                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1006           return EmitLValue(&DRE).getAddress();
1007         });
1008         // Check if the variable is also a firstprivate: in this case IInit is
1009         // not generated. Initialization of this variable will happen in codegen
1010         // for 'firstprivate' clause.
1011         if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1012           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1013           bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
1014             // Emit private VarDecl with copy init.
1015             EmitDecl(*VD);
1016             return GetAddrOfLocalVar(VD);
1017           });
1018           assert(IsRegistered &&
1019                  "lastprivate var already registered as private");
1020           (void)IsRegistered;
1021         }
1022       }
1023       ++IRef;
1024       ++IDestRef;
1025     }
1026   }
1027   return HasAtLeastOneLastprivate;
1028 }
1029 
1030 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
1031     const OMPExecutableDirective &D, bool NoFinals,
1032     llvm::Value *IsLastIterCond) {
1033   if (!HaveInsertPoint())
1034     return;
1035   // Emit following code:
1036   // if (<IsLastIterCond>) {
1037   //   orig_var1 = private_orig_var1;
1038   //   ...
1039   //   orig_varn = private_orig_varn;
1040   // }
1041   llvm::BasicBlock *ThenBB = nullptr;
1042   llvm::BasicBlock *DoneBB = nullptr;
1043   if (IsLastIterCond) {
1044     ThenBB = createBasicBlock(".omp.lastprivate.then");
1045     DoneBB = createBasicBlock(".omp.lastprivate.done");
1046     Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1047     EmitBlock(ThenBB);
1048   }
1049   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1050   llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1051   if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1052     auto IC = LoopDirective->counters().begin();
1053     for (const Expr *F : LoopDirective->finals()) {
1054       const auto *D =
1055           cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1056       if (NoFinals)
1057         AlreadyEmittedVars.insert(D);
1058       else
1059         LoopCountersAndUpdates[D] = F;
1060       ++IC;
1061     }
1062   }
1063   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1064     auto IRef = C->varlist_begin();
1065     auto ISrcRef = C->source_exprs().begin();
1066     auto IDestRef = C->destination_exprs().begin();
1067     for (const Expr *AssignOp : C->assignment_ops()) {
1068       const auto *PrivateVD =
1069           cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1070       QualType Type = PrivateVD->getType();
1071       const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1072       if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1073         // If lastprivate variable is a loop control variable for loop-based
1074         // directive, update its value before copyin back to original
1075         // variable.
1076         if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1077           EmitIgnoredExpr(FinalExpr);
1078         const auto *SrcVD =
1079             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1080         const auto *DestVD =
1081             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1082         // Get the address of the original variable.
1083         Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1084         // Get the address of the private variable.
1085         Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1086         if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1087           PrivateAddr =
1088               Address(Builder.CreateLoad(PrivateAddr),
1089                       getNaturalTypeAlignment(RefTy->getPointeeType()));
1090         EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1091       }
1092       ++IRef;
1093       ++ISrcRef;
1094       ++IDestRef;
1095     }
1096     if (const Expr *PostUpdate = C->getPostUpdateExpr())
1097       EmitIgnoredExpr(PostUpdate);
1098   }
1099   if (IsLastIterCond)
1100     EmitBlock(DoneBB, /*IsFinished=*/true);
1101 }
1102 
1103 void CodeGenFunction::EmitOMPReductionClauseInit(
1104     const OMPExecutableDirective &D,
1105     CodeGenFunction::OMPPrivateScope &PrivateScope) {
1106   if (!HaveInsertPoint())
1107     return;
1108   SmallVector<const Expr *, 4> Shareds;
1109   SmallVector<const Expr *, 4> Privates;
1110   SmallVector<const Expr *, 4> ReductionOps;
1111   SmallVector<const Expr *, 4> LHSs;
1112   SmallVector<const Expr *, 4> RHSs;
1113   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1114     auto IPriv = C->privates().begin();
1115     auto IRed = C->reduction_ops().begin();
1116     auto ILHS = C->lhs_exprs().begin();
1117     auto IRHS = C->rhs_exprs().begin();
1118     for (const Expr *Ref : C->varlists()) {
1119       Shareds.emplace_back(Ref);
1120       Privates.emplace_back(*IPriv);
1121       ReductionOps.emplace_back(*IRed);
1122       LHSs.emplace_back(*ILHS);
1123       RHSs.emplace_back(*IRHS);
1124       std::advance(IPriv, 1);
1125       std::advance(IRed, 1);
1126       std::advance(ILHS, 1);
1127       std::advance(IRHS, 1);
1128     }
1129   }
1130   ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
1131   unsigned Count = 0;
1132   auto ILHS = LHSs.begin();
1133   auto IRHS = RHSs.begin();
1134   auto IPriv = Privates.begin();
1135   for (const Expr *IRef : Shareds) {
1136     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1137     // Emit private VarDecl with reduction init.
1138     RedCG.emitSharedLValue(*this, Count);
1139     RedCG.emitAggregateType(*this, Count);
1140     AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1141     RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1142                              RedCG.getSharedLValue(Count),
1143                              [&Emission](CodeGenFunction &CGF) {
1144                                CGF.EmitAutoVarInit(Emission);
1145                                return true;
1146                              });
1147     EmitAutoVarCleanups(Emission);
1148     Address BaseAddr = RedCG.adjustPrivateAddress(
1149         *this, Count, Emission.getAllocatedAddress());
1150     bool IsRegistered = PrivateScope.addPrivate(
1151         RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
1152     assert(IsRegistered && "private var already registered as private");
1153     // Silence the warning about unused variable.
1154     (void)IsRegistered;
1155 
1156     const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1157     const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1158     QualType Type = PrivateVD->getType();
1159     bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1160     if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1161       // Store the address of the original variable associated with the LHS
1162       // implicit variable.
1163       PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
1164         return RedCG.getSharedLValue(Count).getAddress();
1165       });
1166       PrivateScope.addPrivate(
1167           RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
1168     } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1169                isa<ArraySubscriptExpr>(IRef)) {
1170       // Store the address of the original variable associated with the LHS
1171       // implicit variable.
1172       PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
1173         return RedCG.getSharedLValue(Count).getAddress();
1174       });
1175       PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
1176         return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1177                                             ConvertTypeForMem(RHSVD->getType()),
1178                                             "rhs.begin");
1179       });
1180     } else {
1181       QualType Type = PrivateVD->getType();
1182       bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1183       Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
1184       // Store the address of the original variable associated with the LHS
1185       // implicit variable.
1186       if (IsArray) {
1187         OriginalAddr = Builder.CreateElementBitCast(
1188             OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1189       }
1190       PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
1191       PrivateScope.addPrivate(
1192           RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
1193             return IsArray
1194                        ? Builder.CreateElementBitCast(
1195                              GetAddrOfLocalVar(PrivateVD),
1196                              ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1197                        : GetAddrOfLocalVar(PrivateVD);
1198           });
1199     }
1200     ++ILHS;
1201     ++IRHS;
1202     ++IPriv;
1203     ++Count;
1204   }
1205 }
1206 
1207 void CodeGenFunction::EmitOMPReductionClauseFinal(
1208     const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1209   if (!HaveInsertPoint())
1210     return;
1211   llvm::SmallVector<const Expr *, 8> Privates;
1212   llvm::SmallVector<const Expr *, 8> LHSExprs;
1213   llvm::SmallVector<const Expr *, 8> RHSExprs;
1214   llvm::SmallVector<const Expr *, 8> ReductionOps;
1215   bool HasAtLeastOneReduction = false;
1216   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1217     HasAtLeastOneReduction = true;
1218     Privates.append(C->privates().begin(), C->privates().end());
1219     LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1220     RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1221     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1222   }
1223   if (HasAtLeastOneReduction) {
1224     bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1225                       isOpenMPParallelDirective(D.getDirectiveKind()) ||
1226                       ReductionKind == OMPD_simd;
1227     bool SimpleReduction = ReductionKind == OMPD_simd;
1228     // Emit nowait reduction if nowait clause is present or directive is a
1229     // parallel directive (it always has implicit barrier).
1230     CGM.getOpenMPRuntime().emitReduction(
1231         *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1232         {WithNowait, SimpleReduction, ReductionKind});
1233   }
1234 }
1235 
1236 static void emitPostUpdateForReductionClause(
1237     CodeGenFunction &CGF, const OMPExecutableDirective &D,
1238     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1239   if (!CGF.HaveInsertPoint())
1240     return;
1241   llvm::BasicBlock *DoneBB = nullptr;
1242   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1243     if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1244       if (!DoneBB) {
1245         if (llvm::Value *Cond = CondGen(CGF)) {
1246           // If the first post-update expression is found, emit conditional
1247           // block if it was requested.
1248           llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1249           DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1250           CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1251           CGF.EmitBlock(ThenBB);
1252         }
1253       }
1254       CGF.EmitIgnoredExpr(PostUpdate);
1255     }
1256   }
1257   if (DoneBB)
1258     CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1259 }
1260 
1261 namespace {
1262 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1263 /// parallel function. This is necessary for combined constructs such as
1264 /// 'distribute parallel for'
1265 typedef llvm::function_ref<void(CodeGenFunction &,
1266                                 const OMPExecutableDirective &,
1267                                 llvm::SmallVectorImpl<llvm::Value *> &)>
1268     CodeGenBoundParametersTy;
1269 } // anonymous namespace
1270 
1271 static void emitCommonOMPParallelDirective(
1272     CodeGenFunction &CGF, const OMPExecutableDirective &S,
1273     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1274     const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1275   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1276   llvm::Function *OutlinedFn =
1277       CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1278           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1279   if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1280     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1281     llvm::Value *NumThreads =
1282         CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1283                            /*IgnoreResultAssign=*/true);
1284     CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1285         CGF, NumThreads, NumThreadsClause->getBeginLoc());
1286   }
1287   if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1288     CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1289     CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1290         CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1291   }
1292   const Expr *IfCond = nullptr;
1293   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1294     if (C->getNameModifier() == OMPD_unknown ||
1295         C->getNameModifier() == OMPD_parallel) {
1296       IfCond = C->getCondition();
1297       break;
1298     }
1299   }
1300 
1301   OMPParallelScope Scope(CGF, S);
1302   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1303   // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1304   // lower and upper bounds with the pragma 'for' chunking mechanism.
1305   // The following lambda takes care of appending the lower and upper bound
1306   // parameters when necessary
1307   CodeGenBoundParameters(CGF, S, CapturedVars);
1308   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1309   CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1310                                               CapturedVars, IfCond);
1311 }
1312 
1313 static void emitEmptyBoundParameters(CodeGenFunction &,
1314                                      const OMPExecutableDirective &,
1315                                      llvm::SmallVectorImpl<llvm::Value *> &) {}
1316 
1317 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1318   // Emit parallel region as a standalone region.
1319   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1320     Action.Enter(CGF);
1321     OMPPrivateScope PrivateScope(CGF);
1322     bool Copyins = CGF.EmitOMPCopyinClause(S);
1323     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1324     if (Copyins) {
1325       // Emit implicit barrier to synchronize threads and avoid data races on
1326       // propagation master's thread values of threadprivate variables to local
1327       // instances of that variables of all other implicit threads.
1328       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1329           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1330           /*ForceSimpleCall=*/true);
1331     }
1332     CGF.EmitOMPPrivateClause(S, PrivateScope);
1333     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1334     (void)PrivateScope.Privatize();
1335     CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
1336     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1337   };
1338   emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1339                                  emitEmptyBoundParameters);
1340   emitPostUpdateForReductionClause(*this, S,
1341                                    [](CodeGenFunction &) { return nullptr; });
1342 }
1343 
1344 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1345                      int MaxLevel, int Level = 0) {
1346   assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1347   const Stmt *SimplifiedS = S->IgnoreContainers();
1348   if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1349     PrettyStackTraceLoc CrashInfo(
1350         CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1351         "LLVM IR generation of compound statement ('{}')");
1352 
1353     // Keep track of the current cleanup stack depth, including debug scopes.
1354     CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1355     for (const Stmt *CurStmt : CS->body())
1356       emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1357     return;
1358   }
1359   if (SimplifiedS == NextLoop) {
1360     if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1361       S = For->getBody();
1362     } else {
1363       assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1364              "Expected canonical for loop or range-based for loop.");
1365       const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1366       CGF.EmitStmt(CXXFor->getLoopVarStmt());
1367       S = CXXFor->getBody();
1368     }
1369     if (Level + 1 < MaxLevel) {
1370       NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1371           S, /*TryImperfectlyNestedLoops=*/true);
1372       emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1373       return;
1374     }
1375   }
1376   CGF.EmitStmt(S);
1377 }
1378 
1379 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1380                                       JumpDest LoopExit) {
1381   RunCleanupsScope BodyScope(*this);
1382   // Update counters values on current iteration.
1383   for (const Expr *UE : D.updates())
1384     EmitIgnoredExpr(UE);
1385   // Update the linear variables.
1386   // In distribute directives only loop counters may be marked as linear, no
1387   // need to generate the code for them.
1388   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1389     for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1390       for (const Expr *UE : C->updates())
1391         EmitIgnoredExpr(UE);
1392     }
1393   }
1394 
1395   // On a continue in the body, jump to the end.
1396   JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
1397   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1398   for (const Expr *E : D.finals_conditions()) {
1399     if (!E)
1400       continue;
1401     // Check that loop counter in non-rectangular nest fits into the iteration
1402     // space.
1403     llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1404     EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1405                          getProfileCount(D.getBody()));
1406     EmitBlock(NextBB);
1407   }
1408   // Emit loop variables for C++ range loops.
1409   const Stmt *Body =
1410       D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1411   // Emit loop body.
1412   emitBody(*this, Body,
1413            OMPLoopDirective::tryToFindNextInnerLoop(
1414                Body, /*TryImperfectlyNestedLoops=*/true),
1415            D.getCollapsedNumber());
1416 
1417   // The end (updates/cleanups).
1418   EmitBlock(Continue.getBlock());
1419   BreakContinueStack.pop_back();
1420 }
1421 
1422 void CodeGenFunction::EmitOMPInnerLoop(
1423     const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1424     const Expr *IncExpr,
1425     const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
1426     const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
1427   auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1428 
1429   // Start the loop with a block that tests the condition.
1430   auto CondBlock = createBasicBlock("omp.inner.for.cond");
1431   EmitBlock(CondBlock);
1432   const SourceRange R = S.getSourceRange();
1433   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1434                  SourceLocToDebugLoc(R.getEnd()));
1435 
1436   // If there are any cleanups between here and the loop-exit scope,
1437   // create a block to stage a loop exit along.
1438   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1439   if (RequiresCleanup)
1440     ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1441 
1442   llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
1443 
1444   // Emit condition.
1445   EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1446   if (ExitBlock != LoopExit.getBlock()) {
1447     EmitBlock(ExitBlock);
1448     EmitBranchThroughCleanup(LoopExit);
1449   }
1450 
1451   EmitBlock(LoopBody);
1452   incrementProfileCounter(&S);
1453 
1454   // Create a block for the increment.
1455   JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1456   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1457 
1458   BodyGen(*this);
1459 
1460   // Emit "IV = IV + 1" and a back-edge to the condition block.
1461   EmitBlock(Continue.getBlock());
1462   EmitIgnoredExpr(IncExpr);
1463   PostIncGen(*this);
1464   BreakContinueStack.pop_back();
1465   EmitBranch(CondBlock);
1466   LoopStack.pop();
1467   // Emit the fall-through block.
1468   EmitBlock(LoopExit.getBlock());
1469 }
1470 
1471 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1472   if (!HaveInsertPoint())
1473     return false;
1474   // Emit inits for the linear variables.
1475   bool HasLinears = false;
1476   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1477     for (const Expr *Init : C->inits()) {
1478       HasLinears = true;
1479       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1480       if (const auto *Ref =
1481               dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
1482         AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1483         const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
1484         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1485                         CapturedStmtInfo->lookup(OrigVD) != nullptr,
1486                         VD->getInit()->getType(), VK_LValue,
1487                         VD->getInit()->getExprLoc());
1488         EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
1489                                                 VD->getType()),
1490                        /*capturedByInit=*/false);
1491         EmitAutoVarCleanups(Emission);
1492       } else {
1493         EmitVarDecl(*VD);
1494       }
1495     }
1496     // Emit the linear steps for the linear clauses.
1497     // If a step is not constant, it is pre-calculated before the loop.
1498     if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1499       if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1500         EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1501         // Emit calculation of the linear step.
1502         EmitIgnoredExpr(CS);
1503       }
1504   }
1505   return HasLinears;
1506 }
1507 
1508 void CodeGenFunction::EmitOMPLinearClauseFinal(
1509     const OMPLoopDirective &D,
1510     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1511   if (!HaveInsertPoint())
1512     return;
1513   llvm::BasicBlock *DoneBB = nullptr;
1514   // Emit the final values of the linear variables.
1515   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1516     auto IC = C->varlist_begin();
1517     for (const Expr *F : C->finals()) {
1518       if (!DoneBB) {
1519         if (llvm::Value *Cond = CondGen(*this)) {
1520           // If the first post-update expression is found, emit conditional
1521           // block if it was requested.
1522           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
1523           DoneBB = createBasicBlock(".omp.linear.pu.done");
1524           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1525           EmitBlock(ThenBB);
1526         }
1527       }
1528       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1529       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1530                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
1531                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1532       Address OrigAddr = EmitLValue(&DRE).getAddress();
1533       CodeGenFunction::OMPPrivateScope VarScope(*this);
1534       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1535       (void)VarScope.Privatize();
1536       EmitIgnoredExpr(F);
1537       ++IC;
1538     }
1539     if (const Expr *PostUpdate = C->getPostUpdateExpr())
1540       EmitIgnoredExpr(PostUpdate);
1541   }
1542   if (DoneBB)
1543     EmitBlock(DoneBB, /*IsFinished=*/true);
1544 }
1545 
1546 static void emitAlignedClause(CodeGenFunction &CGF,
1547                               const OMPExecutableDirective &D) {
1548   if (!CGF.HaveInsertPoint())
1549     return;
1550   for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1551     llvm::APInt ClauseAlignment(64, 0);
1552     if (const Expr *AlignmentExpr = Clause->getAlignment()) {
1553       auto *AlignmentCI =
1554           cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1555       ClauseAlignment = AlignmentCI->getValue();
1556     }
1557     for (const Expr *E : Clause->varlists()) {
1558       llvm::APInt Alignment(ClauseAlignment);
1559       if (Alignment == 0) {
1560         // OpenMP [2.8.1, Description]
1561         // If no optional parameter is specified, implementation-defined default
1562         // alignments for SIMD instructions on the target platforms are assumed.
1563         Alignment =
1564             CGF.getContext()
1565                 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1566                     E->getType()->getPointeeType()))
1567                 .getQuantity();
1568       }
1569       assert((Alignment == 0 || Alignment.isPowerOf2()) &&
1570              "alignment is not power of 2");
1571       if (Alignment != 0) {
1572         llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1573         CGF.EmitAlignmentAssumption(
1574             PtrValue, E, /*No second loc needed*/ SourceLocation(),
1575             llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
1576       }
1577     }
1578   }
1579 }
1580 
1581 void CodeGenFunction::EmitOMPPrivateLoopCounters(
1582     const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
1583   if (!HaveInsertPoint())
1584     return;
1585   auto I = S.private_counters().begin();
1586   for (const Expr *E : S.counters()) {
1587     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1588     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1589     // Emit var without initialization.
1590     AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
1591     EmitAutoVarCleanups(VarEmission);
1592     LocalDeclMap.erase(PrivateVD);
1593     (void)LoopScope.addPrivate(VD, [&VarEmission]() {
1594       return VarEmission.getAllocatedAddress();
1595     });
1596     if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
1597         VD->hasGlobalStorage()) {
1598       (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
1599         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
1600                         LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
1601                         E->getType(), VK_LValue, E->getExprLoc());
1602         return EmitLValue(&DRE).getAddress();
1603       });
1604     } else {
1605       (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
1606         return VarEmission.getAllocatedAddress();
1607       });
1608     }
1609     ++I;
1610   }
1611   // Privatize extra loop counters used in loops for ordered(n) clauses.
1612   for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
1613     if (!C->getNumForLoops())
1614       continue;
1615     for (unsigned I = S.getCollapsedNumber(),
1616                   E = C->getLoopNumIterations().size();
1617          I < E; ++I) {
1618       const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
1619       const auto *VD = cast<VarDecl>(DRE->getDecl());
1620       // Override only those variables that can be captured to avoid re-emission
1621       // of the variables declared within the loops.
1622       if (DRE->refersToEnclosingVariableOrCapture()) {
1623         (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
1624           return CreateMemTemp(DRE->getType(), VD->getName());
1625         });
1626       }
1627     }
1628   }
1629 }
1630 
1631 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1632                         const Expr *Cond, llvm::BasicBlock *TrueBlock,
1633                         llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1634   if (!CGF.HaveInsertPoint())
1635     return;
1636   {
1637     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1638     CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
1639     (void)PreCondScope.Privatize();
1640     // Get initial values of real counters.
1641     for (const Expr *I : S.inits()) {
1642       CGF.EmitIgnoredExpr(I);
1643     }
1644   }
1645   // Create temp loop control variables with their init values to support
1646   // non-rectangular loops.
1647   CodeGenFunction::OMPMapVars PreCondVars;
1648   for (const Expr * E: S.dependent_counters()) {
1649     if (!E)
1650       continue;
1651     assert(!E->getType().getNonReferenceType()->isRecordType() &&
1652            "dependent counter must not be an iterator.");
1653     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1654     Address CounterAddr =
1655         CGF.CreateMemTemp(VD->getType().getNonReferenceType());
1656     (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
1657   }
1658   (void)PreCondVars.apply(CGF);
1659   for (const Expr *E : S.dependent_inits()) {
1660     if (!E)
1661       continue;
1662     CGF.EmitIgnoredExpr(E);
1663   }
1664   // Check that loop is executed at least one time.
1665   CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1666   PreCondVars.restore(CGF);
1667 }
1668 
1669 void CodeGenFunction::EmitOMPLinearClause(
1670     const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
1671   if (!HaveInsertPoint())
1672     return;
1673   llvm::DenseSet<const VarDecl *> SIMDLCVs;
1674   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1675     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1676     for (const Expr *C : LoopDirective->counters()) {
1677       SIMDLCVs.insert(
1678           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1679     }
1680   }
1681   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1682     auto CurPrivate = C->privates().begin();
1683     for (const Expr *E : C->varlists()) {
1684       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1685       const auto *PrivateVD =
1686           cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1687       if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
1688         bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
1689           // Emit private VarDecl with copy init.
1690           EmitVarDecl(*PrivateVD);
1691           return GetAddrOfLocalVar(PrivateVD);
1692         });
1693         assert(IsRegistered && "linear var already registered as private");
1694         // Silence the warning about unused variable.
1695         (void)IsRegistered;
1696       } else {
1697         EmitVarDecl(*PrivateVD);
1698       }
1699       ++CurPrivate;
1700     }
1701   }
1702 }
1703 
1704 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1705                                      const OMPExecutableDirective &D,
1706                                      bool IsMonotonic) {
1707   if (!CGF.HaveInsertPoint())
1708     return;
1709   if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1710     RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1711                                  /*ignoreResult=*/true);
1712     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1713     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1714     // In presence of finite 'safelen', it may be unsafe to mark all
1715     // the memory instructions parallel, because loop-carried
1716     // dependences of 'safelen' iterations are possible.
1717     if (!IsMonotonic)
1718       CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1719   } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1720     RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1721                                  /*ignoreResult=*/true);
1722     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1723     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1724     // In presence of finite 'safelen', it may be unsafe to mark all
1725     // the memory instructions parallel, because loop-carried
1726     // dependences of 'safelen' iterations are possible.
1727     CGF.LoopStack.setParallel(/*Enable=*/false);
1728   }
1729 }
1730 
1731 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1732                                       bool IsMonotonic) {
1733   // Walk clauses and process safelen/lastprivate.
1734   LoopStack.setParallel(!IsMonotonic);
1735   LoopStack.setVectorizeEnable();
1736   emitSimdlenSafelenClause(*this, D, IsMonotonic);
1737 }
1738 
1739 void CodeGenFunction::EmitOMPSimdFinal(
1740     const OMPLoopDirective &D,
1741     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1742   if (!HaveInsertPoint())
1743     return;
1744   llvm::BasicBlock *DoneBB = nullptr;
1745   auto IC = D.counters().begin();
1746   auto IPC = D.private_counters().begin();
1747   for (const Expr *F : D.finals()) {
1748     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1749     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
1750     const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
1751     if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
1752         OrigVD->hasGlobalStorage() || CED) {
1753       if (!DoneBB) {
1754         if (llvm::Value *Cond = CondGen(*this)) {
1755           // If the first post-update expression is found, emit conditional
1756           // block if it was requested.
1757           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
1758           DoneBB = createBasicBlock(".omp.final.done");
1759           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1760           EmitBlock(ThenBB);
1761         }
1762       }
1763       Address OrigAddr = Address::invalid();
1764       if (CED) {
1765         OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
1766       } else {
1767         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
1768                         /*RefersToEnclosingVariableOrCapture=*/false,
1769                         (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
1770         OrigAddr = EmitLValue(&DRE).getAddress();
1771       }
1772       OMPPrivateScope VarScope(*this);
1773       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
1774       (void)VarScope.Privatize();
1775       EmitIgnoredExpr(F);
1776     }
1777     ++IC;
1778     ++IPC;
1779   }
1780   if (DoneBB)
1781     EmitBlock(DoneBB, /*IsFinished=*/true);
1782 }
1783 
1784 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
1785                                          const OMPLoopDirective &S,
1786                                          CodeGenFunction::JumpDest LoopExit) {
1787   CGF.EmitOMPLoopBody(S, LoopExit);
1788   CGF.EmitStopPoint(&S);
1789 }
1790 
1791 /// Emit a helper variable and return corresponding lvalue.
1792 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1793                                const DeclRefExpr *Helper) {
1794   auto VDecl = cast<VarDecl>(Helper->getDecl());
1795   CGF.EmitVarDecl(*VDecl);
1796   return CGF.EmitLValue(Helper);
1797 }
1798 
1799 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
1800                               PrePostActionTy &Action) {
1801   Action.Enter(CGF);
1802   assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
1803          "Expected simd directive");
1804   OMPLoopScope PreInitScope(CGF, S);
1805   // if (PreCond) {
1806   //   for (IV in 0..LastIteration) BODY;
1807   //   <Final counter/linear vars updates>;
1808   // }
1809   //
1810   if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
1811       isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
1812       isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
1813     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1814     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1815   }
1816 
1817   // Emit: if (PreCond) - begin.
1818   // If the condition constant folds and can be elided, avoid emitting the
1819   // whole loop.
1820   bool CondConstant;
1821   llvm::BasicBlock *ContBlock = nullptr;
1822   if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1823     if (!CondConstant)
1824       return;
1825   } else {
1826     llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
1827     ContBlock = CGF.createBasicBlock("simd.if.end");
1828     emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1829                 CGF.getProfileCount(&S));
1830     CGF.EmitBlock(ThenBlock);
1831     CGF.incrementProfileCounter(&S);
1832   }
1833 
1834   // Emit the loop iteration variable.
1835   const Expr *IVExpr = S.getIterationVariable();
1836   const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1837   CGF.EmitVarDecl(*IVDecl);
1838   CGF.EmitIgnoredExpr(S.getInit());
1839 
1840   // Emit the iterations count variable.
1841   // If it is not a variable, Sema decided to calculate iterations count on
1842   // each iteration (e.g., it is foldable into a constant).
1843   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1844     CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1845     // Emit calculation of the iterations count.
1846     CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1847   }
1848 
1849   emitAlignedClause(CGF, S);
1850   (void)CGF.EmitOMPLinearClauseInit(S);
1851   {
1852     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1853     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
1854     CGF.EmitOMPLinearClause(S, LoopScope);
1855     CGF.EmitOMPPrivateClause(S, LoopScope);
1856     CGF.EmitOMPReductionClauseInit(S, LoopScope);
1857     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1858     (void)LoopScope.Privatize();
1859     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
1860       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
1861 
1862     auto &&ThenGen = [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
1863       CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1864       CGF.EmitOMPSimdInit(S);
1865 
1866       CGF.EmitOMPInnerLoop(
1867           S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1868           [&S](CodeGenFunction &CGF) {
1869             CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1870             CGF.EmitStopPoint(&S);
1871           },
1872           [](CodeGenFunction &) {});
1873     };
1874     auto &&ElseGen = [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
1875       CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
1876       CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
1877 
1878       CGF.EmitOMPInnerLoop(
1879           S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1880           [&S](CodeGenFunction &CGF) {
1881             CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
1882             CGF.EmitStopPoint(&S);
1883           },
1884           [](CodeGenFunction &) {});
1885     };
1886     const Expr *IfCond = nullptr;
1887     for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1888       if (CGF.getLangOpts().OpenMP >= 50 &&
1889           (C->getNameModifier() == OMPD_unknown ||
1890            C->getNameModifier() == OMPD_simd)) {
1891         IfCond = C->getCondition();
1892         break;
1893       }
1894     }
1895     if (IfCond) {
1896       CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
1897     } else {
1898       RegionCodeGenTy ThenRCG(ThenGen);
1899       ThenRCG(CGF);
1900     }
1901     CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
1902     // Emit final copy of the lastprivate variables at the end of loops.
1903     if (HasLastprivateClause)
1904       CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
1905     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
1906     emitPostUpdateForReductionClause(CGF, S,
1907                                      [](CodeGenFunction &) { return nullptr; });
1908   }
1909   CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
1910   // Emit: if (PreCond) - end.
1911   if (ContBlock) {
1912     CGF.EmitBranch(ContBlock);
1913     CGF.EmitBlock(ContBlock, true);
1914   }
1915 }
1916 
1917 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1918   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1919     emitOMPSimdRegion(CGF, S, Action);
1920   };
1921   OMPLexicalScope Scope(*this, S, OMPD_unknown);
1922   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1923 }
1924 
1925 void CodeGenFunction::EmitOMPOuterLoop(
1926     bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
1927     CodeGenFunction::OMPPrivateScope &LoopScope,
1928     const CodeGenFunction::OMPLoopArguments &LoopArgs,
1929     const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
1930     const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
1931   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
1932 
1933   const Expr *IVExpr = S.getIterationVariable();
1934   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1935   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1936 
1937   JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1938 
1939   // Start the loop with a block that tests the condition.
1940   llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
1941   EmitBlock(CondBlock);
1942   const SourceRange R = S.getSourceRange();
1943   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
1944                  SourceLocToDebugLoc(R.getEnd()));
1945 
1946   llvm::Value *BoolCondVal = nullptr;
1947   if (!DynamicOrOrdered) {
1948     // UB = min(UB, GlobalUB) or
1949     // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
1950     // 'distribute parallel for')
1951     EmitIgnoredExpr(LoopArgs.EUB);
1952     // IV = LB
1953     EmitIgnoredExpr(LoopArgs.Init);
1954     // IV < UB
1955     BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
1956   } else {
1957     BoolCondVal =
1958         RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
1959                        LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
1960   }
1961 
1962   // If there are any cleanups between here and the loop-exit scope,
1963   // create a block to stage a loop exit along.
1964   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
1965   if (LoopScope.requiresCleanups())
1966     ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1967 
1968   llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
1969   Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1970   if (ExitBlock != LoopExit.getBlock()) {
1971     EmitBlock(ExitBlock);
1972     EmitBranchThroughCleanup(LoopExit);
1973   }
1974   EmitBlock(LoopBody);
1975 
1976   // Emit "IV = LB" (in case of static schedule, we have already calculated new
1977   // LB for loop condition and emitted it above).
1978   if (DynamicOrOrdered)
1979     EmitIgnoredExpr(LoopArgs.Init);
1980 
1981   // Create a block for the increment.
1982   JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1983   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1984 
1985   // Generate !llvm.loop.parallel metadata for loads and stores for loops
1986   // with dynamic/guided scheduling and without ordered clause.
1987   if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1988     LoopStack.setParallel(!IsMonotonic);
1989   else
1990     EmitOMPSimdInit(S, IsMonotonic);
1991 
1992   SourceLocation Loc = S.getBeginLoc();
1993 
1994   // when 'distribute' is not combined with a 'for':
1995   // while (idx <= UB) { BODY; ++idx; }
1996   // when 'distribute' is combined with a 'for'
1997   // (e.g. 'distribute parallel for')
1998   // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
1999   EmitOMPInnerLoop(
2000       S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2001       [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2002         CodeGenLoop(CGF, S, LoopExit);
2003       },
2004       [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2005         CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2006       });
2007 
2008   EmitBlock(Continue.getBlock());
2009   BreakContinueStack.pop_back();
2010   if (!DynamicOrOrdered) {
2011     // Emit "LB = LB + Stride", "UB = UB + Stride".
2012     EmitIgnoredExpr(LoopArgs.NextLB);
2013     EmitIgnoredExpr(LoopArgs.NextUB);
2014   }
2015 
2016   EmitBranch(CondBlock);
2017   LoopStack.pop();
2018   // Emit the fall-through block.
2019   EmitBlock(LoopExit.getBlock());
2020 
2021   // Tell the runtime we are done.
2022   auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2023     if (!DynamicOrOrdered)
2024       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2025                                                      S.getDirectiveKind());
2026   };
2027   OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2028 }
2029 
2030 void CodeGenFunction::EmitOMPForOuterLoop(
2031     const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
2032     const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2033     const OMPLoopArguments &LoopArgs,
2034     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2035   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2036 
2037   // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
2038   const bool DynamicOrOrdered =
2039       Ordered || RT.isDynamic(ScheduleKind.Schedule);
2040 
2041   assert((Ordered ||
2042           !RT.isStaticNonchunked(ScheduleKind.Schedule,
2043                                  LoopArgs.Chunk != nullptr)) &&
2044          "static non-chunked schedule does not need outer loop");
2045 
2046   // Emit outer loop.
2047   //
2048   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2049   // When schedule(dynamic,chunk_size) is specified, the iterations are
2050   // distributed to threads in the team in chunks as the threads request them.
2051   // Each thread executes a chunk of iterations, then requests another chunk,
2052   // until no chunks remain to be distributed. Each chunk contains chunk_size
2053   // iterations, except for the last chunk to be distributed, which may have
2054   // fewer iterations. When no chunk_size is specified, it defaults to 1.
2055   //
2056   // When schedule(guided,chunk_size) is specified, the iterations are assigned
2057   // to threads in the team in chunks as the executing threads request them.
2058   // Each thread executes a chunk of iterations, then requests another chunk,
2059   // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2060   // each chunk is proportional to the number of unassigned iterations divided
2061   // by the number of threads in the team, decreasing to 1. For a chunk_size
2062   // with value k (greater than 1), the size of each chunk is determined in the
2063   // same way, with the restriction that the chunks do not contain fewer than k
2064   // iterations (except for the last chunk to be assigned, which may have fewer
2065   // than k iterations).
2066   //
2067   // When schedule(auto) is specified, the decision regarding scheduling is
2068   // delegated to the compiler and/or runtime system. The programmer gives the
2069   // implementation the freedom to choose any possible mapping of iterations to
2070   // threads in the team.
2071   //
2072   // When schedule(runtime) is specified, the decision regarding scheduling is
2073   // deferred until run time, and the schedule and chunk size are taken from the
2074   // run-sched-var ICV. If the ICV is set to auto, the schedule is
2075   // implementation defined
2076   //
2077   // while(__kmpc_dispatch_next(&LB, &UB)) {
2078   //   idx = LB;
2079   //   while (idx <= UB) { BODY; ++idx;
2080   //   __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2081   //   } // inner loop
2082   // }
2083   //
2084   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2085   // When schedule(static, chunk_size) is specified, iterations are divided into
2086   // chunks of size chunk_size, and the chunks are assigned to the threads in
2087   // the team in a round-robin fashion in the order of the thread number.
2088   //
2089   // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2090   //   while (idx <= UB) { BODY; ++idx; } // inner loop
2091   //   LB = LB + ST;
2092   //   UB = UB + ST;
2093   // }
2094   //
2095 
2096   const Expr *IVExpr = S.getIterationVariable();
2097   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2098   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2099 
2100   if (DynamicOrOrdered) {
2101     const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2102         CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
2103     llvm::Value *LBVal = DispatchBounds.first;
2104     llvm::Value *UBVal = DispatchBounds.second;
2105     CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2106                                                              LoopArgs.Chunk};
2107     RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
2108                            IVSigned, Ordered, DipatchRTInputValues);
2109   } else {
2110     CGOpenMPRuntime::StaticRTInput StaticInit(
2111         IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2112         LoopArgs.ST, LoopArgs.Chunk);
2113     RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
2114                          ScheduleKind, StaticInit);
2115   }
2116 
2117   auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2118                                     const unsigned IVSize,
2119                                     const bool IVSigned) {
2120     if (Ordered) {
2121       CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2122                                                             IVSigned);
2123     }
2124   };
2125 
2126   OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2127                                  LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2128   OuterLoopArgs.IncExpr = S.getInc();
2129   OuterLoopArgs.Init = S.getInit();
2130   OuterLoopArgs.Cond = S.getCond();
2131   OuterLoopArgs.NextLB = S.getNextLowerBound();
2132   OuterLoopArgs.NextUB = S.getNextUpperBound();
2133   EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2134                    emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
2135 }
2136 
2137 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2138                              const unsigned IVSize, const bool IVSigned) {}
2139 
2140 void CodeGenFunction::EmitOMPDistributeOuterLoop(
2141     OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2142     OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2143     const CodeGenLoopTy &CodeGenLoopContent) {
2144 
2145   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2146 
2147   // Emit outer loop.
2148   // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2149   // dynamic
2150   //
2151 
2152   const Expr *IVExpr = S.getIterationVariable();
2153   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2154   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2155 
2156   CGOpenMPRuntime::StaticRTInput StaticInit(
2157       IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2158       LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
2159   RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
2160 
2161   // for combined 'distribute' and 'for' the increment expression of distribute
2162   // is stored in DistInc. For 'distribute' alone, it is in Inc.
2163   Expr *IncExpr;
2164   if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2165     IncExpr = S.getDistInc();
2166   else
2167     IncExpr = S.getInc();
2168 
2169   // this routine is shared by 'omp distribute parallel for' and
2170   // 'omp distribute': select the right EUB expression depending on the
2171   // directive
2172   OMPLoopArguments OuterLoopArgs;
2173   OuterLoopArgs.LB = LoopArgs.LB;
2174   OuterLoopArgs.UB = LoopArgs.UB;
2175   OuterLoopArgs.ST = LoopArgs.ST;
2176   OuterLoopArgs.IL = LoopArgs.IL;
2177   OuterLoopArgs.Chunk = LoopArgs.Chunk;
2178   OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2179                           ? S.getCombinedEnsureUpperBound()
2180                           : S.getEnsureUpperBound();
2181   OuterLoopArgs.IncExpr = IncExpr;
2182   OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2183                            ? S.getCombinedInit()
2184                            : S.getInit();
2185   OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2186                            ? S.getCombinedCond()
2187                            : S.getCond();
2188   OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2189                              ? S.getCombinedNextLowerBound()
2190                              : S.getNextLowerBound();
2191   OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2192                              ? S.getCombinedNextUpperBound()
2193                              : S.getNextUpperBound();
2194 
2195   EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
2196                    LoopScope, OuterLoopArgs, CodeGenLoopContent,
2197                    emitEmptyOrdered);
2198 }
2199 
2200 static std::pair<LValue, LValue>
2201 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
2202                                      const OMPExecutableDirective &S) {
2203   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2204   LValue LB =
2205       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2206   LValue UB =
2207       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2208 
2209   // When composing 'distribute' with 'for' (e.g. as in 'distribute
2210   // parallel for') we need to use the 'distribute'
2211   // chunk lower and upper bounds rather than the whole loop iteration
2212   // space. These are parameters to the outlined function for 'parallel'
2213   // and we copy the bounds of the previous schedule into the
2214   // the current ones.
2215   LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
2216   LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
2217   llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
2218       PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
2219   PrevLBVal = CGF.EmitScalarConversion(
2220       PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
2221       LS.getIterationVariable()->getType(),
2222       LS.getPrevLowerBoundVariable()->getExprLoc());
2223   llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
2224       PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
2225   PrevUBVal = CGF.EmitScalarConversion(
2226       PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
2227       LS.getIterationVariable()->getType(),
2228       LS.getPrevUpperBoundVariable()->getExprLoc());
2229 
2230   CGF.EmitStoreOfScalar(PrevLBVal, LB);
2231   CGF.EmitStoreOfScalar(PrevUBVal, UB);
2232 
2233   return {LB, UB};
2234 }
2235 
2236 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
2237 /// we need to use the LB and UB expressions generated by the worksharing
2238 /// code generation support, whereas in non combined situations we would
2239 /// just emit 0 and the LastIteration expression
2240 /// This function is necessary due to the difference of the LB and UB
2241 /// types for the RT emission routines for 'for_static_init' and
2242 /// 'for_dispatch_init'
2243 static std::pair<llvm::Value *, llvm::Value *>
2244 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
2245                                         const OMPExecutableDirective &S,
2246                                         Address LB, Address UB) {
2247   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
2248   const Expr *IVExpr = LS.getIterationVariable();
2249   // when implementing a dynamic schedule for a 'for' combined with a
2250   // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
2251   // is not normalized as each team only executes its own assigned
2252   // distribute chunk
2253   QualType IteratorTy = IVExpr->getType();
2254   llvm::Value *LBVal =
2255       CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2256   llvm::Value *UBVal =
2257       CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
2258   return {LBVal, UBVal};
2259 }
2260 
2261 static void emitDistributeParallelForDistributeInnerBoundParams(
2262     CodeGenFunction &CGF, const OMPExecutableDirective &S,
2263     llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
2264   const auto &Dir = cast<OMPLoopDirective>(S);
2265   LValue LB =
2266       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
2267   llvm::Value *LBCast = CGF.Builder.CreateIntCast(
2268       CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2269   CapturedVars.push_back(LBCast);
2270   LValue UB =
2271       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
2272 
2273   llvm::Value *UBCast = CGF.Builder.CreateIntCast(
2274       CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
2275   CapturedVars.push_back(UBCast);
2276 }
2277 
2278 static void
2279 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
2280                                  const OMPLoopDirective &S,
2281                                  CodeGenFunction::JumpDest LoopExit) {
2282   auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
2283                                          PrePostActionTy &Action) {
2284     Action.Enter(CGF);
2285     bool HasCancel = false;
2286     if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2287       if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
2288         HasCancel = D->hasCancel();
2289       else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
2290         HasCancel = D->hasCancel();
2291       else if (const auto *D =
2292                    dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
2293         HasCancel = D->hasCancel();
2294     }
2295     CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
2296                                                      HasCancel);
2297     CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
2298                                emitDistributeParallelForInnerBounds,
2299                                emitDistributeParallelForDispatchBounds);
2300   };
2301 
2302   emitCommonOMPParallelDirective(
2303       CGF, S,
2304       isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
2305       CGInlinedWorksharingLoop,
2306       emitDistributeParallelForDistributeInnerBoundParams);
2307 }
2308 
2309 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
2310     const OMPDistributeParallelForDirective &S) {
2311   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2312     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2313                               S.getDistInc());
2314   };
2315   OMPLexicalScope Scope(*this, S, OMPD_parallel);
2316   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2317 }
2318 
2319 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
2320     const OMPDistributeParallelForSimdDirective &S) {
2321   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2322     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
2323                               S.getDistInc());
2324   };
2325   OMPLexicalScope Scope(*this, S, OMPD_parallel);
2326   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
2327 }
2328 
2329 void CodeGenFunction::EmitOMPDistributeSimdDirective(
2330     const OMPDistributeSimdDirective &S) {
2331   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2332     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
2333   };
2334   OMPLexicalScope Scope(*this, S, OMPD_unknown);
2335   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2336 }
2337 
2338 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
2339     CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
2340   // Emit SPMD target parallel for region as a standalone region.
2341   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2342     emitOMPSimdRegion(CGF, S, Action);
2343   };
2344   llvm::Function *Fn;
2345   llvm::Constant *Addr;
2346   // Emit target region as a standalone region.
2347   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
2348       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
2349   assert(Fn && Addr && "Target device function emission failed.");
2350 }
2351 
2352 void CodeGenFunction::EmitOMPTargetSimdDirective(
2353     const OMPTargetSimdDirective &S) {
2354   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2355     emitOMPSimdRegion(CGF, S, Action);
2356   };
2357   emitCommonOMPTargetDirective(*this, S, CodeGen);
2358 }
2359 
2360 namespace {
2361   struct ScheduleKindModifiersTy {
2362     OpenMPScheduleClauseKind Kind;
2363     OpenMPScheduleClauseModifier M1;
2364     OpenMPScheduleClauseModifier M2;
2365     ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
2366                             OpenMPScheduleClauseModifier M1,
2367                             OpenMPScheduleClauseModifier M2)
2368         : Kind(Kind), M1(M1), M2(M2) {}
2369   };
2370 } // namespace
2371 
2372 bool CodeGenFunction::EmitOMPWorksharingLoop(
2373     const OMPLoopDirective &S, Expr *EUB,
2374     const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2375     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2376   // Emit the loop iteration variable.
2377   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
2378   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
2379   EmitVarDecl(*IVDecl);
2380 
2381   // Emit the iterations count variable.
2382   // If it is not a variable, Sema decided to calculate iterations count on each
2383   // iteration (e.g., it is foldable into a constant).
2384   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2385     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2386     // Emit calculation of the iterations count.
2387     EmitIgnoredExpr(S.getCalcLastIteration());
2388   }
2389 
2390   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2391 
2392   bool HasLastprivateClause;
2393   // Check pre-condition.
2394   {
2395     OMPLoopScope PreInitScope(*this, S);
2396     // Skip the entire loop if we don't meet the precondition.
2397     // If the condition constant folds and can be elided, avoid emitting the
2398     // whole loop.
2399     bool CondConstant;
2400     llvm::BasicBlock *ContBlock = nullptr;
2401     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2402       if (!CondConstant)
2403         return false;
2404     } else {
2405       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
2406       ContBlock = createBasicBlock("omp.precond.end");
2407       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
2408                   getProfileCount(&S));
2409       EmitBlock(ThenBlock);
2410       incrementProfileCounter(&S);
2411     }
2412 
2413     RunCleanupsScope DoacrossCleanupScope(*this);
2414     bool Ordered = false;
2415     if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
2416       if (OrderedClause->getNumForLoops())
2417         RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
2418       else
2419         Ordered = true;
2420     }
2421 
2422     llvm::DenseSet<const Expr *> EmittedFinals;
2423     emitAlignedClause(*this, S);
2424     bool HasLinears = EmitOMPLinearClauseInit(S);
2425     // Emit helper vars inits.
2426 
2427     std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
2428     LValue LB = Bounds.first;
2429     LValue UB = Bounds.second;
2430     LValue ST =
2431         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
2432     LValue IL =
2433         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
2434 
2435     // Emit 'then' code.
2436     {
2437       OMPPrivateScope LoopScope(*this);
2438       if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
2439         // Emit implicit barrier to synchronize threads and avoid data races on
2440         // initialization of firstprivate variables and post-update of
2441         // lastprivate variables.
2442         CGM.getOpenMPRuntime().emitBarrierCall(
2443             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2444             /*ForceSimpleCall=*/true);
2445       }
2446       EmitOMPPrivateClause(S, LoopScope);
2447       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
2448       EmitOMPReductionClauseInit(S, LoopScope);
2449       EmitOMPPrivateLoopCounters(S, LoopScope);
2450       EmitOMPLinearClause(S, LoopScope);
2451       (void)LoopScope.Privatize();
2452       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2453         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
2454 
2455       // Detect the loop schedule kind and chunk.
2456       const Expr *ChunkExpr = nullptr;
2457       OpenMPScheduleTy ScheduleKind;
2458       if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
2459         ScheduleKind.Schedule = C->getScheduleKind();
2460         ScheduleKind.M1 = C->getFirstScheduleModifier();
2461         ScheduleKind.M2 = C->getSecondScheduleModifier();
2462         ChunkExpr = C->getChunkSize();
2463       } else {
2464         // Default behaviour for schedule clause.
2465         CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
2466             *this, S, ScheduleKind.Schedule, ChunkExpr);
2467       }
2468       bool HasChunkSizeOne = false;
2469       llvm::Value *Chunk = nullptr;
2470       if (ChunkExpr) {
2471         Chunk = EmitScalarExpr(ChunkExpr);
2472         Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
2473                                      S.getIterationVariable()->getType(),
2474                                      S.getBeginLoc());
2475         Expr::EvalResult Result;
2476         if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
2477           llvm::APSInt EvaluatedChunk = Result.Val.getInt();
2478           HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
2479         }
2480       }
2481       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2482       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2483       // OpenMP 4.5, 2.7.1 Loop Construct, Description.
2484       // If the static schedule kind is specified or if the ordered clause is
2485       // specified, and if no monotonic modifier is specified, the effect will
2486       // be as if the monotonic modifier was specified.
2487       bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule,
2488           /* Chunked */ Chunk != nullptr) && HasChunkSizeOne &&
2489           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
2490       if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
2491                                  /* Chunked */ Chunk != nullptr) ||
2492            StaticChunkedOne) &&
2493           !Ordered) {
2494         if (isOpenMPSimdDirective(S.getDirectiveKind()))
2495           EmitOMPSimdInit(S, /*IsMonotonic=*/true);
2496         // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2497         // When no chunk_size is specified, the iteration space is divided into
2498         // chunks that are approximately equal in size, and at most one chunk is
2499         // distributed to each thread. Note that the size of the chunks is
2500         // unspecified in this case.
2501         CGOpenMPRuntime::StaticRTInput StaticInit(
2502             IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
2503             UB.getAddress(), ST.getAddress(),
2504             StaticChunkedOne ? Chunk : nullptr);
2505         RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
2506                              ScheduleKind, StaticInit);
2507         JumpDest LoopExit =
2508             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
2509         // UB = min(UB, GlobalUB);
2510         if (!StaticChunkedOne)
2511           EmitIgnoredExpr(S.getEnsureUpperBound());
2512         // IV = LB;
2513         EmitIgnoredExpr(S.getInit());
2514         // For unchunked static schedule generate:
2515         //
2516         // while (idx <= UB) {
2517         //   BODY;
2518         //   ++idx;
2519         // }
2520         //
2521         // For static schedule with chunk one:
2522         //
2523         // while (IV <= PrevUB) {
2524         //   BODY;
2525         //   IV += ST;
2526         // }
2527         EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
2528             StaticChunkedOne ? S.getCombinedParForInDistCond() : S.getCond(),
2529             StaticChunkedOne ? S.getDistInc() : S.getInc(),
2530             [&S, LoopExit](CodeGenFunction &CGF) {
2531              CGF.EmitOMPLoopBody(S, LoopExit);
2532              CGF.EmitStopPoint(&S);
2533             },
2534             [](CodeGenFunction &) {});
2535         EmitBlock(LoopExit.getBlock());
2536         // Tell the runtime we are done.
2537         auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2538           CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2539                                                          S.getDirectiveKind());
2540         };
2541         OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2542       } else {
2543         const bool IsMonotonic =
2544             Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
2545             ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
2546             ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
2547             ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
2548         // Emit the outer loop, which requests its work chunk [LB..UB] from
2549         // runtime and runs the inner loop to process it.
2550         const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
2551                                              ST.getAddress(), IL.getAddress(),
2552                                              Chunk, EUB);
2553         EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
2554                             LoopArguments, CGDispatchBounds);
2555       }
2556       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2557         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
2558           return CGF.Builder.CreateIsNotNull(
2559               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2560         });
2561       }
2562       EmitOMPReductionClauseFinal(
2563           S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
2564                  ? /*Parallel and Simd*/ OMPD_parallel_for_simd
2565                  : /*Parallel only*/ OMPD_parallel);
2566       // Emit post-update of the reduction variables if IsLastIter != 0.
2567       emitPostUpdateForReductionClause(
2568           *this, S, [IL, &S](CodeGenFunction &CGF) {
2569             return CGF.Builder.CreateIsNotNull(
2570                 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2571           });
2572       // Emit final copy of the lastprivate variables if IsLastIter != 0.
2573       if (HasLastprivateClause)
2574         EmitOMPLastprivateClauseFinal(
2575             S, isOpenMPSimdDirective(S.getDirectiveKind()),
2576             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
2577     }
2578     EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
2579       return CGF.Builder.CreateIsNotNull(
2580           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2581     });
2582     DoacrossCleanupScope.ForceCleanup();
2583     // We're now done with the loop, so jump to the continuation block.
2584     if (ContBlock) {
2585       EmitBranch(ContBlock);
2586       EmitBlock(ContBlock, /*IsFinished=*/true);
2587     }
2588   }
2589   return HasLastprivateClause;
2590 }
2591 
2592 /// The following two functions generate expressions for the loop lower
2593 /// and upper bounds in case of static and dynamic (dispatch) schedule
2594 /// of the associated 'for' or 'distribute' loop.
2595 static std::pair<LValue, LValue>
2596 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
2597   const auto &LS = cast<OMPLoopDirective>(S);
2598   LValue LB =
2599       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
2600   LValue UB =
2601       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
2602   return {LB, UB};
2603 }
2604 
2605 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
2606 /// consider the lower and upper bound expressions generated by the
2607 /// worksharing loop support, but we use 0 and the iteration space size as
2608 /// constants
2609 static std::pair<llvm::Value *, llvm::Value *>
2610 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
2611                           Address LB, Address UB) {
2612   const auto &LS = cast<OMPLoopDirective>(S);
2613   const Expr *IVExpr = LS.getIterationVariable();
2614   const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
2615   llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
2616   llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
2617   return {LBVal, UBVal};
2618 }
2619 
2620 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
2621   bool HasLastprivates = false;
2622   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2623                                           PrePostActionTy &) {
2624     OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
2625     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2626                                                  emitForLoopBounds,
2627                                                  emitDispatchForLoopBounds);
2628   };
2629   {
2630     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2631     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
2632                                                 S.hasCancel());
2633   }
2634 
2635   // Emit an implicit barrier at the end.
2636   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2637     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2638 }
2639 
2640 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
2641   bool HasLastprivates = false;
2642   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
2643                                           PrePostActionTy &) {
2644     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
2645                                                  emitForLoopBounds,
2646                                                  emitDispatchForLoopBounds);
2647   };
2648   {
2649     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2650     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2651   }
2652 
2653   // Emit an implicit barrier at the end.
2654   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
2655     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
2656 }
2657 
2658 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
2659                                 const Twine &Name,
2660                                 llvm::Value *Init = nullptr) {
2661   LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
2662   if (Init)
2663     CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
2664   return LVal;
2665 }
2666 
2667 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
2668   const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
2669   const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
2670   bool HasLastprivates = false;
2671   auto &&CodeGen = [&S, CapturedStmt, CS,
2672                     &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
2673     ASTContext &C = CGF.getContext();
2674     QualType KmpInt32Ty =
2675         C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2676     // Emit helper vars inits.
2677     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
2678                                   CGF.Builder.getInt32(0));
2679     llvm::ConstantInt *GlobalUBVal = CS != nullptr
2680                                          ? CGF.Builder.getInt32(CS->size() - 1)
2681                                          : CGF.Builder.getInt32(0);
2682     LValue UB =
2683         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
2684     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
2685                                   CGF.Builder.getInt32(1));
2686     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
2687                                   CGF.Builder.getInt32(0));
2688     // Loop counter.
2689     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
2690     OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2691     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
2692     OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
2693     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
2694     // Generate condition for loop.
2695     BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
2696                         OK_Ordinary, S.getBeginLoc(), FPOptions());
2697     // Increment for loop counter.
2698     UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
2699                       S.getBeginLoc(), true);
2700     auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
2701       // Iterate through all sections and emit a switch construct:
2702       // switch (IV) {
2703       //   case 0:
2704       //     <SectionStmt[0]>;
2705       //     break;
2706       // ...
2707       //   case <NumSection> - 1:
2708       //     <SectionStmt[<NumSection> - 1]>;
2709       //     break;
2710       // }
2711       // .omp.sections.exit:
2712       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
2713       llvm::SwitchInst *SwitchStmt =
2714           CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
2715                                    ExitBB, CS == nullptr ? 1 : CS->size());
2716       if (CS) {
2717         unsigned CaseNumber = 0;
2718         for (const Stmt *SubStmt : CS->children()) {
2719           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
2720           CGF.EmitBlock(CaseBB);
2721           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
2722           CGF.EmitStmt(SubStmt);
2723           CGF.EmitBranch(ExitBB);
2724           ++CaseNumber;
2725         }
2726       } else {
2727         llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
2728         CGF.EmitBlock(CaseBB);
2729         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
2730         CGF.EmitStmt(CapturedStmt);
2731         CGF.EmitBranch(ExitBB);
2732       }
2733       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2734     };
2735 
2736     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2737     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
2738       // Emit implicit barrier to synchronize threads and avoid data races on
2739       // initialization of firstprivate variables and post-update of lastprivate
2740       // variables.
2741       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
2742           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
2743           /*ForceSimpleCall=*/true);
2744     }
2745     CGF.EmitOMPPrivateClause(S, LoopScope);
2746     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2747     CGF.EmitOMPReductionClauseInit(S, LoopScope);
2748     (void)LoopScope.Privatize();
2749     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2750       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
2751 
2752     // Emit static non-chunked loop.
2753     OpenMPScheduleTy ScheduleKind;
2754     ScheduleKind.Schedule = OMPC_SCHEDULE_static;
2755     CGOpenMPRuntime::StaticRTInput StaticInit(
2756         /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
2757         LB.getAddress(), UB.getAddress(), ST.getAddress());
2758     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
2759         CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
2760     // UB = min(UB, GlobalUB);
2761     llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
2762     llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
2763         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
2764     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
2765     // IV = LB;
2766     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
2767     // while (idx <= UB) { BODY; ++idx; }
2768     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
2769                          [](CodeGenFunction &) {});
2770     // Tell the runtime we are done.
2771     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2772       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2773                                                      S.getDirectiveKind());
2774     };
2775     CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
2776     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
2777     // Emit post-update of the reduction variables if IsLastIter != 0.
2778     emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
2779       return CGF.Builder.CreateIsNotNull(
2780           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
2781     });
2782 
2783     // Emit final copy of the lastprivate variables if IsLastIter != 0.
2784     if (HasLastprivates)
2785       CGF.EmitOMPLastprivateClauseFinal(
2786           S, /*NoFinals=*/false,
2787           CGF.Builder.CreateIsNotNull(
2788               CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
2789   };
2790 
2791   bool HasCancel = false;
2792   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
2793     HasCancel = OSD->hasCancel();
2794   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
2795     HasCancel = OPSD->hasCancel();
2796   OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
2797   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
2798                                               HasCancel);
2799   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
2800   // clause. Otherwise the barrier will be generated by the codegen for the
2801   // directive.
2802   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
2803     // Emit implicit barrier to synchronize threads and avoid data races on
2804     // initialization of firstprivate variables.
2805     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
2806                                            OMPD_unknown);
2807   }
2808 }
2809 
2810 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
2811   {
2812     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2813     EmitSections(S);
2814   }
2815   // Emit an implicit barrier at the end.
2816   if (!S.getSingleClause<OMPNowaitClause>()) {
2817     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
2818                                            OMPD_sections);
2819   }
2820 }
2821 
2822 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
2823   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2824     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
2825   };
2826   OMPLexicalScope Scope(*this, S, OMPD_unknown);
2827   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
2828                                               S.hasCancel());
2829 }
2830 
2831 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
2832   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
2833   llvm::SmallVector<const Expr *, 8> DestExprs;
2834   llvm::SmallVector<const Expr *, 8> SrcExprs;
2835   llvm::SmallVector<const Expr *, 8> AssignmentOps;
2836   // Check if there are any 'copyprivate' clauses associated with this
2837   // 'single' construct.
2838   // Build a list of copyprivate variables along with helper expressions
2839   // (<source>, <destination>, <destination>=<source> expressions)
2840   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
2841     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
2842     DestExprs.append(C->destination_exprs().begin(),
2843                      C->destination_exprs().end());
2844     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
2845     AssignmentOps.append(C->assignment_ops().begin(),
2846                          C->assignment_ops().end());
2847   }
2848   // Emit code for 'single' region along with 'copyprivate' clauses
2849   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2850     Action.Enter(CGF);
2851     OMPPrivateScope SingleScope(CGF);
2852     (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
2853     CGF.EmitOMPPrivateClause(S, SingleScope);
2854     (void)SingleScope.Privatize();
2855     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
2856   };
2857   {
2858     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2859     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
2860                                             CopyprivateVars, DestExprs,
2861                                             SrcExprs, AssignmentOps);
2862   }
2863   // Emit an implicit barrier at the end (to avoid data race on firstprivate
2864   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
2865   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
2866     CGM.getOpenMPRuntime().emitBarrierCall(
2867         *this, S.getBeginLoc(),
2868         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
2869   }
2870 }
2871 
2872 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
2873   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2874     Action.Enter(CGF);
2875     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
2876   };
2877   OMPLexicalScope Scope(*this, S, OMPD_unknown);
2878   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
2879 }
2880 
2881 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
2882   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2883     Action.Enter(CGF);
2884     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
2885   };
2886   const Expr *Hint = nullptr;
2887   if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
2888     Hint = HintClause->getHint();
2889   OMPLexicalScope Scope(*this, S, OMPD_unknown);
2890   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
2891                                             S.getDirectiveName().getAsString(),
2892                                             CodeGen, S.getBeginLoc(), Hint);
2893 }
2894 
2895 void CodeGenFunction::EmitOMPParallelForDirective(
2896     const OMPParallelForDirective &S) {
2897   // Emit directive as a combined directive that consists of two implicit
2898   // directives: 'parallel' with 'for' directive.
2899   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2900     Action.Enter(CGF);
2901     OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
2902     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2903                                emitDispatchForLoopBounds);
2904   };
2905   emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
2906                                  emitEmptyBoundParameters);
2907 }
2908 
2909 void CodeGenFunction::EmitOMPParallelForSimdDirective(
2910     const OMPParallelForSimdDirective &S) {
2911   // Emit directive as a combined directive that consists of two implicit
2912   // directives: 'parallel' with 'for' directive.
2913   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2914     Action.Enter(CGF);
2915     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
2916                                emitDispatchForLoopBounds);
2917   };
2918   emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
2919                                  emitEmptyBoundParameters);
2920 }
2921 
2922 void CodeGenFunction::EmitOMPParallelSectionsDirective(
2923     const OMPParallelSectionsDirective &S) {
2924   // Emit directive as a combined directive that consists of two implicit
2925   // directives: 'parallel' with 'sections' directive.
2926   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2927     Action.Enter(CGF);
2928     CGF.EmitSections(S);
2929   };
2930   emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
2931                                  emitEmptyBoundParameters);
2932 }
2933 
2934 void CodeGenFunction::EmitOMPTaskBasedDirective(
2935     const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
2936     const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
2937     OMPTaskDataTy &Data) {
2938   // Emit outlined function for task construct.
2939   const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
2940   auto I = CS->getCapturedDecl()->param_begin();
2941   auto PartId = std::next(I);
2942   auto TaskT = std::next(I, 4);
2943   // Check if the task is final
2944   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2945     // If the condition constant folds and can be elided, try to avoid emitting
2946     // the condition and the dead arm of the if/else.
2947     const Expr *Cond = Clause->getCondition();
2948     bool CondConstant;
2949     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2950       Data.Final.setInt(CondConstant);
2951     else
2952       Data.Final.setPointer(EvaluateExprAsBool(Cond));
2953   } else {
2954     // By default the task is not final.
2955     Data.Final.setInt(/*IntVal=*/false);
2956   }
2957   // Check if the task has 'priority' clause.
2958   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
2959     const Expr *Prio = Clause->getPriority();
2960     Data.Priority.setInt(/*IntVal=*/true);
2961     Data.Priority.setPointer(EmitScalarConversion(
2962         EmitScalarExpr(Prio), Prio->getType(),
2963         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2964         Prio->getExprLoc()));
2965   }
2966   // The first function argument for tasks is a thread id, the second one is a
2967   // part id (0 for tied tasks, >=0 for untied task).
2968   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
2969   // Get list of private variables.
2970   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
2971     auto IRef = C->varlist_begin();
2972     for (const Expr *IInit : C->private_copies()) {
2973       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2974       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2975         Data.PrivateVars.push_back(*IRef);
2976         Data.PrivateCopies.push_back(IInit);
2977       }
2978       ++IRef;
2979     }
2980   }
2981   EmittedAsPrivate.clear();
2982   // Get list of firstprivate variables.
2983   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2984     auto IRef = C->varlist_begin();
2985     auto IElemInitRef = C->inits().begin();
2986     for (const Expr *IInit : C->private_copies()) {
2987       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2988       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2989         Data.FirstprivateVars.push_back(*IRef);
2990         Data.FirstprivateCopies.push_back(IInit);
2991         Data.FirstprivateInits.push_back(*IElemInitRef);
2992       }
2993       ++IRef;
2994       ++IElemInitRef;
2995     }
2996   }
2997   // Get list of lastprivate variables (for taskloops).
2998   llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
2999   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3000     auto IRef = C->varlist_begin();
3001     auto ID = C->destination_exprs().begin();
3002     for (const Expr *IInit : C->private_copies()) {
3003       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3004       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3005         Data.LastprivateVars.push_back(*IRef);
3006         Data.LastprivateCopies.push_back(IInit);
3007       }
3008       LastprivateDstsOrigs.insert(
3009           {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3010            cast<DeclRefExpr>(*IRef)});
3011       ++IRef;
3012       ++ID;
3013     }
3014   }
3015   SmallVector<const Expr *, 4> LHSs;
3016   SmallVector<const Expr *, 4> RHSs;
3017   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3018     auto IPriv = C->privates().begin();
3019     auto IRed = C->reduction_ops().begin();
3020     auto ILHS = C->lhs_exprs().begin();
3021     auto IRHS = C->rhs_exprs().begin();
3022     for (const Expr *Ref : C->varlists()) {
3023       Data.ReductionVars.emplace_back(Ref);
3024       Data.ReductionCopies.emplace_back(*IPriv);
3025       Data.ReductionOps.emplace_back(*IRed);
3026       LHSs.emplace_back(*ILHS);
3027       RHSs.emplace_back(*IRHS);
3028       std::advance(IPriv, 1);
3029       std::advance(IRed, 1);
3030       std::advance(ILHS, 1);
3031       std::advance(IRHS, 1);
3032     }
3033   }
3034   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
3035       *this, S.getBeginLoc(), LHSs, RHSs, Data);
3036   // Build list of dependences.
3037   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3038     for (const Expr *IRef : C->varlists())
3039       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3040   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3041                     CapturedRegion](CodeGenFunction &CGF,
3042                                     PrePostActionTy &Action) {
3043     // Set proper addresses for generated private copies.
3044     OMPPrivateScope Scope(CGF);
3045     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3046         !Data.LastprivateVars.empty()) {
3047       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3048           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3049       enum { PrivatesParam = 2, CopyFnParam = 3 };
3050       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3051           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3052       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3053           CS->getCapturedDecl()->getParam(PrivatesParam)));
3054       // Map privates.
3055       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3056       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3057       CallArgs.push_back(PrivatesPtr);
3058       for (const Expr *E : Data.PrivateVars) {
3059         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3060         Address PrivatePtr = CGF.CreateMemTemp(
3061             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
3062         PrivatePtrs.emplace_back(VD, PrivatePtr);
3063         CallArgs.push_back(PrivatePtr.getPointer());
3064       }
3065       for (const Expr *E : Data.FirstprivateVars) {
3066         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3067         Address PrivatePtr =
3068             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3069                               ".firstpriv.ptr.addr");
3070         PrivatePtrs.emplace_back(VD, PrivatePtr);
3071         CallArgs.push_back(PrivatePtr.getPointer());
3072       }
3073       for (const Expr *E : Data.LastprivateVars) {
3074         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3075         Address PrivatePtr =
3076             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3077                               ".lastpriv.ptr.addr");
3078         PrivatePtrs.emplace_back(VD, PrivatePtr);
3079         CallArgs.push_back(PrivatePtr.getPointer());
3080       }
3081       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3082           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3083       for (const auto &Pair : LastprivateDstsOrigs) {
3084         const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
3085         DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3086                         /*RefersToEnclosingVariableOrCapture=*/
3087                             CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3088                         Pair.second->getType(), VK_LValue,
3089                         Pair.second->getExprLoc());
3090         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
3091           return CGF.EmitLValue(&DRE).getAddress();
3092         });
3093       }
3094       for (const auto &Pair : PrivatePtrs) {
3095         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3096                             CGF.getContext().getDeclAlign(Pair.first));
3097         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3098       }
3099     }
3100     if (Data.Reductions) {
3101       OMPLexicalScope LexScope(CGF, S, CapturedRegion);
3102       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3103                              Data.ReductionOps);
3104       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3105           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3106       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3107         RedCG.emitSharedLValue(CGF, Cnt);
3108         RedCG.emitAggregateType(CGF, Cnt);
3109         // FIXME: This must removed once the runtime library is fixed.
3110         // Emit required threadprivate variables for
3111         // initializer/combiner/finalizer.
3112         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3113                                                            RedCG, Cnt);
3114         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3115             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3116         Replacement =
3117             Address(CGF.EmitScalarConversion(
3118                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3119                         CGF.getContext().getPointerType(
3120                             Data.ReductionCopies[Cnt]->getType()),
3121                         Data.ReductionCopies[Cnt]->getExprLoc()),
3122                     Replacement.getAlignment());
3123         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3124         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3125                          [Replacement]() { return Replacement; });
3126       }
3127     }
3128     // Privatize all private variables except for in_reduction items.
3129     (void)Scope.Privatize();
3130     SmallVector<const Expr *, 4> InRedVars;
3131     SmallVector<const Expr *, 4> InRedPrivs;
3132     SmallVector<const Expr *, 4> InRedOps;
3133     SmallVector<const Expr *, 4> TaskgroupDescriptors;
3134     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3135       auto IPriv = C->privates().begin();
3136       auto IRed = C->reduction_ops().begin();
3137       auto ITD = C->taskgroup_descriptors().begin();
3138       for (const Expr *Ref : C->varlists()) {
3139         InRedVars.emplace_back(Ref);
3140         InRedPrivs.emplace_back(*IPriv);
3141         InRedOps.emplace_back(*IRed);
3142         TaskgroupDescriptors.emplace_back(*ITD);
3143         std::advance(IPriv, 1);
3144         std::advance(IRed, 1);
3145         std::advance(ITD, 1);
3146       }
3147     }
3148     // Privatize in_reduction items here, because taskgroup descriptors must be
3149     // privatized earlier.
3150     OMPPrivateScope InRedScope(CGF);
3151     if (!InRedVars.empty()) {
3152       ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3153       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3154         RedCG.emitSharedLValue(CGF, Cnt);
3155         RedCG.emitAggregateType(CGF, Cnt);
3156         // The taskgroup descriptor variable is always implicit firstprivate and
3157         // privatized already during processing of the firstprivates.
3158         // FIXME: This must removed once the runtime library is fixed.
3159         // Emit required threadprivate variables for
3160         // initializer/combiner/finalizer.
3161         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3162                                                            RedCG, Cnt);
3163         llvm::Value *ReductionsPtr =
3164             CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3165                                  TaskgroupDescriptors[Cnt]->getExprLoc());
3166         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3167             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3168         Replacement = Address(
3169             CGF.EmitScalarConversion(
3170                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3171                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
3172                 InRedPrivs[Cnt]->getExprLoc()),
3173             Replacement.getAlignment());
3174         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3175         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3176                               [Replacement]() { return Replacement; });
3177       }
3178     }
3179     (void)InRedScope.Privatize();
3180 
3181     Action.Enter(CGF);
3182     BodyGen(CGF);
3183   };
3184   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3185       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3186       Data.NumberOfParts);
3187   OMPLexicalScope Scope(*this, S, llvm::None,
3188                         !isOpenMPParallelDirective(S.getDirectiveKind()));
3189   TaskGen(*this, OutlinedFn, Data);
3190 }
3191 
3192 static ImplicitParamDecl *
3193 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
3194                                   QualType Ty, CapturedDecl *CD,
3195                                   SourceLocation Loc) {
3196   auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3197                                            ImplicitParamDecl::Other);
3198   auto *OrigRef = DeclRefExpr::Create(
3199       C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3200       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3201   auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3202                                               ImplicitParamDecl::Other);
3203   auto *PrivateRef = DeclRefExpr::Create(
3204       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
3205       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3206   QualType ElemType = C.getBaseElementType(Ty);
3207   auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3208                                            ImplicitParamDecl::Other);
3209   auto *InitRef = DeclRefExpr::Create(
3210       C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3211       /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
3212   PrivateVD->setInitStyle(VarDecl::CInit);
3213   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3214                                               InitRef, /*BasePath=*/nullptr,
3215                                               VK_RValue));
3216   Data.FirstprivateVars.emplace_back(OrigRef);
3217   Data.FirstprivateCopies.emplace_back(PrivateRef);
3218   Data.FirstprivateInits.emplace_back(InitRef);
3219   return OrigVD;
3220 }
3221 
3222 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3223     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3224     OMPTargetDataInfo &InputInfo) {
3225   // Emit outlined function for task construct.
3226   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3227   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3228   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3229   auto I = CS->getCapturedDecl()->param_begin();
3230   auto PartId = std::next(I);
3231   auto TaskT = std::next(I, 4);
3232   OMPTaskDataTy Data;
3233   // The task is not final.
3234   Data.Final.setInt(/*IntVal=*/false);
3235   // Get list of firstprivate variables.
3236   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3237     auto IRef = C->varlist_begin();
3238     auto IElemInitRef = C->inits().begin();
3239     for (auto *IInit : C->private_copies()) {
3240       Data.FirstprivateVars.push_back(*IRef);
3241       Data.FirstprivateCopies.push_back(IInit);
3242       Data.FirstprivateInits.push_back(*IElemInitRef);
3243       ++IRef;
3244       ++IElemInitRef;
3245     }
3246   }
3247   OMPPrivateScope TargetScope(*this);
3248   VarDecl *BPVD = nullptr;
3249   VarDecl *PVD = nullptr;
3250   VarDecl *SVD = nullptr;
3251   if (InputInfo.NumberOfTargetItems > 0) {
3252     auto *CD = CapturedDecl::Create(
3253         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3254     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3255     QualType BaseAndPointersType = getContext().getConstantArrayType(
3256         getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
3257         /*IndexTypeQuals=*/0);
3258     BPVD = createImplicitFirstprivateForType(
3259         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3260     PVD = createImplicitFirstprivateForType(
3261         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3262     QualType SizesType = getContext().getConstantArrayType(
3263         getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
3264         ArrSize, nullptr, ArrayType::Normal,
3265         /*IndexTypeQuals=*/0);
3266     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3267                                             S.getBeginLoc());
3268     TargetScope.addPrivate(
3269         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3270     TargetScope.addPrivate(PVD,
3271                            [&InputInfo]() { return InputInfo.PointersArray; });
3272     TargetScope.addPrivate(SVD,
3273                            [&InputInfo]() { return InputInfo.SizesArray; });
3274   }
3275   (void)TargetScope.Privatize();
3276   // Build list of dependences.
3277   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3278     for (const Expr *IRef : C->varlists())
3279       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3280   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3281                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3282     // Set proper addresses for generated private copies.
3283     OMPPrivateScope Scope(CGF);
3284     if (!Data.FirstprivateVars.empty()) {
3285       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3286           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3287       enum { PrivatesParam = 2, CopyFnParam = 3 };
3288       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3289           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3290       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3291           CS->getCapturedDecl()->getParam(PrivatesParam)));
3292       // Map privates.
3293       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3294       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3295       CallArgs.push_back(PrivatesPtr);
3296       for (const Expr *E : Data.FirstprivateVars) {
3297         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3298         Address PrivatePtr =
3299             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3300                               ".firstpriv.ptr.addr");
3301         PrivatePtrs.emplace_back(VD, PrivatePtr);
3302         CallArgs.push_back(PrivatePtr.getPointer());
3303       }
3304       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3305           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3306       for (const auto &Pair : PrivatePtrs) {
3307         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3308                             CGF.getContext().getDeclAlign(Pair.first));
3309         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3310       }
3311     }
3312     // Privatize all private variables except for in_reduction items.
3313     (void)Scope.Privatize();
3314     if (InputInfo.NumberOfTargetItems > 0) {
3315       InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3316           CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
3317       InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3318           CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
3319       InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3320           CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
3321     }
3322 
3323     Action.Enter(CGF);
3324     OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
3325     BodyGen(CGF);
3326   };
3327   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3328       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3329       Data.NumberOfParts);
3330   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3331   IntegerLiteral IfCond(getContext(), TrueOrFalse,
3332                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3333                         SourceLocation());
3334 
3335   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
3336                                       SharedsTy, CapturedStruct, &IfCond, Data);
3337 }
3338 
3339 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3340   // Emit outlined function for task construct.
3341   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3342   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3343   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3344   const Expr *IfCond = nullptr;
3345   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3346     if (C->getNameModifier() == OMPD_unknown ||
3347         C->getNameModifier() == OMPD_task) {
3348       IfCond = C->getCondition();
3349       break;
3350     }
3351   }
3352 
3353   OMPTaskDataTy Data;
3354   // Check if we should emit tied or untied task.
3355   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
3356   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3357     CGF.EmitStmt(CS->getCapturedStmt());
3358   };
3359   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3360                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
3361                             const OMPTaskDataTy &Data) {
3362     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
3363                                             SharedsTy, CapturedStruct, IfCond,
3364                                             Data);
3365   };
3366   EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
3367 }
3368 
3369 void CodeGenFunction::EmitOMPTaskyieldDirective(
3370     const OMPTaskyieldDirective &S) {
3371   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
3372 }
3373 
3374 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
3375   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
3376 }
3377 
3378 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3379   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
3380 }
3381 
3382 void CodeGenFunction::EmitOMPTaskgroupDirective(
3383     const OMPTaskgroupDirective &S) {
3384   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3385     Action.Enter(CGF);
3386     if (const Expr *E = S.getReductionRef()) {
3387       SmallVector<const Expr *, 4> LHSs;
3388       SmallVector<const Expr *, 4> RHSs;
3389       OMPTaskDataTy Data;
3390       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3391         auto IPriv = C->privates().begin();
3392         auto IRed = C->reduction_ops().begin();
3393         auto ILHS = C->lhs_exprs().begin();
3394         auto IRHS = C->rhs_exprs().begin();
3395         for (const Expr *Ref : C->varlists()) {
3396           Data.ReductionVars.emplace_back(Ref);
3397           Data.ReductionCopies.emplace_back(*IPriv);
3398           Data.ReductionOps.emplace_back(*IRed);
3399           LHSs.emplace_back(*ILHS);
3400           RHSs.emplace_back(*IRHS);
3401           std::advance(IPriv, 1);
3402           std::advance(IRed, 1);
3403           std::advance(ILHS, 1);
3404           std::advance(IRHS, 1);
3405         }
3406       }
3407       llvm::Value *ReductionDesc =
3408           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
3409                                                            LHSs, RHSs, Data);
3410       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3411       CGF.EmitVarDecl(*VD);
3412       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3413                             /*Volatile=*/false, E->getType());
3414     }
3415     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3416   };
3417   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3418   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
3419 }
3420 
3421 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
3422   CGM.getOpenMPRuntime().emitFlush(
3423       *this,
3424       [&S]() -> ArrayRef<const Expr *> {
3425         if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3426           return llvm::makeArrayRef(FlushClause->varlist_begin(),
3427                                     FlushClause->varlist_end());
3428         return llvm::None;
3429       }(),
3430       S.getBeginLoc());
3431 }
3432 
3433 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3434                                             const CodeGenLoopTy &CodeGenLoop,
3435                                             Expr *IncExpr) {
3436   // Emit the loop iteration variable.
3437   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3438   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3439   EmitVarDecl(*IVDecl);
3440 
3441   // Emit the iterations count variable.
3442   // If it is not a variable, Sema decided to calculate iterations count on each
3443   // iteration (e.g., it is foldable into a constant).
3444   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3445     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3446     // Emit calculation of the iterations count.
3447     EmitIgnoredExpr(S.getCalcLastIteration());
3448   }
3449 
3450   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3451 
3452   bool HasLastprivateClause = false;
3453   // Check pre-condition.
3454   {
3455     OMPLoopScope PreInitScope(*this, S);
3456     // Skip the entire loop if we don't meet the precondition.
3457     // If the condition constant folds and can be elided, avoid emitting the
3458     // whole loop.
3459     bool CondConstant;
3460     llvm::BasicBlock *ContBlock = nullptr;
3461     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3462       if (!CondConstant)
3463         return;
3464     } else {
3465       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3466       ContBlock = createBasicBlock("omp.precond.end");
3467       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3468                   getProfileCount(&S));
3469       EmitBlock(ThenBlock);
3470       incrementProfileCounter(&S);
3471     }
3472 
3473     emitAlignedClause(*this, S);
3474     // Emit 'then' code.
3475     {
3476       // Emit helper vars inits.
3477 
3478       LValue LB = EmitOMPHelperVar(
3479           *this, cast<DeclRefExpr>(
3480                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3481                           ? S.getCombinedLowerBoundVariable()
3482                           : S.getLowerBoundVariable())));
3483       LValue UB = EmitOMPHelperVar(
3484           *this, cast<DeclRefExpr>(
3485                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3486                           ? S.getCombinedUpperBoundVariable()
3487                           : S.getUpperBoundVariable())));
3488       LValue ST =
3489           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3490       LValue IL =
3491           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3492 
3493       OMPPrivateScope LoopScope(*this);
3494       if (EmitOMPFirstprivateClause(S, LoopScope)) {
3495         // Emit implicit barrier to synchronize threads and avoid data races
3496         // on initialization of firstprivate variables and post-update of
3497         // lastprivate variables.
3498         CGM.getOpenMPRuntime().emitBarrierCall(
3499             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3500             /*ForceSimpleCall=*/true);
3501       }
3502       EmitOMPPrivateClause(S, LoopScope);
3503       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3504           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3505           !isOpenMPTeamsDirective(S.getDirectiveKind()))
3506         EmitOMPReductionClauseInit(S, LoopScope);
3507       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3508       EmitOMPPrivateLoopCounters(S, LoopScope);
3509       (void)LoopScope.Privatize();
3510       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3511         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
3512 
3513       // Detect the distribute schedule kind and chunk.
3514       llvm::Value *Chunk = nullptr;
3515       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3516       if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3517         ScheduleKind = C->getDistScheduleKind();
3518         if (const Expr *Ch = C->getChunkSize()) {
3519           Chunk = EmitScalarExpr(Ch);
3520           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3521                                        S.getIterationVariable()->getType(),
3522                                        S.getBeginLoc());
3523         }
3524       } else {
3525         // Default behaviour for dist_schedule clause.
3526         CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3527             *this, S, ScheduleKind, Chunk);
3528       }
3529       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3530       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3531 
3532       // OpenMP [2.10.8, distribute Construct, Description]
3533       // If dist_schedule is specified, kind must be static. If specified,
3534       // iterations are divided into chunks of size chunk_size, chunks are
3535       // assigned to the teams of the league in a round-robin fashion in the
3536       // order of the team number. When no chunk_size is specified, the
3537       // iteration space is divided into chunks that are approximately equal
3538       // in size, and at most one chunk is distributed to each team of the
3539       // league. The size of the chunks is unspecified in this case.
3540       bool StaticChunked = RT.isStaticChunked(
3541           ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3542           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
3543       if (RT.isStaticNonchunked(ScheduleKind,
3544                                 /* Chunked */ Chunk != nullptr) ||
3545           StaticChunked) {
3546         if (isOpenMPSimdDirective(S.getDirectiveKind()))
3547           EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3548         CGOpenMPRuntime::StaticRTInput StaticInit(
3549             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
3550             LB.getAddress(), UB.getAddress(), ST.getAddress(),
3551             StaticChunked ? Chunk : nullptr);
3552         RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
3553                                     StaticInit);
3554         JumpDest LoopExit =
3555             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3556         // UB = min(UB, GlobalUB);
3557         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3558                             ? S.getCombinedEnsureUpperBound()
3559                             : S.getEnsureUpperBound());
3560         // IV = LB;
3561         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3562                             ? S.getCombinedInit()
3563                             : S.getInit());
3564 
3565         const Expr *Cond =
3566             isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3567                 ? S.getCombinedCond()
3568                 : S.getCond();
3569 
3570         if (StaticChunked)
3571           Cond = S.getCombinedDistCond();
3572 
3573         // For static unchunked schedules generate:
3574         //
3575         //  1. For distribute alone, codegen
3576         //    while (idx <= UB) {
3577         //      BODY;
3578         //      ++idx;
3579         //    }
3580         //
3581         //  2. When combined with 'for' (e.g. as in 'distribute parallel for')
3582         //    while (idx <= UB) {
3583         //      <CodeGen rest of pragma>(LB, UB);
3584         //      idx += ST;
3585         //    }
3586         //
3587         // For static chunk one schedule generate:
3588         //
3589         // while (IV <= GlobalUB) {
3590         //   <CodeGen rest of pragma>(LB, UB);
3591         //   LB += ST;
3592         //   UB += ST;
3593         //   UB = min(UB, GlobalUB);
3594         //   IV = LB;
3595         // }
3596         //
3597         EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
3598                          [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3599                            CodeGenLoop(CGF, S, LoopExit);
3600                          },
3601                          [&S, StaticChunked](CodeGenFunction &CGF) {
3602                            if (StaticChunked) {
3603                              CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3604                              CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3605                              CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3606                              CGF.EmitIgnoredExpr(S.getCombinedInit());
3607                            }
3608                          });
3609         EmitBlock(LoopExit.getBlock());
3610         // Tell the runtime we are done.
3611         RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
3612       } else {
3613         // Emit the outer loop, which requests its work chunk [LB..UB] from
3614         // runtime and runs the inner loop to process it.
3615         const OMPLoopArguments LoopArguments = {
3616             LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
3617             Chunk};
3618         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3619                                    CodeGenLoop);
3620       }
3621       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3622         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
3623           return CGF.Builder.CreateIsNotNull(
3624               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3625         });
3626       }
3627       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3628           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3629           !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3630         EmitOMPReductionClauseFinal(S, OMPD_simd);
3631         // Emit post-update of the reduction variables if IsLastIter != 0.
3632         emitPostUpdateForReductionClause(
3633             *this, S, [IL, &S](CodeGenFunction &CGF) {
3634               return CGF.Builder.CreateIsNotNull(
3635                   CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3636             });
3637       }
3638       // Emit final copy of the lastprivate variables if IsLastIter != 0.
3639       if (HasLastprivateClause) {
3640         EmitOMPLastprivateClauseFinal(
3641             S, /*NoFinals=*/false,
3642             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
3643       }
3644     }
3645 
3646     // We're now done with the loop, so jump to the continuation block.
3647     if (ContBlock) {
3648       EmitBranch(ContBlock);
3649       EmitBlock(ContBlock, true);
3650     }
3651   }
3652 }
3653 
3654 void CodeGenFunction::EmitOMPDistributeDirective(
3655     const OMPDistributeDirective &S) {
3656   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3657     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3658   };
3659   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3660   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3661 }
3662 
3663 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
3664                                                    const CapturedStmt *S) {
3665   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3666   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
3667   CGF.CapturedStmtInfo = &CapStmtInfo;
3668   llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
3669   Fn->setDoesNotRecurse();
3670   return Fn;
3671 }
3672 
3673 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
3674   if (S.hasClausesOfKind<OMPDependClause>()) {
3675     assert(!S.getAssociatedStmt() &&
3676            "No associated statement must be in ordered depend construct.");
3677     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
3678       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
3679     return;
3680   }
3681   const auto *C = S.getSingleClause<OMPSIMDClause>();
3682   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
3683                                  PrePostActionTy &Action) {
3684     const CapturedStmt *CS = S.getInnermostCapturedStmt();
3685     if (C) {
3686       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
3687       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
3688       llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
3689       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
3690                                                       OutlinedFn, CapturedVars);
3691     } else {
3692       Action.Enter(CGF);
3693       CGF.EmitStmt(CS->getCapturedStmt());
3694     }
3695   };
3696   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3697   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
3698 }
3699 
3700 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
3701                                          QualType SrcType, QualType DestType,
3702                                          SourceLocation Loc) {
3703   assert(CGF.hasScalarEvaluationKind(DestType) &&
3704          "DestType must have scalar evaluation kind.");
3705   assert(!Val.isAggregate() && "Must be a scalar or complex.");
3706   return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
3707                                                    DestType, Loc)
3708                         : CGF.EmitComplexToScalarConversion(
3709                               Val.getComplexVal(), SrcType, DestType, Loc);
3710 }
3711 
3712 static CodeGenFunction::ComplexPairTy
3713 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
3714                       QualType DestType, SourceLocation Loc) {
3715   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
3716          "DestType must have complex evaluation kind.");
3717   CodeGenFunction::ComplexPairTy ComplexVal;
3718   if (Val.isScalar()) {
3719     // Convert the input element to the element type of the complex.
3720     QualType DestElementType =
3721         DestType->castAs<ComplexType>()->getElementType();
3722     llvm::Value *ScalarVal = CGF.EmitScalarConversion(
3723         Val.getScalarVal(), SrcType, DestElementType, Loc);
3724     ComplexVal = CodeGenFunction::ComplexPairTy(
3725         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
3726   } else {
3727     assert(Val.isComplex() && "Must be a scalar or complex.");
3728     QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
3729     QualType DestElementType =
3730         DestType->castAs<ComplexType>()->getElementType();
3731     ComplexVal.first = CGF.EmitScalarConversion(
3732         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
3733     ComplexVal.second = CGF.EmitScalarConversion(
3734         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
3735   }
3736   return ComplexVal;
3737 }
3738 
3739 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
3740                                   LValue LVal, RValue RVal) {
3741   if (LVal.isGlobalReg()) {
3742     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
3743   } else {
3744     CGF.EmitAtomicStore(RVal, LVal,
3745                         IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3746                                  : llvm::AtomicOrdering::Monotonic,
3747                         LVal.isVolatile(), /*isInit=*/false);
3748   }
3749 }
3750 
3751 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
3752                                          QualType RValTy, SourceLocation Loc) {
3753   switch (getEvaluationKind(LVal.getType())) {
3754   case TEK_Scalar:
3755     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
3756                                *this, RVal, RValTy, LVal.getType(), Loc)),
3757                            LVal);
3758     break;
3759   case TEK_Complex:
3760     EmitStoreOfComplex(
3761         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
3762         /*isInit=*/false);
3763     break;
3764   case TEK_Aggregate:
3765     llvm_unreachable("Must be a scalar or complex.");
3766   }
3767 }
3768 
3769 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
3770                                   const Expr *X, const Expr *V,
3771                                   SourceLocation Loc) {
3772   // v = x;
3773   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
3774   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
3775   LValue XLValue = CGF.EmitLValue(X);
3776   LValue VLValue = CGF.EmitLValue(V);
3777   RValue Res = XLValue.isGlobalReg()
3778                    ? CGF.EmitLoadOfLValue(XLValue, Loc)
3779                    : CGF.EmitAtomicLoad(
3780                          XLValue, Loc,
3781                          IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
3782                                   : llvm::AtomicOrdering::Monotonic,
3783                          XLValue.isVolatile());
3784   // OpenMP, 2.12.6, atomic Construct
3785   // Any atomic construct with a seq_cst clause forces the atomically
3786   // performed operation to include an implicit flush operation without a
3787   // list.
3788   if (IsSeqCst)
3789     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3790   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
3791 }
3792 
3793 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
3794                                    const Expr *X, const Expr *E,
3795                                    SourceLocation Loc) {
3796   // x = expr;
3797   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
3798   emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
3799   // OpenMP, 2.12.6, atomic Construct
3800   // Any atomic construct with a seq_cst clause forces the atomically
3801   // performed operation to include an implicit flush operation without a
3802   // list.
3803   if (IsSeqCst)
3804     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3805 }
3806 
3807 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
3808                                                 RValue Update,
3809                                                 BinaryOperatorKind BO,
3810                                                 llvm::AtomicOrdering AO,
3811                                                 bool IsXLHSInRHSPart) {
3812   ASTContext &Context = CGF.getContext();
3813   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
3814   // expression is simple and atomic is allowed for the given type for the
3815   // target platform.
3816   if (BO == BO_Comma || !Update.isScalar() ||
3817       !Update.getScalarVal()->getType()->isIntegerTy() ||
3818       !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
3819                         (Update.getScalarVal()->getType() !=
3820                          X.getAddress().getElementType())) ||
3821       !X.getAddress().getElementType()->isIntegerTy() ||
3822       !Context.getTargetInfo().hasBuiltinAtomic(
3823           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
3824     return std::make_pair(false, RValue::get(nullptr));
3825 
3826   llvm::AtomicRMWInst::BinOp RMWOp;
3827   switch (BO) {
3828   case BO_Add:
3829     RMWOp = llvm::AtomicRMWInst::Add;
3830     break;
3831   case BO_Sub:
3832     if (!IsXLHSInRHSPart)
3833       return std::make_pair(false, RValue::get(nullptr));
3834     RMWOp = llvm::AtomicRMWInst::Sub;
3835     break;
3836   case BO_And:
3837     RMWOp = llvm::AtomicRMWInst::And;
3838     break;
3839   case BO_Or:
3840     RMWOp = llvm::AtomicRMWInst::Or;
3841     break;
3842   case BO_Xor:
3843     RMWOp = llvm::AtomicRMWInst::Xor;
3844     break;
3845   case BO_LT:
3846     RMWOp = X.getType()->hasSignedIntegerRepresentation()
3847                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
3848                                    : llvm::AtomicRMWInst::Max)
3849                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
3850                                    : llvm::AtomicRMWInst::UMax);
3851     break;
3852   case BO_GT:
3853     RMWOp = X.getType()->hasSignedIntegerRepresentation()
3854                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
3855                                    : llvm::AtomicRMWInst::Min)
3856                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
3857                                    : llvm::AtomicRMWInst::UMin);
3858     break;
3859   case BO_Assign:
3860     RMWOp = llvm::AtomicRMWInst::Xchg;
3861     break;
3862   case BO_Mul:
3863   case BO_Div:
3864   case BO_Rem:
3865   case BO_Shl:
3866   case BO_Shr:
3867   case BO_LAnd:
3868   case BO_LOr:
3869     return std::make_pair(false, RValue::get(nullptr));
3870   case BO_PtrMemD:
3871   case BO_PtrMemI:
3872   case BO_LE:
3873   case BO_GE:
3874   case BO_EQ:
3875   case BO_NE:
3876   case BO_Cmp:
3877   case BO_AddAssign:
3878   case BO_SubAssign:
3879   case BO_AndAssign:
3880   case BO_OrAssign:
3881   case BO_XorAssign:
3882   case BO_MulAssign:
3883   case BO_DivAssign:
3884   case BO_RemAssign:
3885   case BO_ShlAssign:
3886   case BO_ShrAssign:
3887   case BO_Comma:
3888     llvm_unreachable("Unsupported atomic update operation");
3889   }
3890   llvm::Value *UpdateVal = Update.getScalarVal();
3891   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
3892     UpdateVal = CGF.Builder.CreateIntCast(
3893         IC, X.getAddress().getElementType(),
3894         X.getType()->hasSignedIntegerRepresentation());
3895   }
3896   llvm::Value *Res =
3897       CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
3898   return std::make_pair(true, RValue::get(Res));
3899 }
3900 
3901 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
3902     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3903     llvm::AtomicOrdering AO, SourceLocation Loc,
3904     const llvm::function_ref<RValue(RValue)> CommonGen) {
3905   // Update expressions are allowed to have the following forms:
3906   // x binop= expr; -> xrval + expr;
3907   // x++, ++x -> xrval + 1;
3908   // x--, --x -> xrval - 1;
3909   // x = x binop expr; -> xrval binop expr
3910   // x = expr Op x; - > expr binop xrval;
3911   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
3912   if (!Res.first) {
3913     if (X.isGlobalReg()) {
3914       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
3915       // 'xrval'.
3916       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
3917     } else {
3918       // Perform compare-and-swap procedure.
3919       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
3920     }
3921   }
3922   return Res;
3923 }
3924 
3925 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
3926                                     const Expr *X, const Expr *E,
3927                                     const Expr *UE, bool IsXLHSInRHSPart,
3928                                     SourceLocation Loc) {
3929   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3930          "Update expr in 'atomic update' must be a binary operator.");
3931   const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
3932   // Update expressions are allowed to have the following forms:
3933   // x binop= expr; -> xrval + expr;
3934   // x++, ++x -> xrval + 1;
3935   // x--, --x -> xrval - 1;
3936   // x = x binop expr; -> xrval binop expr
3937   // x = expr Op x; - > expr binop xrval;
3938   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
3939   LValue XLValue = CGF.EmitLValue(X);
3940   RValue ExprRValue = CGF.EmitAnyExpr(E);
3941   llvm::AtomicOrdering AO = IsSeqCst
3942                                 ? llvm::AtomicOrdering::SequentiallyConsistent
3943                                 : llvm::AtomicOrdering::Monotonic;
3944   const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
3945   const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
3946   const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
3947   const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
3948   auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
3949     CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
3950     CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
3951     return CGF.EmitAnyExpr(UE);
3952   };
3953   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
3954       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
3955   // OpenMP, 2.12.6, atomic Construct
3956   // Any atomic construct with a seq_cst clause forces the atomically
3957   // performed operation to include an implicit flush operation without a
3958   // list.
3959   if (IsSeqCst)
3960     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
3961 }
3962 
3963 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
3964                             QualType SourceType, QualType ResType,
3965                             SourceLocation Loc) {
3966   switch (CGF.getEvaluationKind(ResType)) {
3967   case TEK_Scalar:
3968     return RValue::get(
3969         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
3970   case TEK_Complex: {
3971     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
3972     return RValue::getComplex(Res.first, Res.second);
3973   }
3974   case TEK_Aggregate:
3975     break;
3976   }
3977   llvm_unreachable("Must be a scalar or complex.");
3978 }
3979 
3980 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
3981                                      bool IsPostfixUpdate, const Expr *V,
3982                                      const Expr *X, const Expr *E,
3983                                      const Expr *UE, bool IsXLHSInRHSPart,
3984                                      SourceLocation Loc) {
3985   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
3986   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
3987   RValue NewVVal;
3988   LValue VLValue = CGF.EmitLValue(V);
3989   LValue XLValue = CGF.EmitLValue(X);
3990   RValue ExprRValue = CGF.EmitAnyExpr(E);
3991   llvm::AtomicOrdering AO = IsSeqCst
3992                                 ? llvm::AtomicOrdering::SequentiallyConsistent
3993                                 : llvm::AtomicOrdering::Monotonic;
3994   QualType NewVValType;
3995   if (UE) {
3996     // 'x' is updated with some additional value.
3997     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
3998            "Update expr in 'atomic capture' must be a binary operator.");
3999     const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
4000     // Update expressions are allowed to have the following forms:
4001     // x binop= expr; -> xrval + expr;
4002     // x++, ++x -> xrval + 1;
4003     // x--, --x -> xrval - 1;
4004     // x = x binop expr; -> xrval binop expr
4005     // x = expr Op x; - > expr binop xrval;
4006     const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4007     const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4008     const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4009     NewVValType = XRValExpr->getType();
4010     const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4011     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
4012                   IsPostfixUpdate](RValue XRValue) {
4013       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4014       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4015       RValue Res = CGF.EmitAnyExpr(UE);
4016       NewVVal = IsPostfixUpdate ? XRValue : Res;
4017       return Res;
4018     };
4019     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4020         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4021     if (Res.first) {
4022       // 'atomicrmw' instruction was generated.
4023       if (IsPostfixUpdate) {
4024         // Use old value from 'atomicrmw'.
4025         NewVVal = Res.second;
4026       } else {
4027         // 'atomicrmw' does not provide new value, so evaluate it using old
4028         // value of 'x'.
4029         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4030         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4031         NewVVal = CGF.EmitAnyExpr(UE);
4032       }
4033     }
4034   } else {
4035     // 'x' is simply rewritten with some 'expr'.
4036     NewVValType = X->getType().getNonReferenceType();
4037     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
4038                                X->getType().getNonReferenceType(), Loc);
4039     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
4040       NewVVal = XRValue;
4041       return ExprRValue;
4042     };
4043     // Try to perform atomicrmw xchg, otherwise simple exchange.
4044     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4045         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4046         Loc, Gen);
4047     if (Res.first) {
4048       // 'atomicrmw' instruction was generated.
4049       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4050     }
4051   }
4052   // Emit post-update store to 'v' of old/new 'x' value.
4053   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
4054   // OpenMP, 2.12.6, atomic Construct
4055   // Any atomic construct with a seq_cst clause forces the atomically
4056   // performed operation to include an implicit flush operation without a
4057   // list.
4058   if (IsSeqCst)
4059     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
4060 }
4061 
4062 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
4063                               bool IsSeqCst, bool IsPostfixUpdate,
4064                               const Expr *X, const Expr *V, const Expr *E,
4065                               const Expr *UE, bool IsXLHSInRHSPart,
4066                               SourceLocation Loc) {
4067   switch (Kind) {
4068   case OMPC_read:
4069     emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
4070     break;
4071   case OMPC_write:
4072     emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
4073     break;
4074   case OMPC_unknown:
4075   case OMPC_update:
4076     emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
4077     break;
4078   case OMPC_capture:
4079     emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
4080                              IsXLHSInRHSPart, Loc);
4081     break;
4082   case OMPC_if:
4083   case OMPC_final:
4084   case OMPC_num_threads:
4085   case OMPC_private:
4086   case OMPC_firstprivate:
4087   case OMPC_lastprivate:
4088   case OMPC_reduction:
4089   case OMPC_task_reduction:
4090   case OMPC_in_reduction:
4091   case OMPC_safelen:
4092   case OMPC_simdlen:
4093   case OMPC_allocator:
4094   case OMPC_allocate:
4095   case OMPC_collapse:
4096   case OMPC_default:
4097   case OMPC_seq_cst:
4098   case OMPC_shared:
4099   case OMPC_linear:
4100   case OMPC_aligned:
4101   case OMPC_copyin:
4102   case OMPC_copyprivate:
4103   case OMPC_flush:
4104   case OMPC_proc_bind:
4105   case OMPC_schedule:
4106   case OMPC_ordered:
4107   case OMPC_nowait:
4108   case OMPC_untied:
4109   case OMPC_threadprivate:
4110   case OMPC_depend:
4111   case OMPC_mergeable:
4112   case OMPC_device:
4113   case OMPC_threads:
4114   case OMPC_simd:
4115   case OMPC_map:
4116   case OMPC_num_teams:
4117   case OMPC_thread_limit:
4118   case OMPC_priority:
4119   case OMPC_grainsize:
4120   case OMPC_nogroup:
4121   case OMPC_num_tasks:
4122   case OMPC_hint:
4123   case OMPC_dist_schedule:
4124   case OMPC_defaultmap:
4125   case OMPC_uniform:
4126   case OMPC_to:
4127   case OMPC_from:
4128   case OMPC_use_device_ptr:
4129   case OMPC_is_device_ptr:
4130   case OMPC_unified_address:
4131   case OMPC_unified_shared_memory:
4132   case OMPC_reverse_offload:
4133   case OMPC_dynamic_allocators:
4134   case OMPC_atomic_default_mem_order:
4135   case OMPC_device_type:
4136   case OMPC_match:
4137     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4138   }
4139 }
4140 
4141 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
4142   bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
4143   OpenMPClauseKind Kind = OMPC_unknown;
4144   for (const OMPClause *C : S.clauses()) {
4145     // Find first clause (skip seq_cst clause, if it is first).
4146     if (C->getClauseKind() != OMPC_seq_cst) {
4147       Kind = C->getClauseKind();
4148       break;
4149     }
4150   }
4151 
4152   const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
4153   if (const auto *FE = dyn_cast<FullExpr>(CS))
4154     enterFullExpression(FE);
4155   // Processing for statements under 'atomic capture'.
4156   if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
4157     for (const Stmt *C : Compound->body()) {
4158       if (const auto *FE = dyn_cast<FullExpr>(C))
4159         enterFullExpression(FE);
4160     }
4161   }
4162 
4163   auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
4164                                             PrePostActionTy &) {
4165     CGF.EmitStopPoint(CS);
4166     emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
4167                       S.getV(), S.getExpr(), S.getUpdateExpr(),
4168                       S.isXLHSInRHSPart(), S.getBeginLoc());
4169   };
4170   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4171   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
4172 }
4173 
4174 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4175                                          const OMPExecutableDirective &S,
4176                                          const RegionCodeGenTy &CodeGen) {
4177   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4178   CodeGenModule &CGM = CGF.CGM;
4179 
4180   // On device emit this construct as inlined code.
4181   if (CGM.getLangOpts().OpenMPIsDevice) {
4182     OMPLexicalScope Scope(CGF, S, OMPD_target);
4183     CGM.getOpenMPRuntime().emitInlinedDirective(
4184         CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4185           CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4186         });
4187     return;
4188   }
4189 
4190   llvm::Function *Fn = nullptr;
4191   llvm::Constant *FnID = nullptr;
4192 
4193   const Expr *IfCond = nullptr;
4194   // Check for the at most one if clause associated with the target region.
4195   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4196     if (C->getNameModifier() == OMPD_unknown ||
4197         C->getNameModifier() == OMPD_target) {
4198       IfCond = C->getCondition();
4199       break;
4200     }
4201   }
4202 
4203   // Check if we have any device clause associated with the directive.
4204   const Expr *Device = nullptr;
4205   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4206     Device = C->getDevice();
4207 
4208   // Check if we have an if clause whose conditional always evaluates to false
4209   // or if we do not have any targets specified. If so the target region is not
4210   // an offload entry point.
4211   bool IsOffloadEntry = true;
4212   if (IfCond) {
4213     bool Val;
4214     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
4215       IsOffloadEntry = false;
4216   }
4217   if (CGM.getLangOpts().OMPTargetTriples.empty())
4218     IsOffloadEntry = false;
4219 
4220   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
4221   StringRef ParentName;
4222   // In case we have Ctors/Dtors we use the complete type variant to produce
4223   // the mangling of the device outlined kernel.
4224   if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
4225     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
4226   else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
4227     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4228   else
4229     ParentName =
4230         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
4231 
4232   // Emit target region as a standalone region.
4233   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4234                                                     IsOffloadEntry, CodeGen);
4235   OMPLexicalScope Scope(CGF, S, OMPD_task);
4236   auto &&SizeEmitter =
4237       [IsOffloadEntry](CodeGenFunction &CGF,
4238                        const OMPLoopDirective &D) -> llvm::Value * {
4239     if (IsOffloadEntry) {
4240       OMPLoopScope(CGF, D);
4241       // Emit calculation of the iterations count.
4242       llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4243       NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4244                                                 /*isSigned=*/false);
4245       return NumIterations;
4246     }
4247     return nullptr;
4248   };
4249   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4250                                         SizeEmitter);
4251 }
4252 
4253 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4254                              PrePostActionTy &Action) {
4255   Action.Enter(CGF);
4256   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4257   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4258   CGF.EmitOMPPrivateClause(S, PrivateScope);
4259   (void)PrivateScope.Privatize();
4260   if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4261     CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4262 
4263   CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
4264 }
4265 
4266 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4267                                                   StringRef ParentName,
4268                                                   const OMPTargetDirective &S) {
4269   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4270     emitTargetRegion(CGF, S, Action);
4271   };
4272   llvm::Function *Fn;
4273   llvm::Constant *Addr;
4274   // Emit target region as a standalone region.
4275   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4276       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4277   assert(Fn && Addr && "Target device function emission failed.");
4278 }
4279 
4280 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4281   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4282     emitTargetRegion(CGF, S, Action);
4283   };
4284   emitCommonOMPTargetDirective(*this, S, CodeGen);
4285 }
4286 
4287 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4288                                         const OMPExecutableDirective &S,
4289                                         OpenMPDirectiveKind InnermostKind,
4290                                         const RegionCodeGenTy &CodeGen) {
4291   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4292   llvm::Function *OutlinedFn =
4293       CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4294           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
4295 
4296   const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4297   const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
4298   if (NT || TL) {
4299     const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4300     const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
4301 
4302     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4303                                                   S.getBeginLoc());
4304   }
4305 
4306   OMPTeamsScope Scope(CGF, S);
4307   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4308   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
4309   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
4310                                            CapturedVars);
4311 }
4312 
4313 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
4314   // Emit teams region as a standalone region.
4315   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4316     Action.Enter(CGF);
4317     OMPPrivateScope PrivateScope(CGF);
4318     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4319     CGF.EmitOMPPrivateClause(S, PrivateScope);
4320     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4321     (void)PrivateScope.Privatize();
4322     CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
4323     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4324   };
4325   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4326   emitPostUpdateForReductionClause(*this, S,
4327                                    [](CodeGenFunction &) { return nullptr; });
4328 }
4329 
4330 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4331                                   const OMPTargetTeamsDirective &S) {
4332   auto *CS = S.getCapturedStmt(OMPD_teams);
4333   Action.Enter(CGF);
4334   // Emit teams region as a standalone region.
4335   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4336     Action.Enter(CGF);
4337     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4338     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4339     CGF.EmitOMPPrivateClause(S, PrivateScope);
4340     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4341     (void)PrivateScope.Privatize();
4342     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4343       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4344     CGF.EmitStmt(CS->getCapturedStmt());
4345     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4346   };
4347   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
4348   emitPostUpdateForReductionClause(CGF, S,
4349                                    [](CodeGenFunction &) { return nullptr; });
4350 }
4351 
4352 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4353     CodeGenModule &CGM, StringRef ParentName,
4354     const OMPTargetTeamsDirective &S) {
4355   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4356     emitTargetTeamsRegion(CGF, Action, S);
4357   };
4358   llvm::Function *Fn;
4359   llvm::Constant *Addr;
4360   // Emit target region as a standalone region.
4361   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4362       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4363   assert(Fn && Addr && "Target device function emission failed.");
4364 }
4365 
4366 void CodeGenFunction::EmitOMPTargetTeamsDirective(
4367     const OMPTargetTeamsDirective &S) {
4368   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4369     emitTargetTeamsRegion(CGF, Action, S);
4370   };
4371   emitCommonOMPTargetDirective(*this, S, CodeGen);
4372 }
4373 
4374 static void
4375 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4376                                 const OMPTargetTeamsDistributeDirective &S) {
4377   Action.Enter(CGF);
4378   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4379     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4380   };
4381 
4382   // Emit teams region as a standalone region.
4383   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4384                                             PrePostActionTy &Action) {
4385     Action.Enter(CGF);
4386     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4387     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4388     (void)PrivateScope.Privatize();
4389     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4390                                                     CodeGenDistribute);
4391     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4392   };
4393   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4394   emitPostUpdateForReductionClause(CGF, S,
4395                                    [](CodeGenFunction &) { return nullptr; });
4396 }
4397 
4398 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4399     CodeGenModule &CGM, StringRef ParentName,
4400     const OMPTargetTeamsDistributeDirective &S) {
4401   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4402     emitTargetTeamsDistributeRegion(CGF, Action, S);
4403   };
4404   llvm::Function *Fn;
4405   llvm::Constant *Addr;
4406   // Emit target region as a standalone region.
4407   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4408       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4409   assert(Fn && Addr && "Target device function emission failed.");
4410 }
4411 
4412 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4413     const OMPTargetTeamsDistributeDirective &S) {
4414   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4415     emitTargetTeamsDistributeRegion(CGF, Action, S);
4416   };
4417   emitCommonOMPTargetDirective(*this, S, CodeGen);
4418 }
4419 
4420 static void emitTargetTeamsDistributeSimdRegion(
4421     CodeGenFunction &CGF, PrePostActionTy &Action,
4422     const OMPTargetTeamsDistributeSimdDirective &S) {
4423   Action.Enter(CGF);
4424   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4425     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4426   };
4427 
4428   // Emit teams region as a standalone region.
4429   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4430                                             PrePostActionTy &Action) {
4431     Action.Enter(CGF);
4432     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4433     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4434     (void)PrivateScope.Privatize();
4435     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4436                                                     CodeGenDistribute);
4437     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4438   };
4439   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4440   emitPostUpdateForReductionClause(CGF, S,
4441                                    [](CodeGenFunction &) { return nullptr; });
4442 }
4443 
4444 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4445     CodeGenModule &CGM, StringRef ParentName,
4446     const OMPTargetTeamsDistributeSimdDirective &S) {
4447   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4448     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4449   };
4450   llvm::Function *Fn;
4451   llvm::Constant *Addr;
4452   // Emit target region as a standalone region.
4453   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4454       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4455   assert(Fn && Addr && "Target device function emission failed.");
4456 }
4457 
4458 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4459     const OMPTargetTeamsDistributeSimdDirective &S) {
4460   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4461     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4462   };
4463   emitCommonOMPTargetDirective(*this, S, CodeGen);
4464 }
4465 
4466 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4467     const OMPTeamsDistributeDirective &S) {
4468 
4469   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4470     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4471   };
4472 
4473   // Emit teams region as a standalone region.
4474   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4475                                             PrePostActionTy &Action) {
4476     Action.Enter(CGF);
4477     OMPPrivateScope PrivateScope(CGF);
4478     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4479     (void)PrivateScope.Privatize();
4480     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4481                                                     CodeGenDistribute);
4482     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4483   };
4484   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4485   emitPostUpdateForReductionClause(*this, S,
4486                                    [](CodeGenFunction &) { return nullptr; });
4487 }
4488 
4489 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4490     const OMPTeamsDistributeSimdDirective &S) {
4491   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4492     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4493   };
4494 
4495   // Emit teams region as a standalone region.
4496   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4497                                             PrePostActionTy &Action) {
4498     Action.Enter(CGF);
4499     OMPPrivateScope PrivateScope(CGF);
4500     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4501     (void)PrivateScope.Privatize();
4502     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4503                                                     CodeGenDistribute);
4504     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4505   };
4506   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4507   emitPostUpdateForReductionClause(*this, S,
4508                                    [](CodeGenFunction &) { return nullptr; });
4509 }
4510 
4511 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4512     const OMPTeamsDistributeParallelForDirective &S) {
4513   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4514     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4515                               S.getDistInc());
4516   };
4517 
4518   // Emit teams region as a standalone region.
4519   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4520                                             PrePostActionTy &Action) {
4521     Action.Enter(CGF);
4522     OMPPrivateScope PrivateScope(CGF);
4523     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4524     (void)PrivateScope.Privatize();
4525     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4526                                                     CodeGenDistribute);
4527     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4528   };
4529   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4530   emitPostUpdateForReductionClause(*this, S,
4531                                    [](CodeGenFunction &) { return nullptr; });
4532 }
4533 
4534 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4535     const OMPTeamsDistributeParallelForSimdDirective &S) {
4536   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4537     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4538                               S.getDistInc());
4539   };
4540 
4541   // Emit teams region as a standalone region.
4542   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4543                                             PrePostActionTy &Action) {
4544     Action.Enter(CGF);
4545     OMPPrivateScope PrivateScope(CGF);
4546     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4547     (void)PrivateScope.Privatize();
4548     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4549         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4550     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4551   };
4552   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4553   emitPostUpdateForReductionClause(*this, S,
4554                                    [](CodeGenFunction &) { return nullptr; });
4555 }
4556 
4557 static void emitTargetTeamsDistributeParallelForRegion(
4558     CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4559     PrePostActionTy &Action) {
4560   Action.Enter(CGF);
4561   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4562     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4563                               S.getDistInc());
4564   };
4565 
4566   // Emit teams region as a standalone region.
4567   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4568                                                  PrePostActionTy &Action) {
4569     Action.Enter(CGF);
4570     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4571     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4572     (void)PrivateScope.Privatize();
4573     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4574         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4575     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4576   };
4577 
4578   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4579                               CodeGenTeams);
4580   emitPostUpdateForReductionClause(CGF, S,
4581                                    [](CodeGenFunction &) { return nullptr; });
4582 }
4583 
4584 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
4585     CodeGenModule &CGM, StringRef ParentName,
4586     const OMPTargetTeamsDistributeParallelForDirective &S) {
4587   // Emit SPMD target teams distribute parallel for region as a standalone
4588   // region.
4589   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4590     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4591   };
4592   llvm::Function *Fn;
4593   llvm::Constant *Addr;
4594   // Emit target region as a standalone region.
4595   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4596       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4597   assert(Fn && Addr && "Target device function emission failed.");
4598 }
4599 
4600 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
4601     const OMPTargetTeamsDistributeParallelForDirective &S) {
4602   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4603     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
4604   };
4605   emitCommonOMPTargetDirective(*this, S, CodeGen);
4606 }
4607 
4608 static void emitTargetTeamsDistributeParallelForSimdRegion(
4609     CodeGenFunction &CGF,
4610     const OMPTargetTeamsDistributeParallelForSimdDirective &S,
4611     PrePostActionTy &Action) {
4612   Action.Enter(CGF);
4613   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4614     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4615                               S.getDistInc());
4616   };
4617 
4618   // Emit teams region as a standalone region.
4619   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4620                                                  PrePostActionTy &Action) {
4621     Action.Enter(CGF);
4622     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4623     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4624     (void)PrivateScope.Privatize();
4625     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4626         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4627     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4628   };
4629 
4630   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
4631                               CodeGenTeams);
4632   emitPostUpdateForReductionClause(CGF, S,
4633                                    [](CodeGenFunction &) { return nullptr; });
4634 }
4635 
4636 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
4637     CodeGenModule &CGM, StringRef ParentName,
4638     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4639   // Emit SPMD target teams distribute parallel for simd region as a standalone
4640   // region.
4641   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4642     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4643   };
4644   llvm::Function *Fn;
4645   llvm::Constant *Addr;
4646   // Emit target region as a standalone region.
4647   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4648       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4649   assert(Fn && Addr && "Target device function emission failed.");
4650 }
4651 
4652 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
4653     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
4654   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4655     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
4656   };
4657   emitCommonOMPTargetDirective(*this, S, CodeGen);
4658 }
4659 
4660 void CodeGenFunction::EmitOMPCancellationPointDirective(
4661     const OMPCancellationPointDirective &S) {
4662   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
4663                                                    S.getCancelRegion());
4664 }
4665 
4666 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
4667   const Expr *IfCond = nullptr;
4668   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4669     if (C->getNameModifier() == OMPD_unknown ||
4670         C->getNameModifier() == OMPD_cancel) {
4671       IfCond = C->getCondition();
4672       break;
4673     }
4674   }
4675   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
4676                                         S.getCancelRegion());
4677 }
4678 
4679 CodeGenFunction::JumpDest
4680 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
4681   if (Kind == OMPD_parallel || Kind == OMPD_task ||
4682       Kind == OMPD_target_parallel)
4683     return ReturnBlock;
4684   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
4685          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
4686          Kind == OMPD_distribute_parallel_for ||
4687          Kind == OMPD_target_parallel_for ||
4688          Kind == OMPD_teams_distribute_parallel_for ||
4689          Kind == OMPD_target_teams_distribute_parallel_for);
4690   return OMPCancelStack.getExitBlock();
4691 }
4692 
4693 void CodeGenFunction::EmitOMPUseDevicePtrClause(
4694     const OMPClause &NC, OMPPrivateScope &PrivateScope,
4695     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
4696   const auto &C = cast<OMPUseDevicePtrClause>(NC);
4697   auto OrigVarIt = C.varlist_begin();
4698   auto InitIt = C.inits().begin();
4699   for (const Expr *PvtVarIt : C.private_copies()) {
4700     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
4701     const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
4702     const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
4703 
4704     // In order to identify the right initializer we need to match the
4705     // declaration used by the mapping logic. In some cases we may get
4706     // OMPCapturedExprDecl that refers to the original declaration.
4707     const ValueDecl *MatchingVD = OrigVD;
4708     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
4709       // OMPCapturedExprDecl are used to privative fields of the current
4710       // structure.
4711       const auto *ME = cast<MemberExpr>(OED->getInit());
4712       assert(isa<CXXThisExpr>(ME->getBase()) &&
4713              "Base should be the current struct!");
4714       MatchingVD = ME->getMemberDecl();
4715     }
4716 
4717     // If we don't have information about the current list item, move on to
4718     // the next one.
4719     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
4720     if (InitAddrIt == CaptureDeviceAddrMap.end())
4721       continue;
4722 
4723     bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
4724                                                          InitAddrIt, InitVD,
4725                                                          PvtVD]() {
4726       // Initialize the temporary initialization variable with the address we
4727       // get from the runtime library. We have to cast the source address
4728       // because it is always a void *. References are materialized in the
4729       // privatization scope, so the initialization here disregards the fact
4730       // the original variable is a reference.
4731       QualType AddrQTy =
4732           getContext().getPointerType(OrigVD->getType().getNonReferenceType());
4733       llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
4734       Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
4735       setAddrOfLocalVar(InitVD, InitAddr);
4736 
4737       // Emit private declaration, it will be initialized by the value we
4738       // declaration we just added to the local declarations map.
4739       EmitDecl(*PvtVD);
4740 
4741       // The initialization variables reached its purpose in the emission
4742       // of the previous declaration, so we don't need it anymore.
4743       LocalDeclMap.erase(InitVD);
4744 
4745       // Return the address of the private variable.
4746       return GetAddrOfLocalVar(PvtVD);
4747     });
4748     assert(IsRegistered && "firstprivate var already registered as private");
4749     // Silence the warning about unused variable.
4750     (void)IsRegistered;
4751 
4752     ++OrigVarIt;
4753     ++InitIt;
4754   }
4755 }
4756 
4757 // Generate the instructions for '#pragma omp target data' directive.
4758 void CodeGenFunction::EmitOMPTargetDataDirective(
4759     const OMPTargetDataDirective &S) {
4760   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
4761 
4762   // Create a pre/post action to signal the privatization of the device pointer.
4763   // This action can be replaced by the OpenMP runtime code generation to
4764   // deactivate privatization.
4765   bool PrivatizeDevicePointers = false;
4766   class DevicePointerPrivActionTy : public PrePostActionTy {
4767     bool &PrivatizeDevicePointers;
4768 
4769   public:
4770     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
4771         : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
4772     void Enter(CodeGenFunction &CGF) override {
4773       PrivatizeDevicePointers = true;
4774     }
4775   };
4776   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
4777 
4778   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
4779                        CodeGenFunction &CGF, PrePostActionTy &Action) {
4780     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4781       CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4782     };
4783 
4784     // Codegen that selects whether to generate the privatization code or not.
4785     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
4786                           &InnermostCodeGen](CodeGenFunction &CGF,
4787                                              PrePostActionTy &Action) {
4788       RegionCodeGenTy RCG(InnermostCodeGen);
4789       PrivatizeDevicePointers = false;
4790 
4791       // Call the pre-action to change the status of PrivatizeDevicePointers if
4792       // needed.
4793       Action.Enter(CGF);
4794 
4795       if (PrivatizeDevicePointers) {
4796         OMPPrivateScope PrivateScope(CGF);
4797         // Emit all instances of the use_device_ptr clause.
4798         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
4799           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
4800                                         Info.CaptureDeviceAddrMap);
4801         (void)PrivateScope.Privatize();
4802         RCG(CGF);
4803       } else {
4804         RCG(CGF);
4805       }
4806     };
4807 
4808     // Forward the provided action to the privatization codegen.
4809     RegionCodeGenTy PrivRCG(PrivCodeGen);
4810     PrivRCG.setAction(Action);
4811 
4812     // Notwithstanding the body of the region is emitted as inlined directive,
4813     // we don't use an inline scope as changes in the references inside the
4814     // region are expected to be visible outside, so we do not privative them.
4815     OMPLexicalScope Scope(CGF, S);
4816     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
4817                                                     PrivRCG);
4818   };
4819 
4820   RegionCodeGenTy RCG(CodeGen);
4821 
4822   // If we don't have target devices, don't bother emitting the data mapping
4823   // code.
4824   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
4825     RCG(*this);
4826     return;
4827   }
4828 
4829   // Check if we have any if clause associated with the directive.
4830   const Expr *IfCond = nullptr;
4831   if (const auto *C = S.getSingleClause<OMPIfClause>())
4832     IfCond = C->getCondition();
4833 
4834   // Check if we have any device clause associated with the directive.
4835   const Expr *Device = nullptr;
4836   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
4837     Device = C->getDevice();
4838 
4839   // Set the action to signal privatization of device pointers.
4840   RCG.setAction(PrivAction);
4841 
4842   // Emit region code.
4843   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
4844                                              Info);
4845 }
4846 
4847 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
4848     const OMPTargetEnterDataDirective &S) {
4849   // If we don't have target devices, don't bother emitting the data mapping
4850   // code.
4851   if (CGM.getLangOpts().OMPTargetTriples.empty())
4852     return;
4853 
4854   // Check if we have any if clause associated with the directive.
4855   const Expr *IfCond = nullptr;
4856   if (const auto *C = S.getSingleClause<OMPIfClause>())
4857     IfCond = C->getCondition();
4858 
4859   // Check if we have any device clause associated with the directive.
4860   const Expr *Device = nullptr;
4861   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
4862     Device = C->getDevice();
4863 
4864   OMPLexicalScope Scope(*this, S, OMPD_task);
4865   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
4866 }
4867 
4868 void CodeGenFunction::EmitOMPTargetExitDataDirective(
4869     const OMPTargetExitDataDirective &S) {
4870   // If we don't have target devices, don't bother emitting the data mapping
4871   // code.
4872   if (CGM.getLangOpts().OMPTargetTriples.empty())
4873     return;
4874 
4875   // Check if we have any if clause associated with the directive.
4876   const Expr *IfCond = nullptr;
4877   if (const auto *C = S.getSingleClause<OMPIfClause>())
4878     IfCond = C->getCondition();
4879 
4880   // Check if we have any device clause associated with the directive.
4881   const Expr *Device = nullptr;
4882   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
4883     Device = C->getDevice();
4884 
4885   OMPLexicalScope Scope(*this, S, OMPD_task);
4886   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
4887 }
4888 
4889 static void emitTargetParallelRegion(CodeGenFunction &CGF,
4890                                      const OMPTargetParallelDirective &S,
4891                                      PrePostActionTy &Action) {
4892   // Get the captured statement associated with the 'parallel' region.
4893   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
4894   Action.Enter(CGF);
4895   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4896     Action.Enter(CGF);
4897     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4898     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4899     CGF.EmitOMPPrivateClause(S, PrivateScope);
4900     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4901     (void)PrivateScope.Privatize();
4902     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4903       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4904     // TODO: Add support for clauses.
4905     CGF.EmitStmt(CS->getCapturedStmt());
4906     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4907   };
4908   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
4909                                  emitEmptyBoundParameters);
4910   emitPostUpdateForReductionClause(CGF, S,
4911                                    [](CodeGenFunction &) { return nullptr; });
4912 }
4913 
4914 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
4915     CodeGenModule &CGM, StringRef ParentName,
4916     const OMPTargetParallelDirective &S) {
4917   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4918     emitTargetParallelRegion(CGF, S, Action);
4919   };
4920   llvm::Function *Fn;
4921   llvm::Constant *Addr;
4922   // Emit target region as a standalone region.
4923   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4924       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4925   assert(Fn && Addr && "Target device function emission failed.");
4926 }
4927 
4928 void CodeGenFunction::EmitOMPTargetParallelDirective(
4929     const OMPTargetParallelDirective &S) {
4930   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4931     emitTargetParallelRegion(CGF, S, Action);
4932   };
4933   emitCommonOMPTargetDirective(*this, S, CodeGen);
4934 }
4935 
4936 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
4937                                         const OMPTargetParallelForDirective &S,
4938                                         PrePostActionTy &Action) {
4939   Action.Enter(CGF);
4940   // Emit directive as a combined directive that consists of two implicit
4941   // directives: 'parallel' with 'for' directive.
4942   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4943     Action.Enter(CGF);
4944     CodeGenFunction::OMPCancelStackRAII CancelRegion(
4945         CGF, OMPD_target_parallel_for, S.hasCancel());
4946     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4947                                emitDispatchForLoopBounds);
4948   };
4949   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
4950                                  emitEmptyBoundParameters);
4951 }
4952 
4953 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
4954     CodeGenModule &CGM, StringRef ParentName,
4955     const OMPTargetParallelForDirective &S) {
4956   // Emit SPMD target parallel for region as a standalone region.
4957   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4958     emitTargetParallelForRegion(CGF, S, Action);
4959   };
4960   llvm::Function *Fn;
4961   llvm::Constant *Addr;
4962   // Emit target region as a standalone region.
4963   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4964       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4965   assert(Fn && Addr && "Target device function emission failed.");
4966 }
4967 
4968 void CodeGenFunction::EmitOMPTargetParallelForDirective(
4969     const OMPTargetParallelForDirective &S) {
4970   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4971     emitTargetParallelForRegion(CGF, S, Action);
4972   };
4973   emitCommonOMPTargetDirective(*this, S, CodeGen);
4974 }
4975 
4976 static void
4977 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
4978                                 const OMPTargetParallelForSimdDirective &S,
4979                                 PrePostActionTy &Action) {
4980   Action.Enter(CGF);
4981   // Emit directive as a combined directive that consists of two implicit
4982   // directives: 'parallel' with 'for' directive.
4983   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4984     Action.Enter(CGF);
4985     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
4986                                emitDispatchForLoopBounds);
4987   };
4988   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
4989                                  emitEmptyBoundParameters);
4990 }
4991 
4992 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
4993     CodeGenModule &CGM, StringRef ParentName,
4994     const OMPTargetParallelForSimdDirective &S) {
4995   // Emit SPMD target parallel for region as a standalone region.
4996   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4997     emitTargetParallelForSimdRegion(CGF, S, Action);
4998   };
4999   llvm::Function *Fn;
5000   llvm::Constant *Addr;
5001   // Emit target region as a standalone region.
5002   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5003       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5004   assert(Fn && Addr && "Target device function emission failed.");
5005 }
5006 
5007 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5008     const OMPTargetParallelForSimdDirective &S) {
5009   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5010     emitTargetParallelForSimdRegion(CGF, S, Action);
5011   };
5012   emitCommonOMPTargetDirective(*this, S, CodeGen);
5013 }
5014 
5015 /// Emit a helper variable and return corresponding lvalue.
5016 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5017                      const ImplicitParamDecl *PVD,
5018                      CodeGenFunction::OMPPrivateScope &Privates) {
5019   const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5020   Privates.addPrivate(VDecl,
5021                       [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
5022 }
5023 
5024 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5025   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5026   // Emit outlined function for task construct.
5027   const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
5028   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5029   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
5030   const Expr *IfCond = nullptr;
5031   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5032     if (C->getNameModifier() == OMPD_unknown ||
5033         C->getNameModifier() == OMPD_taskloop) {
5034       IfCond = C->getCondition();
5035       break;
5036     }
5037   }
5038 
5039   OMPTaskDataTy Data;
5040   // Check if taskloop must be emitted without taskgroup.
5041   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
5042   // TODO: Check if we should emit tied or untied task.
5043   Data.Tied = true;
5044   // Set scheduling for taskloop
5045   if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5046     // grainsize clause
5047     Data.Schedule.setInt(/*IntVal=*/false);
5048     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
5049   } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5050     // num_tasks clause
5051     Data.Schedule.setInt(/*IntVal=*/true);
5052     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
5053   }
5054 
5055   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5056     // if (PreCond) {
5057     //   for (IV in 0..LastIteration) BODY;
5058     //   <Final counter/linear vars updates>;
5059     // }
5060     //
5061 
5062     // Emit: if (PreCond) - begin.
5063     // If the condition constant folds and can be elided, avoid emitting the
5064     // whole loop.
5065     bool CondConstant;
5066     llvm::BasicBlock *ContBlock = nullptr;
5067     OMPLoopScope PreInitScope(CGF, S);
5068     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5069       if (!CondConstant)
5070         return;
5071     } else {
5072       llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
5073       ContBlock = CGF.createBasicBlock("taskloop.if.end");
5074       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5075                   CGF.getProfileCount(&S));
5076       CGF.EmitBlock(ThenBlock);
5077       CGF.incrementProfileCounter(&S);
5078     }
5079 
5080     if (isOpenMPSimdDirective(S.getDirectiveKind())) {
5081       CGF.EmitOMPSimdInit(S);
5082       (void)CGF.EmitOMPLinearClauseInit(S);
5083     }
5084 
5085     OMPPrivateScope LoopScope(CGF);
5086     // Emit helper vars inits.
5087     enum { LowerBound = 5, UpperBound, Stride, LastIter };
5088     auto *I = CS->getCapturedDecl()->param_begin();
5089     auto *LBP = std::next(I, LowerBound);
5090     auto *UBP = std::next(I, UpperBound);
5091     auto *STP = std::next(I, Stride);
5092     auto *LIP = std::next(I, LastIter);
5093     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5094              LoopScope);
5095     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5096              LoopScope);
5097     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5098     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5099              LoopScope);
5100     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
5101     CGF.EmitOMPLinearClause(S, LoopScope);
5102     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
5103     (void)LoopScope.Privatize();
5104     // Emit the loop iteration variable.
5105     const Expr *IVExpr = S.getIterationVariable();
5106     const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
5107     CGF.EmitVarDecl(*IVDecl);
5108     CGF.EmitIgnoredExpr(S.getInit());
5109 
5110     // Emit the iterations count variable.
5111     // If it is not a variable, Sema decided to calculate iterations count on
5112     // each iteration (e.g., it is foldable into a constant).
5113     if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5114       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5115       // Emit calculation of the iterations count.
5116       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5117     }
5118 
5119     CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
5120                          S.getInc(),
5121                          [&S](CodeGenFunction &CGF) {
5122                            CGF.EmitOMPLoopBody(S, JumpDest());
5123                            CGF.EmitStopPoint(&S);
5124                          },
5125                          [](CodeGenFunction &) {});
5126     // Emit: if (PreCond) - end.
5127     if (ContBlock) {
5128       CGF.EmitBranch(ContBlock);
5129       CGF.EmitBlock(ContBlock, true);
5130     }
5131     // Emit final copy of the lastprivate variables if IsLastIter != 0.
5132     if (HasLastprivateClause) {
5133       CGF.EmitOMPLastprivateClauseFinal(
5134           S, isOpenMPSimdDirective(S.getDirectiveKind()),
5135           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5136               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5137               (*LIP)->getType(), S.getBeginLoc())));
5138     }
5139     CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5140       return CGF.Builder.CreateIsNotNull(
5141           CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5142                                (*LIP)->getType(), S.getBeginLoc()));
5143     });
5144   };
5145   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
5146                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
5147                             const OMPTaskDataTy &Data) {
5148     auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5149                       &Data](CodeGenFunction &CGF, PrePostActionTy &) {
5150       OMPLoopScope PreInitScope(CGF, S);
5151       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
5152                                                   OutlinedFn, SharedsTy,
5153                                                   CapturedStruct, IfCond, Data);
5154     };
5155     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5156                                                     CodeGen);
5157   };
5158   if (Data.Nogroup) {
5159     EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5160   } else {
5161     CGM.getOpenMPRuntime().emitTaskgroupRegion(
5162         *this,
5163         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5164                                         PrePostActionTy &Action) {
5165           Action.Enter(CGF);
5166           CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5167                                         Data);
5168         },
5169         S.getBeginLoc());
5170   }
5171 }
5172 
5173 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
5174   EmitOMPTaskLoopBasedDirective(S);
5175 }
5176 
5177 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5178     const OMPTaskLoopSimdDirective &S) {
5179   EmitOMPTaskLoopBasedDirective(S);
5180 }
5181 
5182 void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5183     const OMPMasterTaskLoopDirective &S) {
5184   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5185     Action.Enter(CGF);
5186     EmitOMPTaskLoopBasedDirective(S);
5187   };
5188   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5189   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5190 }
5191 
5192 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5193     const OMPMasterTaskLoopSimdDirective &S) {
5194   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5195     Action.Enter(CGF);
5196     EmitOMPTaskLoopBasedDirective(S);
5197   };
5198   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5199   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5200 }
5201 
5202 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5203     const OMPParallelMasterTaskLoopDirective &S) {
5204   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5205     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5206                                   PrePostActionTy &Action) {
5207       Action.Enter(CGF);
5208       CGF.EmitOMPTaskLoopBasedDirective(S);
5209     };
5210     OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5211     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5212                                             S.getBeginLoc());
5213   };
5214   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5215                                  emitEmptyBoundParameters);
5216 }
5217 
5218 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5219     const OMPParallelMasterTaskLoopSimdDirective &S) {
5220   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5221     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5222                                   PrePostActionTy &Action) {
5223       Action.Enter(CGF);
5224       CGF.EmitOMPTaskLoopBasedDirective(S);
5225     };
5226     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5227     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5228                                             S.getBeginLoc());
5229   };
5230   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5231                                  emitEmptyBoundParameters);
5232 }
5233 
5234 // Generate the instructions for '#pragma omp target update' directive.
5235 void CodeGenFunction::EmitOMPTargetUpdateDirective(
5236     const OMPTargetUpdateDirective &S) {
5237   // If we don't have target devices, don't bother emitting the data mapping
5238   // code.
5239   if (CGM.getLangOpts().OMPTargetTriples.empty())
5240     return;
5241 
5242   // Check if we have any if clause associated with the directive.
5243   const Expr *IfCond = nullptr;
5244   if (const auto *C = S.getSingleClause<OMPIfClause>())
5245     IfCond = C->getCondition();
5246 
5247   // Check if we have any device clause associated with the directive.
5248   const Expr *Device = nullptr;
5249   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5250     Device = C->getDevice();
5251 
5252   OMPLexicalScope Scope(*this, S, OMPD_task);
5253   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5254 }
5255 
5256 void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5257     const OMPExecutableDirective &D) {
5258   if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5259     return;
5260   auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5261     if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5262       emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5263     } else {
5264       OMPPrivateScope LoopGlobals(CGF);
5265       if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
5266         for (const Expr *E : LD->counters()) {
5267           const auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5268           if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5269             LValue GlobLVal = CGF.EmitLValue(E);
5270             LoopGlobals.addPrivate(
5271                 VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
5272           }
5273           if (isa<OMPCapturedExprDecl>(VD)) {
5274             // Emit only those that were not explicitly referenced in clauses.
5275             if (!CGF.LocalDeclMap.count(VD))
5276               CGF.EmitVarDecl(*VD);
5277           }
5278         }
5279         for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5280           if (!C->getNumForLoops())
5281             continue;
5282           for (unsigned I = LD->getCollapsedNumber(),
5283                         E = C->getLoopNumIterations().size();
5284                I < E; ++I) {
5285             if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
5286                     cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
5287               // Emit only those that were not explicitly referenced in clauses.
5288               if (!CGF.LocalDeclMap.count(VD))
5289                 CGF.EmitVarDecl(*VD);
5290             }
5291           }
5292         }
5293       }
5294       LoopGlobals.Privatize();
5295       CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
5296     }
5297   };
5298   OMPSimdLexicalScope Scope(*this, D);
5299   CGM.getOpenMPRuntime().emitInlinedDirective(
5300       *this,
5301       isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5302                                                   : D.getDirectiveKind(),
5303       CodeGen);
5304 }
5305