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