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