xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp (revision 3a9a9c0ca44ec535dcf73fe8462bee458e54814b)
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/AST/StmtVisitor.h"
25 #include "clang/Basic/OpenMPKinds.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "llvm/BinaryFormat/Dwarf.h"
28 #include "llvm/Frontend/OpenMP/OMPConstants.h"
29 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DebugInfoMetadata.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/Support/AtomicOrdering.h"
36 using namespace clang;
37 using namespace CodeGen;
38 using namespace llvm::omp;
39 
40 static const VarDecl *getBaseDecl(const Expr *Ref);
41 
42 namespace {
43 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
44 /// for captured expressions.
45 class OMPLexicalScope : public CodeGenFunction::LexicalScope {
46   void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
47     for (const auto *C : S.clauses()) {
48       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
49         if (const auto *PreInit =
50                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
51           for (const auto *I : PreInit->decls()) {
52             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
53               CGF.EmitVarDecl(cast<VarDecl>(*I));
54             } else {
55               CodeGenFunction::AutoVarEmission Emission =
56                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
57               CGF.EmitAutoVarCleanups(Emission);
58             }
59           }
60         }
61       }
62     }
63   }
64   CodeGenFunction::OMPPrivateScope InlinedShareds;
65 
66   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
67     return CGF.LambdaCaptureFields.lookup(VD) ||
68            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
69            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
70             cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
71   }
72 
73 public:
74   OMPLexicalScope(
75       CodeGenFunction &CGF, const OMPExecutableDirective &S,
76       const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
77       const bool EmitPreInitStmt = true)
78       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
79         InlinedShareds(CGF) {
80     if (EmitPreInitStmt)
81       emitPreInitStmt(CGF, S);
82     if (!CapturedRegion.hasValue())
83       return;
84     assert(S.hasAssociatedStmt() &&
85            "Expected associated statement for inlined directive.");
86     const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
87     for (const auto &C : CS->captures()) {
88       if (C.capturesVariable() || C.capturesVariableByCopy()) {
89         auto *VD = C.getCapturedVar();
90         assert(VD == VD->getCanonicalDecl() &&
91                "Canonical decl must be captured.");
92         DeclRefExpr DRE(
93             CGF.getContext(), const_cast<VarDecl *>(VD),
94             isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
95                                        InlinedShareds.isGlobalVarCaptured(VD)),
96             VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
97         InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
98           return CGF.EmitLValue(&DRE).getAddress(CGF);
99         });
100       }
101     }
102     (void)InlinedShareds.Privatize();
103   }
104 };
105 
106 /// Lexical scope for OpenMP parallel construct, that handles correct codegen
107 /// for captured expressions.
108 class OMPParallelScope final : public OMPLexicalScope {
109   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
110     OpenMPDirectiveKind Kind = S.getDirectiveKind();
111     return !(isOpenMPTargetExecutionDirective(Kind) ||
112              isOpenMPLoopBoundSharingDirective(Kind)) &&
113            isOpenMPParallelDirective(Kind);
114   }
115 
116 public:
117   OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
118       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
119                         EmitPreInitStmt(S)) {}
120 };
121 
122 /// Lexical scope for OpenMP teams construct, that handles correct codegen
123 /// for captured expressions.
124 class OMPTeamsScope final : public OMPLexicalScope {
125   bool EmitPreInitStmt(const OMPExecutableDirective &S) {
126     OpenMPDirectiveKind Kind = S.getDirectiveKind();
127     return !isOpenMPTargetExecutionDirective(Kind) &&
128            isOpenMPTeamsDirective(Kind);
129   }
130 
131 public:
132   OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
133       : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
134                         EmitPreInitStmt(S)) {}
135 };
136 
137 /// Private scope for OpenMP loop-based directives, that supports capturing
138 /// of used expression from loop statement.
139 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
140   void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) {
141     const DeclStmt *PreInits;
142     CodeGenFunction::OMPMapVars PreCondVars;
143     if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
144       llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
145       for (const auto *E : LD->counters()) {
146         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
147         EmittedAsPrivate.insert(VD->getCanonicalDecl());
148         (void)PreCondVars.setVarAddr(
149             CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
150       }
151       // Mark private vars as undefs.
152       for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) {
153         for (const Expr *IRef : C->varlists()) {
154           const auto *OrigVD =
155               cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
156           if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
157             (void)PreCondVars.setVarAddr(
158                 CGF, OrigVD,
159                 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem(
160                             CGF.getContext().getPointerType(
161                                 OrigVD->getType().getNonReferenceType()))),
162                         CGF.getContext().getDeclAlign(OrigVD)));
163           }
164         }
165       }
166       (void)PreCondVars.apply(CGF);
167       // Emit init, __range and __end variables for C++ range loops.
168       (void)OMPLoopBasedDirective::doForAllLoops(
169           LD->getInnermostCapturedStmt()->getCapturedStmt(),
170           /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(),
171           [&CGF](unsigned Cnt, const Stmt *CurStmt) {
172             if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) {
173               if (const Stmt *Init = CXXFor->getInit())
174                 CGF.EmitStmt(Init);
175               CGF.EmitStmt(CXXFor->getRangeStmt());
176               CGF.EmitStmt(CXXFor->getEndStmt());
177             }
178             return false;
179           });
180       PreInits = cast_or_null<DeclStmt>(LD->getPreInits());
181     } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) {
182       PreInits = cast_or_null<DeclStmt>(Tile->getPreInits());
183     } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) {
184       PreInits = cast_or_null<DeclStmt>(Unroll->getPreInits());
185     } else {
186       llvm_unreachable("Unknown loop-based directive kind.");
187     }
188     if (PreInits) {
189       for (const auto *I : PreInits->decls())
190         CGF.EmitVarDecl(cast<VarDecl>(*I));
191     }
192     PreCondVars.restore(CGF);
193   }
194 
195 public:
196   OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S)
197       : CodeGenFunction::RunCleanupsScope(CGF) {
198     emitPreInitStmt(CGF, S);
199   }
200 };
201 
202 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
203   CodeGenFunction::OMPPrivateScope InlinedShareds;
204 
205   static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
206     return CGF.LambdaCaptureFields.lookup(VD) ||
207            (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
208            (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
209             cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
210   }
211 
212 public:
213   OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
214       : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
215         InlinedShareds(CGF) {
216     for (const auto *C : S.clauses()) {
217       if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
218         if (const auto *PreInit =
219                 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
220           for (const auto *I : PreInit->decls()) {
221             if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
222               CGF.EmitVarDecl(cast<VarDecl>(*I));
223             } else {
224               CodeGenFunction::AutoVarEmission Emission =
225                   CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
226               CGF.EmitAutoVarCleanups(Emission);
227             }
228           }
229         }
230       } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
231         for (const Expr *E : UDP->varlists()) {
232           const Decl *D = cast<DeclRefExpr>(E)->getDecl();
233           if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
234             CGF.EmitVarDecl(*OED);
235         }
236       } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) {
237         for (const Expr *E : UDP->varlists()) {
238           const Decl *D = getBaseDecl(E);
239           if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
240             CGF.EmitVarDecl(*OED);
241         }
242       }
243     }
244     if (!isOpenMPSimdDirective(S.getDirectiveKind()))
245       CGF.EmitOMPPrivateClause(S, InlinedShareds);
246     if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
247       if (const Expr *E = TG->getReductionRef())
248         CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
249     }
250     // Temp copy arrays for inscan reductions should not be emitted as they are
251     // not used in simd only mode.
252     llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps;
253     for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
254       if (C->getModifier() != OMPC_REDUCTION_inscan)
255         continue;
256       for (const Expr *E : C->copy_array_temps())
257         CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl());
258     }
259     const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
260     while (CS) {
261       for (auto &C : CS->captures()) {
262         if (C.capturesVariable() || C.capturesVariableByCopy()) {
263           auto *VD = C.getCapturedVar();
264           if (CopyArrayTemps.contains(VD))
265             continue;
266           assert(VD == VD->getCanonicalDecl() &&
267                  "Canonical decl must be captured.");
268           DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
269                           isCapturedVar(CGF, VD) ||
270                               (CGF.CapturedStmtInfo &&
271                                InlinedShareds.isGlobalVarCaptured(VD)),
272                           VD->getType().getNonReferenceType(), VK_LValue,
273                           C.getLocation());
274           InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
275             return CGF.EmitLValue(&DRE).getAddress(CGF);
276           });
277         }
278       }
279       CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
280     }
281     (void)InlinedShareds.Privatize();
282   }
283 };
284 
285 } // namespace
286 
287 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
288                                          const OMPExecutableDirective &S,
289                                          const RegionCodeGenTy &CodeGen);
290 
291 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
292   if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
293     if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
294       OrigVD = OrigVD->getCanonicalDecl();
295       bool IsCaptured =
296           LambdaCaptureFields.lookup(OrigVD) ||
297           (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
298           (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
299       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured,
300                       OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
301       return EmitLValue(&DRE);
302     }
303   }
304   return EmitLValue(E);
305 }
306 
307 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
308   ASTContext &C = getContext();
309   llvm::Value *Size = nullptr;
310   auto SizeInChars = C.getTypeSizeInChars(Ty);
311   if (SizeInChars.isZero()) {
312     // getTypeSizeInChars() returns 0 for a VLA.
313     while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
314       VlaSizePair VlaSize = getVLASize(VAT);
315       Ty = VlaSize.Type;
316       Size =
317           Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) : VlaSize.NumElts;
318     }
319     SizeInChars = C.getTypeSizeInChars(Ty);
320     if (SizeInChars.isZero())
321       return llvm::ConstantInt::get(SizeTy, /*V=*/0);
322     return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
323   }
324   return CGM.getSize(SizeInChars);
325 }
326 
327 void CodeGenFunction::GenerateOpenMPCapturedVars(
328     const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
329   const RecordDecl *RD = S.getCapturedRecordDecl();
330   auto CurField = RD->field_begin();
331   auto CurCap = S.captures().begin();
332   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
333                                                  E = S.capture_init_end();
334        I != E; ++I, ++CurField, ++CurCap) {
335     if (CurField->hasCapturedVLAType()) {
336       const VariableArrayType *VAT = CurField->getCapturedVLAType();
337       llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
338       CapturedVars.push_back(Val);
339     } else if (CurCap->capturesThis()) {
340       CapturedVars.push_back(CXXThisValue);
341     } else if (CurCap->capturesVariableByCopy()) {
342       llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
343 
344       // If the field is not a pointer, we need to save the actual value
345       // and load it as a void pointer.
346       if (!CurField->getType()->isAnyPointerType()) {
347         ASTContext &Ctx = getContext();
348         Address DstAddr = CreateMemTemp(
349             Ctx.getUIntPtrType(),
350             Twine(CurCap->getCapturedVar()->getName(), ".casted"));
351         LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
352 
353         llvm::Value *SrcAddrVal = EmitScalarConversion(
354             DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
355             Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
356         LValue SrcLV =
357             MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
358 
359         // Store the value using the source type pointer.
360         EmitStoreThroughLValue(RValue::get(CV), SrcLV);
361 
362         // Load the value using the destination type pointer.
363         CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
364       }
365       CapturedVars.push_back(CV);
366     } else {
367       assert(CurCap->capturesVariable() && "Expected capture by reference.");
368       CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer());
369     }
370   }
371 }
372 
373 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
374                                     QualType DstType, StringRef Name,
375                                     LValue AddrLV) {
376   ASTContext &Ctx = CGF.getContext();
377 
378   llvm::Value *CastedPtr = CGF.EmitScalarConversion(
379       AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(),
380       Ctx.getPointerType(DstType), Loc);
381   Address TmpAddr =
382       CGF.MakeNaturalAlignAddrLValue(CastedPtr, DstType).getAddress(CGF);
383   return TmpAddr;
384 }
385 
386 static QualType getCanonicalParamType(ASTContext &C, QualType T) {
387   if (T->isLValueReferenceType())
388     return C.getLValueReferenceType(
389         getCanonicalParamType(C, T.getNonReferenceType()),
390         /*SpelledAsLValue=*/false);
391   if (T->isPointerType())
392     return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
393   if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
394     if (const auto *VLA = dyn_cast<VariableArrayType>(A))
395       return getCanonicalParamType(C, VLA->getElementType());
396     if (!A->isVariablyModifiedType())
397       return C.getCanonicalType(T);
398   }
399   return C.getCanonicalParamType(T);
400 }
401 
402 namespace {
403 /// Contains required data for proper outlined function codegen.
404 struct FunctionOptions {
405   /// Captured statement for which the function is generated.
406   const CapturedStmt *S = nullptr;
407   /// true if cast to/from  UIntPtr is required for variables captured by
408   /// value.
409   const bool UIntPtrCastRequired = true;
410   /// true if only casted arguments must be registered as local args or VLA
411   /// sizes.
412   const bool RegisterCastedArgsOnly = false;
413   /// Name of the generated function.
414   const StringRef FunctionName;
415   /// Location of the non-debug version of the outlined function.
416   SourceLocation Loc;
417   explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
418                            bool RegisterCastedArgsOnly, StringRef FunctionName,
419                            SourceLocation Loc)
420       : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
421         RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
422         FunctionName(FunctionName), Loc(Loc) {}
423 };
424 } // namespace
425 
426 static llvm::Function *emitOutlinedFunctionPrologue(
427     CodeGenFunction &CGF, FunctionArgList &Args,
428     llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
429         &LocalAddrs,
430     llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
431         &VLASizes,
432     llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
433   const CapturedDecl *CD = FO.S->getCapturedDecl();
434   const RecordDecl *RD = FO.S->getCapturedRecordDecl();
435   assert(CD->hasBody() && "missing CapturedDecl body");
436 
437   CXXThisValue = nullptr;
438   // Build the argument list.
439   CodeGenModule &CGM = CGF.CGM;
440   ASTContext &Ctx = CGM.getContext();
441   FunctionArgList TargetArgs;
442   Args.append(CD->param_begin(),
443               std::next(CD->param_begin(), CD->getContextParamPosition()));
444   TargetArgs.append(
445       CD->param_begin(),
446       std::next(CD->param_begin(), CD->getContextParamPosition()));
447   auto I = FO.S->captures().begin();
448   FunctionDecl *DebugFunctionDecl = nullptr;
449   if (!FO.UIntPtrCastRequired) {
450     FunctionProtoType::ExtProtoInfo EPI;
451     QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI);
452     DebugFunctionDecl = FunctionDecl::Create(
453         Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
454         SourceLocation(), DeclarationName(), FunctionTy,
455         Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static,
456         /*UsesFPIntrin=*/false, /*isInlineSpecified=*/false,
457         /*hasWrittenPrototype=*/false);
458   }
459   for (const FieldDecl *FD : RD->fields()) {
460     QualType ArgType = FD->getType();
461     IdentifierInfo *II = nullptr;
462     VarDecl *CapVar = nullptr;
463 
464     // If this is a capture by copy and the type is not a pointer, the outlined
465     // function argument type should be uintptr and the value properly casted to
466     // uintptr. This is necessary given that the runtime library is only able to
467     // deal with pointers. We can pass in the same way the VLA type sizes to the
468     // outlined function.
469     if (FO.UIntPtrCastRequired &&
470         ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
471          I->capturesVariableArrayType()))
472       ArgType = Ctx.getUIntPtrType();
473 
474     if (I->capturesVariable() || I->capturesVariableByCopy()) {
475       CapVar = I->getCapturedVar();
476       II = CapVar->getIdentifier();
477     } else if (I->capturesThis()) {
478       II = &Ctx.Idents.get("this");
479     } else {
480       assert(I->capturesVariableArrayType());
481       II = &Ctx.Idents.get("vla");
482     }
483     if (ArgType->isVariablyModifiedType())
484       ArgType = getCanonicalParamType(Ctx, ArgType);
485     VarDecl *Arg;
486     if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
487       Arg = ParmVarDecl::Create(
488           Ctx, DebugFunctionDecl,
489           CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
490           CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
491           /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
492     } else {
493       Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
494                                       II, ArgType, ImplicitParamDecl::Other);
495     }
496     Args.emplace_back(Arg);
497     // Do not cast arguments if we emit function with non-original types.
498     TargetArgs.emplace_back(
499         FO.UIntPtrCastRequired
500             ? Arg
501             : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
502     ++I;
503   }
504   Args.append(std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
505               CD->param_end());
506   TargetArgs.append(
507       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
508       CD->param_end());
509 
510   // Create the function declaration.
511   const CGFunctionInfo &FuncInfo =
512       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
513   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
514 
515   auto *F =
516       llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
517                              FO.FunctionName, &CGM.getModule());
518   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
519   if (CD->isNothrow())
520     F->setDoesNotThrow();
521   F->setDoesNotRecurse();
522 
523   // Always inline the outlined function if optimizations are enabled.
524   if (CGM.getCodeGenOpts().OptimizationLevel != 0) {
525     F->removeFnAttr(llvm::Attribute::NoInline);
526     F->addFnAttr(llvm::Attribute::AlwaysInline);
527   }
528 
529   // Generate the function.
530   CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
531                     FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(),
532                     FO.UIntPtrCastRequired ? FO.Loc
533                                            : CD->getBody()->getBeginLoc());
534   unsigned Cnt = CD->getContextParamPosition();
535   I = FO.S->captures().begin();
536   for (const FieldDecl *FD : RD->fields()) {
537     // Do not map arguments if we emit function with non-original types.
538     Address LocalAddr(Address::invalid());
539     if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
540       LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
541                                                              TargetArgs[Cnt]);
542     } else {
543       LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
544     }
545     // If we are capturing a pointer by copy we don't need to do anything, just
546     // use the value that we get from the arguments.
547     if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
548       const VarDecl *CurVD = I->getCapturedVar();
549       if (!FO.RegisterCastedArgsOnly)
550         LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
551       ++Cnt;
552       ++I;
553       continue;
554     }
555 
556     LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
557                                         AlignmentSource::Decl);
558     if (FD->hasCapturedVLAType()) {
559       if (FO.UIntPtrCastRequired) {
560         ArgLVal = CGF.MakeAddrLValue(
561             castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
562                                  Args[Cnt]->getName(), ArgLVal),
563             FD->getType(), AlignmentSource::Decl);
564       }
565       llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
566       const VariableArrayType *VAT = FD->getCapturedVLAType();
567       VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
568     } else if (I->capturesVariable()) {
569       const VarDecl *Var = I->getCapturedVar();
570       QualType VarTy = Var->getType();
571       Address ArgAddr = ArgLVal.getAddress(CGF);
572       if (ArgLVal.getType()->isLValueReferenceType()) {
573         ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
574       } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
575         assert(ArgLVal.getType()->isPointerType());
576         ArgAddr = CGF.EmitLoadOfPointer(
577             ArgAddr, ArgLVal.getType()->castAs<PointerType>());
578       }
579       if (!FO.RegisterCastedArgsOnly) {
580         LocalAddrs.insert(
581             {Args[Cnt],
582              {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
583       }
584     } else if (I->capturesVariableByCopy()) {
585       assert(!FD->getType()->isAnyPointerType() &&
586              "Not expecting a captured pointer.");
587       const VarDecl *Var = I->getCapturedVar();
588       LocalAddrs.insert({Args[Cnt],
589                          {Var, FO.UIntPtrCastRequired
590                                    ? castValueFromUintptr(
591                                          CGF, I->getLocation(), FD->getType(),
592                                          Args[Cnt]->getName(), ArgLVal)
593                                    : ArgLVal.getAddress(CGF)}});
594     } else {
595       // If 'this' is captured, load it into CXXThisValue.
596       assert(I->capturesThis());
597       CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
598       LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}});
599     }
600     ++Cnt;
601     ++I;
602   }
603 
604   return F;
605 }
606 
607 llvm::Function *
608 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S,
609                                                     SourceLocation Loc) {
610   assert(
611       CapturedStmtInfo &&
612       "CapturedStmtInfo should be set when generating the captured function");
613   const CapturedDecl *CD = S.getCapturedDecl();
614   // Build the argument list.
615   bool NeedWrapperFunction =
616       getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo();
617   FunctionArgList Args;
618   llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
619   llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
620   SmallString<256> Buffer;
621   llvm::raw_svector_ostream Out(Buffer);
622   Out << CapturedStmtInfo->getHelperName();
623   if (NeedWrapperFunction)
624     Out << "_debug__";
625   FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
626                      Out.str(), Loc);
627   llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
628                                                    VLASizes, CXXThisValue, FO);
629   CodeGenFunction::OMPPrivateScope LocalScope(*this);
630   for (const auto &LocalAddrPair : LocalAddrs) {
631     if (LocalAddrPair.second.first) {
632       LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() {
633         return LocalAddrPair.second.second;
634       });
635     }
636   }
637   (void)LocalScope.Privatize();
638   for (const auto &VLASizePair : VLASizes)
639     VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
640   PGO.assignRegionCounters(GlobalDecl(CD), F);
641   CapturedStmtInfo->EmitBody(*this, CD->getBody());
642   (void)LocalScope.ForceCleanup();
643   FinishFunction(CD->getBodyRBrace());
644   if (!NeedWrapperFunction)
645     return F;
646 
647   FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
648                             /*RegisterCastedArgsOnly=*/true,
649                             CapturedStmtInfo->getHelperName(), Loc);
650   CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
651   WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
652   Args.clear();
653   LocalAddrs.clear();
654   VLASizes.clear();
655   llvm::Function *WrapperF =
656       emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
657                                    WrapperCGF.CXXThisValue, WrapperFO);
658   llvm::SmallVector<llvm::Value *, 4> CallArgs;
659   auto *PI = F->arg_begin();
660   for (const auto *Arg : Args) {
661     llvm::Value *CallArg;
662     auto I = LocalAddrs.find(Arg);
663     if (I != LocalAddrs.end()) {
664       LValue LV = WrapperCGF.MakeAddrLValue(
665           I->second.second,
666           I->second.first ? I->second.first->getType() : Arg->getType(),
667           AlignmentSource::Decl);
668       if (LV.getType()->isAnyComplexType())
669         LV.setAddress(WrapperCGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
670             LV.getAddress(WrapperCGF),
671             PI->getType()->getPointerTo(
672                 LV.getAddress(WrapperCGF).getAddressSpace())));
673       CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
674     } else {
675       auto EI = VLASizes.find(Arg);
676       if (EI != VLASizes.end()) {
677         CallArg = EI->second.second;
678       } else {
679         LValue LV =
680             WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
681                                       Arg->getType(), AlignmentSource::Decl);
682         CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
683       }
684     }
685     CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
686     ++PI;
687   }
688   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs);
689   WrapperCGF.FinishFunction();
690   return WrapperF;
691 }
692 
693 //===----------------------------------------------------------------------===//
694 //                              OpenMP Directive Emission
695 //===----------------------------------------------------------------------===//
696 void CodeGenFunction::EmitOMPAggregateAssign(
697     Address DestAddr, Address SrcAddr, QualType OriginalType,
698     const llvm::function_ref<void(Address, Address)> CopyGen) {
699   // Perform element-by-element initialization.
700   QualType ElementTy;
701 
702   // Drill down to the base element type on both arrays.
703   const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
704   llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
705   SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
706 
707   llvm::Value *SrcBegin = SrcAddr.getPointer();
708   llvm::Value *DestBegin = DestAddr.getPointer();
709   // Cast from pointer to array type to pointer to single element.
710   llvm::Value *DestEnd =
711       Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements);
712   // The basic structure here is a while-do loop.
713   llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
714   llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
715   llvm::Value *IsEmpty =
716       Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
717   Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
718 
719   // Enter the loop body, making that address the current address.
720   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
721   EmitBlock(BodyBB);
722 
723   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
724 
725   llvm::PHINode *SrcElementPHI =
726       Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
727   SrcElementPHI->addIncoming(SrcBegin, EntryBB);
728   Address SrcElementCurrent =
729       Address(SrcElementPHI,
730               SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
731 
732   llvm::PHINode *DestElementPHI = Builder.CreatePHI(
733       DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
734   DestElementPHI->addIncoming(DestBegin, EntryBB);
735   Address DestElementCurrent =
736       Address(DestElementPHI,
737               DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
738 
739   // Emit copy.
740   CopyGen(DestElementCurrent, SrcElementCurrent);
741 
742   // Shift the address forward by one element.
743   llvm::Value *DestElementNext =
744       Builder.CreateConstGEP1_32(DestAddr.getElementType(), DestElementPHI,
745                                  /*Idx0=*/1, "omp.arraycpy.dest.element");
746   llvm::Value *SrcElementNext =
747       Builder.CreateConstGEP1_32(SrcAddr.getElementType(), SrcElementPHI,
748                                  /*Idx0=*/1, "omp.arraycpy.src.element");
749   // Check whether we've reached the end.
750   llvm::Value *Done =
751       Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
752   Builder.CreateCondBr(Done, DoneBB, BodyBB);
753   DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
754   SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
755 
756   // Done.
757   EmitBlock(DoneBB, /*IsFinished=*/true);
758 }
759 
760 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
761                                   Address SrcAddr, const VarDecl *DestVD,
762                                   const VarDecl *SrcVD, const Expr *Copy) {
763   if (OriginalType->isArrayType()) {
764     const auto *BO = dyn_cast<BinaryOperator>(Copy);
765     if (BO && BO->getOpcode() == BO_Assign) {
766       // Perform simple memcpy for simple copying.
767       LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
768       LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
769       EmitAggregateAssign(Dest, Src, OriginalType);
770     } else {
771       // For arrays with complex element types perform element by element
772       // copying.
773       EmitOMPAggregateAssign(
774           DestAddr, SrcAddr, OriginalType,
775           [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
776             // Working with the single array element, so have to remap
777             // destination and source variables to corresponding array
778             // elements.
779             CodeGenFunction::OMPPrivateScope Remap(*this);
780             Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
781             Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
782             (void)Remap.Privatize();
783             EmitIgnoredExpr(Copy);
784           });
785     }
786   } else {
787     // Remap pseudo source variable to private copy.
788     CodeGenFunction::OMPPrivateScope Remap(*this);
789     Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
790     Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
791     (void)Remap.Privatize();
792     // Emit copying of the whole variable.
793     EmitIgnoredExpr(Copy);
794   }
795 }
796 
797 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
798                                                 OMPPrivateScope &PrivateScope) {
799   if (!HaveInsertPoint())
800     return false;
801   bool DeviceConstTarget =
802       getLangOpts().OpenMPIsDevice &&
803       isOpenMPTargetExecutionDirective(D.getDirectiveKind());
804   bool FirstprivateIsLastprivate = false;
805   llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
806   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
807     for (const auto *D : C->varlists())
808       Lastprivates.try_emplace(
809           cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(),
810           C->getKind());
811   }
812   llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
813   llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
814   getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
815   // Force emission of the firstprivate copy if the directive does not emit
816   // outlined function, like omp for, omp simd, omp distribute etc.
817   bool MustEmitFirstprivateCopy =
818       CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
819   for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
820     const auto *IRef = C->varlist_begin();
821     const auto *InitsRef = C->inits().begin();
822     for (const Expr *IInit : C->private_copies()) {
823       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
824       bool ThisFirstprivateIsLastprivate =
825           Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
826       const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
827       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
828       if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
829           !FD->getType()->isReferenceType() &&
830           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
831         EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
832         ++IRef;
833         ++InitsRef;
834         continue;
835       }
836       // Do not emit copy for firstprivate constant variables in target regions,
837       // captured by reference.
838       if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
839           FD && FD->getType()->isReferenceType() &&
840           (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
841         EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
842         ++IRef;
843         ++InitsRef;
844         continue;
845       }
846       FirstprivateIsLastprivate =
847           FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
848       if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
849         const auto *VDInit =
850             cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
851         bool IsRegistered;
852         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
853                         /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
854                         (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
855         LValue OriginalLVal;
856         if (!FD) {
857           // Check if the firstprivate variable is just a constant value.
858           ConstantEmission CE = tryEmitAsConstant(&DRE);
859           if (CE && !CE.isReference()) {
860             // Constant value, no need to create a copy.
861             ++IRef;
862             ++InitsRef;
863             continue;
864           }
865           if (CE && CE.isReference()) {
866             OriginalLVal = CE.getReferenceLValue(*this, &DRE);
867           } else {
868             assert(!CE && "Expected non-constant firstprivate.");
869             OriginalLVal = EmitLValue(&DRE);
870           }
871         } else {
872           OriginalLVal = EmitLValue(&DRE);
873         }
874         QualType Type = VD->getType();
875         if (Type->isArrayType()) {
876           // Emit VarDecl with copy init for arrays.
877           // Get the address of the original variable captured in current
878           // captured region.
879           IsRegistered = PrivateScope.addPrivate(
880               OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
881                 AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
882                 const Expr *Init = VD->getInit();
883                 if (!isa<CXXConstructExpr>(Init) ||
884                     isTrivialInitializer(Init)) {
885                   // Perform simple memcpy.
886                   LValue Dest =
887                       MakeAddrLValue(Emission.getAllocatedAddress(), Type);
888                   EmitAggregateAssign(Dest, OriginalLVal, Type);
889                 } else {
890                   EmitOMPAggregateAssign(
891                       Emission.getAllocatedAddress(),
892                       OriginalLVal.getAddress(*this), Type,
893                       [this, VDInit, Init](Address DestElement,
894                                            Address SrcElement) {
895                         // Clean up any temporaries needed by the
896                         // initialization.
897                         RunCleanupsScope InitScope(*this);
898                         // Emit initialization for single element.
899                         setAddrOfLocalVar(VDInit, SrcElement);
900                         EmitAnyExprToMem(Init, DestElement,
901                                          Init->getType().getQualifiers(),
902                                          /*IsInitializer*/ false);
903                         LocalDeclMap.erase(VDInit);
904                       });
905                 }
906                 EmitAutoVarCleanups(Emission);
907                 return Emission.getAllocatedAddress();
908               });
909         } else {
910           Address OriginalAddr = OriginalLVal.getAddress(*this);
911           IsRegistered =
912               PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD,
913                                                ThisFirstprivateIsLastprivate,
914                                                OrigVD, &Lastprivates, IRef]() {
915                 // Emit private VarDecl with copy init.
916                 // Remap temp VDInit variable to the address of the original
917                 // variable (for proper handling of captured global variables).
918                 setAddrOfLocalVar(VDInit, OriginalAddr);
919                 EmitDecl(*VD);
920                 LocalDeclMap.erase(VDInit);
921                 if (ThisFirstprivateIsLastprivate &&
922                     Lastprivates[OrigVD->getCanonicalDecl()] ==
923                         OMPC_LASTPRIVATE_conditional) {
924                   // Create/init special variable for lastprivate conditionals.
925                   Address VDAddr =
926                       CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
927                           *this, OrigVD);
928                   llvm::Value *V = EmitLoadOfScalar(
929                       MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(),
930                                      AlignmentSource::Decl),
931                       (*IRef)->getExprLoc());
932                   EmitStoreOfScalar(V,
933                                     MakeAddrLValue(VDAddr, (*IRef)->getType(),
934                                                    AlignmentSource::Decl));
935                   LocalDeclMap.erase(VD);
936                   setAddrOfLocalVar(VD, VDAddr);
937                   return VDAddr;
938                 }
939                 return GetAddrOfLocalVar(VD);
940               });
941         }
942         assert(IsRegistered &&
943                "firstprivate var already registered as private");
944         // Silence the warning about unused variable.
945         (void)IsRegistered;
946       }
947       ++IRef;
948       ++InitsRef;
949     }
950   }
951   return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
952 }
953 
954 void CodeGenFunction::EmitOMPPrivateClause(
955     const OMPExecutableDirective &D,
956     CodeGenFunction::OMPPrivateScope &PrivateScope) {
957   if (!HaveInsertPoint())
958     return;
959   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
960   for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
961     auto IRef = C->varlist_begin();
962     for (const Expr *IInit : C->private_copies()) {
963       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
964       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
965         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
966         bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
967           // Emit private VarDecl with copy init.
968           EmitDecl(*VD);
969           return GetAddrOfLocalVar(VD);
970         });
971         assert(IsRegistered && "private var already registered as private");
972         // Silence the warning about unused variable.
973         (void)IsRegistered;
974       }
975       ++IRef;
976     }
977   }
978 }
979 
980 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
981   if (!HaveInsertPoint())
982     return false;
983   // threadprivate_var1 = master_threadprivate_var1;
984   // operator=(threadprivate_var2, master_threadprivate_var2);
985   // ...
986   // __kmpc_barrier(&loc, global_tid);
987   llvm::DenseSet<const VarDecl *> CopiedVars;
988   llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
989   for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
990     auto IRef = C->varlist_begin();
991     auto ISrcRef = C->source_exprs().begin();
992     auto IDestRef = C->destination_exprs().begin();
993     for (const Expr *AssignOp : C->assignment_ops()) {
994       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
995       QualType Type = VD->getType();
996       if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
997         // Get the address of the master variable. If we are emitting code with
998         // TLS support, the address is passed from the master as field in the
999         // captured declaration.
1000         Address MasterAddr = Address::invalid();
1001         if (getLangOpts().OpenMPUseTLS &&
1002             getContext().getTargetInfo().isTLSSupported()) {
1003           assert(CapturedStmtInfo->lookup(VD) &&
1004                  "Copyin threadprivates should have been captured!");
1005           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true,
1006                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1007           MasterAddr = EmitLValue(&DRE).getAddress(*this);
1008           LocalDeclMap.erase(VD);
1009         } else {
1010           MasterAddr =
1011               Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
1012                                           : CGM.GetAddrOfGlobal(VD),
1013                       getContext().getDeclAlign(VD));
1014         }
1015         // Get the address of the threadprivate variable.
1016         Address PrivateAddr = EmitLValue(*IRef).getAddress(*this);
1017         if (CopiedVars.size() == 1) {
1018           // At first check if current thread is a master thread. If it is, no
1019           // need to copy data.
1020           CopyBegin = createBasicBlock("copyin.not.master");
1021           CopyEnd = createBasicBlock("copyin.not.master.end");
1022           // TODO: Avoid ptrtoint conversion.
1023           auto *MasterAddrInt =
1024               Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy);
1025           auto *PrivateAddrInt =
1026               Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy);
1027           Builder.CreateCondBr(
1028               Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin,
1029               CopyEnd);
1030           EmitBlock(CopyBegin);
1031         }
1032         const auto *SrcVD =
1033             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1034         const auto *DestVD =
1035             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1036         EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
1037       }
1038       ++IRef;
1039       ++ISrcRef;
1040       ++IDestRef;
1041     }
1042   }
1043   if (CopyEnd) {
1044     // Exit out of copying procedure for non-master thread.
1045     EmitBlock(CopyEnd, /*IsFinished=*/true);
1046     return true;
1047   }
1048   return false;
1049 }
1050 
1051 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
1052     const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
1053   if (!HaveInsertPoint())
1054     return false;
1055   bool HasAtLeastOneLastprivate = false;
1056   llvm::DenseSet<const VarDecl *> SIMDLCVs;
1057   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
1058     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
1059     for (const Expr *C : LoopDirective->counters()) {
1060       SIMDLCVs.insert(
1061           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
1062     }
1063   }
1064   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1065   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1066     HasAtLeastOneLastprivate = true;
1067     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
1068         !getLangOpts().OpenMPSimd)
1069       break;
1070     const auto *IRef = C->varlist_begin();
1071     const auto *IDestRef = C->destination_exprs().begin();
1072     for (const Expr *IInit : C->private_copies()) {
1073       // Keep the address of the original variable for future update at the end
1074       // of the loop.
1075       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1076       // Taskloops do not require additional initialization, it is done in
1077       // runtime support library.
1078       if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
1079         const auto *DestVD =
1080             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1081         PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
1082           DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
1083                           /*RefersToEnclosingVariableOrCapture=*/
1084                           CapturedStmtInfo->lookup(OrigVD) != nullptr,
1085                           (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
1086           return EmitLValue(&DRE).getAddress(*this);
1087         });
1088         // Check if the variable is also a firstprivate: in this case IInit is
1089         // not generated. Initialization of this variable will happen in codegen
1090         // for 'firstprivate' clause.
1091         if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
1092           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
1093           bool IsRegistered =
1094               PrivateScope.addPrivate(OrigVD, [this, VD, C, OrigVD]() {
1095                 if (C->getKind() == OMPC_LASTPRIVATE_conditional) {
1096                   Address VDAddr =
1097                       CGM.getOpenMPRuntime().emitLastprivateConditionalInit(
1098                           *this, OrigVD);
1099                   setAddrOfLocalVar(VD, VDAddr);
1100                   return VDAddr;
1101                 }
1102                 // Emit private VarDecl with copy init.
1103                 EmitDecl(*VD);
1104                 return GetAddrOfLocalVar(VD);
1105               });
1106           assert(IsRegistered &&
1107                  "lastprivate var already registered as private");
1108           (void)IsRegistered;
1109         }
1110       }
1111       ++IRef;
1112       ++IDestRef;
1113     }
1114   }
1115   return HasAtLeastOneLastprivate;
1116 }
1117 
1118 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
1119     const OMPExecutableDirective &D, bool NoFinals,
1120     llvm::Value *IsLastIterCond) {
1121   if (!HaveInsertPoint())
1122     return;
1123   // Emit following code:
1124   // if (<IsLastIterCond>) {
1125   //   orig_var1 = private_orig_var1;
1126   //   ...
1127   //   orig_varn = private_orig_varn;
1128   // }
1129   llvm::BasicBlock *ThenBB = nullptr;
1130   llvm::BasicBlock *DoneBB = nullptr;
1131   if (IsLastIterCond) {
1132     // Emit implicit barrier if at least one lastprivate conditional is found
1133     // and this is not a simd mode.
1134     if (!getLangOpts().OpenMPSimd &&
1135         llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(),
1136                      [](const OMPLastprivateClause *C) {
1137                        return C->getKind() == OMPC_LASTPRIVATE_conditional;
1138                      })) {
1139       CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(),
1140                                              OMPD_unknown,
1141                                              /*EmitChecks=*/false,
1142                                              /*ForceSimpleCall=*/true);
1143     }
1144     ThenBB = createBasicBlock(".omp.lastprivate.then");
1145     DoneBB = createBasicBlock(".omp.lastprivate.done");
1146     Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
1147     EmitBlock(ThenBB);
1148   }
1149   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
1150   llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
1151   if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
1152     auto IC = LoopDirective->counters().begin();
1153     for (const Expr *F : LoopDirective->finals()) {
1154       const auto *D =
1155           cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
1156       if (NoFinals)
1157         AlreadyEmittedVars.insert(D);
1158       else
1159         LoopCountersAndUpdates[D] = F;
1160       ++IC;
1161     }
1162   }
1163   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
1164     auto IRef = C->varlist_begin();
1165     auto ISrcRef = C->source_exprs().begin();
1166     auto IDestRef = C->destination_exprs().begin();
1167     for (const Expr *AssignOp : C->assignment_ops()) {
1168       const auto *PrivateVD =
1169           cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1170       QualType Type = PrivateVD->getType();
1171       const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
1172       if (AlreadyEmittedVars.insert(CanonicalVD).second) {
1173         // If lastprivate variable is a loop control variable for loop-based
1174         // directive, update its value before copyin back to original
1175         // variable.
1176         if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
1177           EmitIgnoredExpr(FinalExpr);
1178         const auto *SrcVD =
1179             cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
1180         const auto *DestVD =
1181             cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
1182         // Get the address of the private variable.
1183         Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
1184         if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
1185           PrivateAddr =
1186               Address(Builder.CreateLoad(PrivateAddr),
1187                       CGM.getNaturalTypeAlignment(RefTy->getPointeeType()));
1188         // Store the last value to the private copy in the last iteration.
1189         if (C->getKind() == OMPC_LASTPRIVATE_conditional)
1190           CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate(
1191               *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD,
1192               (*IRef)->getExprLoc());
1193         // Get the address of the original variable.
1194         Address OriginalAddr = GetAddrOfLocalVar(DestVD);
1195         EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
1196       }
1197       ++IRef;
1198       ++ISrcRef;
1199       ++IDestRef;
1200     }
1201     if (const Expr *PostUpdate = C->getPostUpdateExpr())
1202       EmitIgnoredExpr(PostUpdate);
1203   }
1204   if (IsLastIterCond)
1205     EmitBlock(DoneBB, /*IsFinished=*/true);
1206 }
1207 
1208 void CodeGenFunction::EmitOMPReductionClauseInit(
1209     const OMPExecutableDirective &D,
1210     CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) {
1211   if (!HaveInsertPoint())
1212     return;
1213   SmallVector<const Expr *, 4> Shareds;
1214   SmallVector<const Expr *, 4> Privates;
1215   SmallVector<const Expr *, 4> ReductionOps;
1216   SmallVector<const Expr *, 4> LHSs;
1217   SmallVector<const Expr *, 4> RHSs;
1218   OMPTaskDataTy Data;
1219   SmallVector<const Expr *, 4> TaskLHSs;
1220   SmallVector<const Expr *, 4> TaskRHSs;
1221   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1222     if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan))
1223       continue;
1224     Shareds.append(C->varlist_begin(), C->varlist_end());
1225     Privates.append(C->privates().begin(), C->privates().end());
1226     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1227     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1228     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1229     if (C->getModifier() == OMPC_REDUCTION_task) {
1230       Data.ReductionVars.append(C->privates().begin(), C->privates().end());
1231       Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
1232       Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
1233       Data.ReductionOps.append(C->reduction_ops().begin(),
1234                                C->reduction_ops().end());
1235       TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1236       TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1237     }
1238   }
1239   ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
1240   unsigned Count = 0;
1241   auto *ILHS = LHSs.begin();
1242   auto *IRHS = RHSs.begin();
1243   auto *IPriv = Privates.begin();
1244   for (const Expr *IRef : Shareds) {
1245     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
1246     // Emit private VarDecl with reduction init.
1247     RedCG.emitSharedOrigLValue(*this, Count);
1248     RedCG.emitAggregateType(*this, Count);
1249     AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
1250     RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
1251                              RedCG.getSharedLValue(Count).getAddress(*this),
1252                              [&Emission](CodeGenFunction &CGF) {
1253                                CGF.EmitAutoVarInit(Emission);
1254                                return true;
1255                              });
1256     EmitAutoVarCleanups(Emission);
1257     Address BaseAddr = RedCG.adjustPrivateAddress(
1258         *this, Count, Emission.getAllocatedAddress());
1259     bool IsRegistered = PrivateScope.addPrivate(
1260         RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
1261     assert(IsRegistered && "private var already registered as private");
1262     // Silence the warning about unused variable.
1263     (void)IsRegistered;
1264 
1265     const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
1266     const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
1267     QualType Type = PrivateVD->getType();
1268     bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
1269     if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
1270       // Store the address of the original variable associated with the LHS
1271       // implicit variable.
1272       PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1273         return RedCG.getSharedLValue(Count).getAddress(*this);
1274       });
1275       PrivateScope.addPrivate(
1276           RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
1277     } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
1278                isa<ArraySubscriptExpr>(IRef)) {
1279       // Store the address of the original variable associated with the LHS
1280       // implicit variable.
1281       PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() {
1282         return RedCG.getSharedLValue(Count).getAddress(*this);
1283       });
1284       PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
1285         return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
1286                                             ConvertTypeForMem(RHSVD->getType()),
1287                                             "rhs.begin");
1288       });
1289     } else {
1290       QualType Type = PrivateVD->getType();
1291       bool IsArray = getContext().getAsArrayType(Type) != nullptr;
1292       Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this);
1293       // Store the address of the original variable associated with the LHS
1294       // implicit variable.
1295       if (IsArray) {
1296         OriginalAddr = Builder.CreateElementBitCast(
1297             OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
1298       }
1299       PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
1300       PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
1301         return IsArray ? Builder.CreateElementBitCast(
1302                              GetAddrOfLocalVar(PrivateVD),
1303                              ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
1304                        : GetAddrOfLocalVar(PrivateVD);
1305       });
1306     }
1307     ++ILHS;
1308     ++IRHS;
1309     ++IPriv;
1310     ++Count;
1311   }
1312   if (!Data.ReductionVars.empty()) {
1313     Data.IsReductionWithTaskMod = true;
1314     Data.IsWorksharingReduction =
1315         isOpenMPWorksharingDirective(D.getDirectiveKind());
1316     llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit(
1317         *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data);
1318     const Expr *TaskRedRef = nullptr;
1319     switch (D.getDirectiveKind()) {
1320     case OMPD_parallel:
1321       TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr();
1322       break;
1323     case OMPD_for:
1324       TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr();
1325       break;
1326     case OMPD_sections:
1327       TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr();
1328       break;
1329     case OMPD_parallel_for:
1330       TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr();
1331       break;
1332     case OMPD_parallel_master:
1333       TaskRedRef =
1334           cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr();
1335       break;
1336     case OMPD_parallel_sections:
1337       TaskRedRef =
1338           cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr();
1339       break;
1340     case OMPD_target_parallel:
1341       TaskRedRef =
1342           cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr();
1343       break;
1344     case OMPD_target_parallel_for:
1345       TaskRedRef =
1346           cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr();
1347       break;
1348     case OMPD_distribute_parallel_for:
1349       TaskRedRef =
1350           cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr();
1351       break;
1352     case OMPD_teams_distribute_parallel_for:
1353       TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D)
1354                        .getTaskReductionRefExpr();
1355       break;
1356     case OMPD_target_teams_distribute_parallel_for:
1357       TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D)
1358                        .getTaskReductionRefExpr();
1359       break;
1360     case OMPD_simd:
1361     case OMPD_for_simd:
1362     case OMPD_section:
1363     case OMPD_single:
1364     case OMPD_master:
1365     case OMPD_critical:
1366     case OMPD_parallel_for_simd:
1367     case OMPD_task:
1368     case OMPD_taskyield:
1369     case OMPD_barrier:
1370     case OMPD_taskwait:
1371     case OMPD_taskgroup:
1372     case OMPD_flush:
1373     case OMPD_depobj:
1374     case OMPD_scan:
1375     case OMPD_ordered:
1376     case OMPD_atomic:
1377     case OMPD_teams:
1378     case OMPD_target:
1379     case OMPD_cancellation_point:
1380     case OMPD_cancel:
1381     case OMPD_target_data:
1382     case OMPD_target_enter_data:
1383     case OMPD_target_exit_data:
1384     case OMPD_taskloop:
1385     case OMPD_taskloop_simd:
1386     case OMPD_master_taskloop:
1387     case OMPD_master_taskloop_simd:
1388     case OMPD_parallel_master_taskloop:
1389     case OMPD_parallel_master_taskloop_simd:
1390     case OMPD_distribute:
1391     case OMPD_target_update:
1392     case OMPD_distribute_parallel_for_simd:
1393     case OMPD_distribute_simd:
1394     case OMPD_target_parallel_for_simd:
1395     case OMPD_target_simd:
1396     case OMPD_teams_distribute:
1397     case OMPD_teams_distribute_simd:
1398     case OMPD_teams_distribute_parallel_for_simd:
1399     case OMPD_target_teams:
1400     case OMPD_target_teams_distribute:
1401     case OMPD_target_teams_distribute_parallel_for_simd:
1402     case OMPD_target_teams_distribute_simd:
1403     case OMPD_declare_target:
1404     case OMPD_end_declare_target:
1405     case OMPD_threadprivate:
1406     case OMPD_allocate:
1407     case OMPD_declare_reduction:
1408     case OMPD_declare_mapper:
1409     case OMPD_declare_simd:
1410     case OMPD_requires:
1411     case OMPD_declare_variant:
1412     case OMPD_begin_declare_variant:
1413     case OMPD_end_declare_variant:
1414     case OMPD_unknown:
1415     default:
1416       llvm_unreachable("Enexpected directive with task reductions.");
1417     }
1418 
1419     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl());
1420     EmitVarDecl(*VD);
1421     EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD),
1422                       /*Volatile=*/false, TaskRedRef->getType());
1423   }
1424 }
1425 
1426 void CodeGenFunction::EmitOMPReductionClauseFinal(
1427     const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
1428   if (!HaveInsertPoint())
1429     return;
1430   llvm::SmallVector<const Expr *, 8> Privates;
1431   llvm::SmallVector<const Expr *, 8> LHSExprs;
1432   llvm::SmallVector<const Expr *, 8> RHSExprs;
1433   llvm::SmallVector<const Expr *, 8> ReductionOps;
1434   bool HasAtLeastOneReduction = false;
1435   bool IsReductionWithTaskMod = false;
1436   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1437     // Do not emit for inscan reductions.
1438     if (C->getModifier() == OMPC_REDUCTION_inscan)
1439       continue;
1440     HasAtLeastOneReduction = true;
1441     Privates.append(C->privates().begin(), C->privates().end());
1442     LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
1443     RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
1444     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
1445     IsReductionWithTaskMod =
1446         IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task;
1447   }
1448   if (HasAtLeastOneReduction) {
1449     if (IsReductionWithTaskMod) {
1450       CGM.getOpenMPRuntime().emitTaskReductionFini(
1451           *this, D.getBeginLoc(),
1452           isOpenMPWorksharingDirective(D.getDirectiveKind()));
1453     }
1454     bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
1455                       isOpenMPParallelDirective(D.getDirectiveKind()) ||
1456                       ReductionKind == OMPD_simd;
1457     bool SimpleReduction = ReductionKind == OMPD_simd;
1458     // Emit nowait reduction if nowait clause is present or directive is a
1459     // parallel directive (it always has implicit barrier).
1460     CGM.getOpenMPRuntime().emitReduction(
1461         *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
1462         {WithNowait, SimpleReduction, ReductionKind});
1463   }
1464 }
1465 
1466 static void emitPostUpdateForReductionClause(
1467     CodeGenFunction &CGF, const OMPExecutableDirective &D,
1468     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
1469   if (!CGF.HaveInsertPoint())
1470     return;
1471   llvm::BasicBlock *DoneBB = nullptr;
1472   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1473     if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
1474       if (!DoneBB) {
1475         if (llvm::Value *Cond = CondGen(CGF)) {
1476           // If the first post-update expression is found, emit conditional
1477           // block if it was requested.
1478           llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
1479           DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
1480           CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
1481           CGF.EmitBlock(ThenBB);
1482         }
1483       }
1484       CGF.EmitIgnoredExpr(PostUpdate);
1485     }
1486   }
1487   if (DoneBB)
1488     CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
1489 }
1490 
1491 namespace {
1492 /// Codegen lambda for appending distribute lower and upper bounds to outlined
1493 /// parallel function. This is necessary for combined constructs such as
1494 /// 'distribute parallel for'
1495 typedef llvm::function_ref<void(CodeGenFunction &,
1496                                 const OMPExecutableDirective &,
1497                                 llvm::SmallVectorImpl<llvm::Value *> &)>
1498     CodeGenBoundParametersTy;
1499 } // anonymous namespace
1500 
1501 static void
1502 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF,
1503                                      const OMPExecutableDirective &S) {
1504   if (CGF.getLangOpts().OpenMP < 50)
1505     return;
1506   llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls;
1507   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
1508     for (const Expr *Ref : C->varlists()) {
1509       if (!Ref->getType()->isScalarType())
1510         continue;
1511       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1512       if (!DRE)
1513         continue;
1514       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1515       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1516     }
1517   }
1518   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
1519     for (const Expr *Ref : C->varlists()) {
1520       if (!Ref->getType()->isScalarType())
1521         continue;
1522       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1523       if (!DRE)
1524         continue;
1525       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1526       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1527     }
1528   }
1529   for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) {
1530     for (const Expr *Ref : C->varlists()) {
1531       if (!Ref->getType()->isScalarType())
1532         continue;
1533       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1534       if (!DRE)
1535         continue;
1536       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1537       CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref);
1538     }
1539   }
1540   // Privates should ne analyzed since they are not captured at all.
1541   // Task reductions may be skipped - tasks are ignored.
1542   // Firstprivates do not return value but may be passed by reference - no need
1543   // to check for updated lastprivate conditional.
1544   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
1545     for (const Expr *Ref : C->varlists()) {
1546       if (!Ref->getType()->isScalarType())
1547         continue;
1548       const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
1549       if (!DRE)
1550         continue;
1551       PrivateDecls.insert(cast<VarDecl>(DRE->getDecl()));
1552     }
1553   }
1554   CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional(
1555       CGF, S, PrivateDecls);
1556 }
1557 
1558 static void emitCommonOMPParallelDirective(
1559     CodeGenFunction &CGF, const OMPExecutableDirective &S,
1560     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1561     const CodeGenBoundParametersTy &CodeGenBoundParameters) {
1562   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1563   llvm::Value *NumThreads = nullptr;
1564   llvm::Function *OutlinedFn =
1565       CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
1566           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
1567   if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
1568     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
1569     NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
1570                                     /*IgnoreResultAssign=*/true);
1571     CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
1572         CGF, NumThreads, NumThreadsClause->getBeginLoc());
1573   }
1574   if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
1575     CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
1576     CGF.CGM.getOpenMPRuntime().emitProcBindClause(
1577         CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
1578   }
1579   const Expr *IfCond = nullptr;
1580   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
1581     if (C->getNameModifier() == OMPD_unknown ||
1582         C->getNameModifier() == OMPD_parallel) {
1583       IfCond = C->getCondition();
1584       break;
1585     }
1586   }
1587 
1588   OMPParallelScope Scope(CGF, S);
1589   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
1590   // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
1591   // lower and upper bounds with the pragma 'for' chunking mechanism.
1592   // The following lambda takes care of appending the lower and upper bound
1593   // parameters when necessary
1594   CodeGenBoundParameters(CGF, S, CapturedVars);
1595   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
1596   CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
1597                                               CapturedVars, IfCond, NumThreads);
1598 }
1599 
1600 static bool isAllocatableDecl(const VarDecl *VD) {
1601   const VarDecl *CVD = VD->getCanonicalDecl();
1602   if (!CVD->hasAttr<OMPAllocateDeclAttr>())
1603     return false;
1604   const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
1605   // Use the default allocation.
1606   return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc ||
1607             AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) &&
1608            !AA->getAllocator());
1609 }
1610 
1611 static void emitEmptyBoundParameters(CodeGenFunction &,
1612                                      const OMPExecutableDirective &,
1613                                      llvm::SmallVectorImpl<llvm::Value *> &) {}
1614 
1615 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
1616     CodeGenFunction &CGF, const VarDecl *VD) {
1617   CodeGenModule &CGM = CGF.CGM;
1618   auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1619 
1620   if (!VD)
1621     return Address::invalid();
1622   const VarDecl *CVD = VD->getCanonicalDecl();
1623   if (!isAllocatableDecl(CVD))
1624     return Address::invalid();
1625   llvm::Value *Size;
1626   CharUnits Align = CGM.getContext().getDeclAlign(CVD);
1627   if (CVD->getType()->isVariablyModifiedType()) {
1628     Size = CGF.getTypeSize(CVD->getType());
1629     // Align the size: ((size + align - 1) / align) * align
1630     Size = CGF.Builder.CreateNUWAdd(
1631         Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
1632     Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
1633     Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
1634   } else {
1635     CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
1636     Size = CGM.getSize(Sz.alignTo(Align));
1637   }
1638 
1639   const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
1640   assert(AA->getAllocator() &&
1641          "Expected allocator expression for non-default allocator.");
1642   llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
1643   // According to the standard, the original allocator type is a enum (integer).
1644   // Convert to pointer type, if required.
1645   if (Allocator->getType()->isIntegerTy())
1646     Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
1647   else if (Allocator->getType()->isPointerTy())
1648     Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
1649                                                                 CGM.VoidPtrTy);
1650 
1651   llvm::Value *Addr = OMPBuilder.createOMPAlloc(
1652       CGF.Builder, Size, Allocator,
1653       getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", "."));
1654   llvm::CallInst *FreeCI =
1655       OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator);
1656 
1657   CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI);
1658   Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1659       Addr,
1660       CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
1661       getNameWithSeparators({CVD->getName(), ".addr"}, ".", "."));
1662   return Address(Addr, Align);
1663 }
1664 
1665 Address CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
1666     CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr,
1667     SourceLocation Loc) {
1668   CodeGenModule &CGM = CGF.CGM;
1669   if (CGM.getLangOpts().OpenMPUseTLS &&
1670       CGM.getContext().getTargetInfo().isTLSSupported())
1671     return VDAddr;
1672 
1673   llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1674 
1675   llvm::Type *VarTy = VDAddr.getElementType();
1676   llvm::Value *Data =
1677       CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy);
1678   llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy));
1679   std::string Suffix = getNameWithSeparators({"cache", ""});
1680   llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix);
1681 
1682   llvm::CallInst *ThreadPrivateCacheCall =
1683       OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName);
1684 
1685   return Address(ThreadPrivateCacheCall, VDAddr.getAlignment());
1686 }
1687 
1688 std::string CodeGenFunction::OMPBuilderCBHelpers::getNameWithSeparators(
1689     ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) {
1690   SmallString<128> Buffer;
1691   llvm::raw_svector_ostream OS(Buffer);
1692   StringRef Sep = FirstSeparator;
1693   for (StringRef Part : Parts) {
1694     OS << Sep << Part;
1695     Sep = Separator;
1696   }
1697   return OS.str().str();
1698 }
1699 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
1700   if (CGM.getLangOpts().OpenMPIRBuilder) {
1701     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1702     // Check if we have any if clause associated with the directive.
1703     llvm::Value *IfCond = nullptr;
1704     if (const auto *C = S.getSingleClause<OMPIfClause>())
1705       IfCond = EmitScalarExpr(C->getCondition(),
1706                               /*IgnoreResultAssign=*/true);
1707 
1708     llvm::Value *NumThreads = nullptr;
1709     if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>())
1710       NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(),
1711                                   /*IgnoreResultAssign=*/true);
1712 
1713     ProcBindKind ProcBind = OMP_PROC_BIND_default;
1714     if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>())
1715       ProcBind = ProcBindClause->getProcBindKind();
1716 
1717     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1718 
1719     // The cleanup callback that finalizes all variabels at the given location,
1720     // thus calls destructors etc.
1721     auto FiniCB = [this](InsertPointTy IP) {
1722       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
1723     };
1724 
1725     // Privatization callback that performs appropriate action for
1726     // shared/private/firstprivate/lastprivate/copyin/... variables.
1727     //
1728     // TODO: This defaults to shared right now.
1729     auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1730                      llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
1731       // The next line is appropriate only for variables (Val) with the
1732       // data-sharing attribute "shared".
1733       ReplVal = &Val;
1734 
1735       return CodeGenIP;
1736     };
1737 
1738     const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
1739     const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt();
1740 
1741     auto BodyGenCB = [ParallelRegionBodyStmt,
1742                       this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
1743                             llvm::BasicBlock &ContinuationBB) {
1744       OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP,
1745                                                       ContinuationBB);
1746       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt,
1747                                              CodeGenIP, ContinuationBB);
1748     };
1749 
1750     CGCapturedStmtInfo CGSI(*CS, CR_OpenMP);
1751     CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
1752     llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
1753         AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
1754     Builder.restoreIP(
1755         OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB,
1756                                   IfCond, NumThreads, ProcBind, S.hasCancel()));
1757     return;
1758   }
1759 
1760   // Emit parallel region as a standalone region.
1761   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
1762     Action.Enter(CGF);
1763     OMPPrivateScope PrivateScope(CGF);
1764     bool Copyins = CGF.EmitOMPCopyinClause(S);
1765     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
1766     if (Copyins) {
1767       // Emit implicit barrier to synchronize threads and avoid data races on
1768       // propagation master's thread values of threadprivate variables to local
1769       // instances of that variables of all other implicit threads.
1770       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1771           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
1772           /*ForceSimpleCall=*/true);
1773     }
1774     CGF.EmitOMPPrivateClause(S, PrivateScope);
1775     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
1776     (void)PrivateScope.Privatize();
1777     CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
1778     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
1779   };
1780   {
1781     auto LPCRegion =
1782         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
1783     emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
1784                                    emitEmptyBoundParameters);
1785     emitPostUpdateForReductionClause(*this, S,
1786                                      [](CodeGenFunction &) { return nullptr; });
1787   }
1788   // Check for outer lastprivate conditional update.
1789   checkForLastprivateConditionalUpdate(*this, S);
1790 }
1791 
1792 void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) {
1793   EmitStmt(S.getIfStmt());
1794 }
1795 
1796 namespace {
1797 /// RAII to handle scopes for loop transformation directives.
1798 class OMPTransformDirectiveScopeRAII {
1799   OMPLoopScope *Scope = nullptr;
1800   CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr;
1801   CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr;
1802 
1803 public:
1804   OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) {
1805     if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) {
1806       Scope = new OMPLoopScope(CGF, *Dir);
1807       CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP);
1808       CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI);
1809     }
1810   }
1811   ~OMPTransformDirectiveScopeRAII() {
1812     if (!Scope)
1813       return;
1814     delete CapInfoRAII;
1815     delete CGSI;
1816     delete Scope;
1817   }
1818 };
1819 } // namespace
1820 
1821 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop,
1822                      int MaxLevel, int Level = 0) {
1823   assert(Level < MaxLevel && "Too deep lookup during loop body codegen.");
1824   const Stmt *SimplifiedS = S->IgnoreContainers();
1825   if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) {
1826     PrettyStackTraceLoc CrashInfo(
1827         CGF.getContext().getSourceManager(), CS->getLBracLoc(),
1828         "LLVM IR generation of compound statement ('{}')");
1829 
1830     // Keep track of the current cleanup stack depth, including debug scopes.
1831     CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange());
1832     for (const Stmt *CurStmt : CS->body())
1833       emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level);
1834     return;
1835   }
1836   if (SimplifiedS == NextLoop) {
1837     if (auto *Dir = dyn_cast<OMPLoopTransformationDirective>(SimplifiedS))
1838       SimplifiedS = Dir->getTransformedStmt();
1839     if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS))
1840       SimplifiedS = CanonLoop->getLoopStmt();
1841     if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) {
1842       S = For->getBody();
1843     } else {
1844       assert(isa<CXXForRangeStmt>(SimplifiedS) &&
1845              "Expected canonical for loop or range-based for loop.");
1846       const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS);
1847       CGF.EmitStmt(CXXFor->getLoopVarStmt());
1848       S = CXXFor->getBody();
1849     }
1850     if (Level + 1 < MaxLevel) {
1851       NextLoop = OMPLoopDirective::tryToFindNextInnerLoop(
1852           S, /*TryImperfectlyNestedLoops=*/true);
1853       emitBody(CGF, S, NextLoop, MaxLevel, Level + 1);
1854       return;
1855     }
1856   }
1857   CGF.EmitStmt(S);
1858 }
1859 
1860 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1861                                       JumpDest LoopExit) {
1862   RunCleanupsScope BodyScope(*this);
1863   // Update counters values on current iteration.
1864   for (const Expr *UE : D.updates())
1865     EmitIgnoredExpr(UE);
1866   // Update the linear variables.
1867   // In distribute directives only loop counters may be marked as linear, no
1868   // need to generate the code for them.
1869   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1870     for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1871       for (const Expr *UE : C->updates())
1872         EmitIgnoredExpr(UE);
1873     }
1874   }
1875 
1876   // On a continue in the body, jump to the end.
1877   JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
1878   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1879   for (const Expr *E : D.finals_conditions()) {
1880     if (!E)
1881       continue;
1882     // Check that loop counter in non-rectangular nest fits into the iteration
1883     // space.
1884     llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next");
1885     EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(),
1886                          getProfileCount(D.getBody()));
1887     EmitBlock(NextBB);
1888   }
1889 
1890   OMPPrivateScope InscanScope(*this);
1891   EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true);
1892   bool IsInscanRegion = InscanScope.Privatize();
1893   if (IsInscanRegion) {
1894     // Need to remember the block before and after scan directive
1895     // to dispatch them correctly depending on the clause used in
1896     // this directive, inclusive or exclusive. For inclusive scan the natural
1897     // order of the blocks is used, for exclusive clause the blocks must be
1898     // executed in reverse order.
1899     OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb");
1900     OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb");
1901     // No need to allocate inscan exit block, in simd mode it is selected in the
1902     // codegen for the scan directive.
1903     if (D.getDirectiveKind() != OMPD_simd && !getLangOpts().OpenMPSimd)
1904       OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb");
1905     OMPScanDispatch = createBasicBlock("omp.inscan.dispatch");
1906     EmitBranch(OMPScanDispatch);
1907     EmitBlock(OMPBeforeScanBlock);
1908   }
1909 
1910   // Emit loop variables for C++ range loops.
1911   const Stmt *Body =
1912       D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers();
1913   // Emit loop body.
1914   emitBody(*this, Body,
1915            OMPLoopBasedDirective::tryToFindNextInnerLoop(
1916                Body, /*TryImperfectlyNestedLoops=*/true),
1917            D.getLoopsNumber());
1918 
1919   // Jump to the dispatcher at the end of the loop body.
1920   if (IsInscanRegion)
1921     EmitBranch(OMPScanExitBlock);
1922 
1923   // The end (updates/cleanups).
1924   EmitBlock(Continue.getBlock());
1925   BreakContinueStack.pop_back();
1926 }
1927 
1928 using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>;
1929 
1930 /// Emit a captured statement and return the function as well as its captured
1931 /// closure context.
1932 static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF,
1933                                              const CapturedStmt *S) {
1934   LValue CapStruct = ParentCGF.InitCapturedStruct(*S);
1935   CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true);
1936   std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI =
1937       std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S);
1938   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get());
1939   llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S);
1940 
1941   return {F, CapStruct.getPointer(ParentCGF)};
1942 }
1943 
1944 /// Emit a call to a previously captured closure.
1945 static llvm::CallInst *
1946 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap,
1947                      llvm::ArrayRef<llvm::Value *> Args) {
1948   // Append the closure context to the argument.
1949   SmallVector<llvm::Value *> EffectiveArgs;
1950   EffectiveArgs.reserve(Args.size() + 1);
1951   llvm::append_range(EffectiveArgs, Args);
1952   EffectiveArgs.push_back(Cap.second);
1953 
1954   return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs);
1955 }
1956 
1957 llvm::CanonicalLoopInfo *
1958 CodeGenFunction::EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth) {
1959   assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented");
1960 
1961   // The caller is processing the loop-associated directive processing the \p
1962   // Depth loops nested in \p S. Put the previous pending loop-associated
1963   // directive to the stack. If the current loop-associated directive is a loop
1964   // transformation directive, it will push its generated loops onto the stack
1965   // such that together with the loops left here they form the combined loop
1966   // nest for the parent loop-associated directive.
1967   int ParentExpectedOMPLoopDepth = ExpectedOMPLoopDepth;
1968   ExpectedOMPLoopDepth = Depth;
1969 
1970   EmitStmt(S);
1971   assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops");
1972 
1973   // The last added loop is the outermost one.
1974   llvm::CanonicalLoopInfo *Result = OMPLoopNestStack.back();
1975 
1976   // Pop the \p Depth loops requested by the call from that stack and restore
1977   // the previous context.
1978   OMPLoopNestStack.pop_back_n(Depth);
1979   ExpectedOMPLoopDepth = ParentExpectedOMPLoopDepth;
1980 
1981   return Result;
1982 }
1983 
1984 void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) {
1985   const Stmt *SyntacticalLoop = S->getLoopStmt();
1986   if (!getLangOpts().OpenMPIRBuilder) {
1987     // Ignore if OpenMPIRBuilder is not enabled.
1988     EmitStmt(SyntacticalLoop);
1989     return;
1990   }
1991 
1992   LexicalScope ForScope(*this, S->getSourceRange());
1993 
1994   // Emit init statements. The Distance/LoopVar funcs may reference variable
1995   // declarations they contain.
1996   const Stmt *BodyStmt;
1997   if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) {
1998     if (const Stmt *InitStmt = For->getInit())
1999       EmitStmt(InitStmt);
2000     BodyStmt = For->getBody();
2001   } else if (const auto *RangeFor =
2002                  dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) {
2003     if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt())
2004       EmitStmt(RangeStmt);
2005     if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt())
2006       EmitStmt(BeginStmt);
2007     if (const DeclStmt *EndStmt = RangeFor->getEndStmt())
2008       EmitStmt(EndStmt);
2009     if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt())
2010       EmitStmt(LoopVarStmt);
2011     BodyStmt = RangeFor->getBody();
2012   } else
2013     llvm_unreachable("Expected for-stmt or range-based for-stmt");
2014 
2015   // Emit closure for later use. By-value captures will be captured here.
2016   const CapturedStmt *DistanceFunc = S->getDistanceFunc();
2017   EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc);
2018   const CapturedStmt *LoopVarFunc = S->getLoopVarFunc();
2019   EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc);
2020 
2021   // Call the distance function to get the number of iterations of the loop to
2022   // come.
2023   QualType LogicalTy = DistanceFunc->getCapturedDecl()
2024                            ->getParam(0)
2025                            ->getType()
2026                            .getNonReferenceType();
2027   Address CountAddr = CreateMemTemp(LogicalTy, ".count.addr");
2028   emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()});
2029   llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count");
2030 
2031   // Emit the loop structure.
2032   llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2033   auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP,
2034                            llvm::Value *IndVar) {
2035     Builder.restoreIP(CodeGenIP);
2036 
2037     // Emit the loop body: Convert the logical iteration number to the loop
2038     // variable and emit the body.
2039     const DeclRefExpr *LoopVarRef = S->getLoopVarRef();
2040     LValue LCVal = EmitLValue(LoopVarRef);
2041     Address LoopVarAddress = LCVal.getAddress(*this);
2042     emitCapturedStmtCall(*this, LoopVarClosure,
2043                          {LoopVarAddress.getPointer(), IndVar});
2044 
2045     RunCleanupsScope BodyScope(*this);
2046     EmitStmt(BodyStmt);
2047   };
2048   llvm::CanonicalLoopInfo *CL =
2049       OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal);
2050 
2051   // Finish up the loop.
2052   Builder.restoreIP(CL->getAfterIP());
2053   ForScope.ForceCleanup();
2054 
2055   // Remember the CanonicalLoopInfo for parent AST nodes consuming it.
2056   OMPLoopNestStack.push_back(CL);
2057 }
2058 
2059 void CodeGenFunction::EmitOMPInnerLoop(
2060     const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond,
2061     const Expr *IncExpr,
2062     const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
2063     const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
2064   auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
2065 
2066   // Start the loop with a block that tests the condition.
2067   auto CondBlock = createBasicBlock("omp.inner.for.cond");
2068   EmitBlock(CondBlock);
2069   const SourceRange R = S.getSourceRange();
2070 
2071   // If attributes are attached, push to the basic block with them.
2072   const auto &OMPED = cast<OMPExecutableDirective>(S);
2073   const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt();
2074   const Stmt *SS = ICS->getCapturedStmt();
2075   const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS);
2076   OMPLoopNestStack.clear();
2077   if (AS)
2078     LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(),
2079                    AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()),
2080                    SourceLocToDebugLoc(R.getEnd()));
2081   else
2082     LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2083                    SourceLocToDebugLoc(R.getEnd()));
2084 
2085   // If there are any cleanups between here and the loop-exit scope,
2086   // create a block to stage a loop exit along.
2087   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2088   if (RequiresCleanup)
2089     ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
2090 
2091   llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
2092 
2093   // Emit condition.
2094   EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
2095   if (ExitBlock != LoopExit.getBlock()) {
2096     EmitBlock(ExitBlock);
2097     EmitBranchThroughCleanup(LoopExit);
2098   }
2099 
2100   EmitBlock(LoopBody);
2101   incrementProfileCounter(&S);
2102 
2103   // Create a block for the increment.
2104   JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
2105   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2106 
2107   BodyGen(*this);
2108 
2109   // Emit "IV = IV + 1" and a back-edge to the condition block.
2110   EmitBlock(Continue.getBlock());
2111   EmitIgnoredExpr(IncExpr);
2112   PostIncGen(*this);
2113   BreakContinueStack.pop_back();
2114   EmitBranch(CondBlock);
2115   LoopStack.pop();
2116   // Emit the fall-through block.
2117   EmitBlock(LoopExit.getBlock());
2118 }
2119 
2120 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
2121   if (!HaveInsertPoint())
2122     return false;
2123   // Emit inits for the linear variables.
2124   bool HasLinears = false;
2125   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2126     for (const Expr *Init : C->inits()) {
2127       HasLinears = true;
2128       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
2129       if (const auto *Ref =
2130               dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
2131         AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
2132         const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
2133         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2134                         CapturedStmtInfo->lookup(OrigVD) != nullptr,
2135                         VD->getInit()->getType(), VK_LValue,
2136                         VD->getInit()->getExprLoc());
2137         EmitExprAsInit(
2138             &DRE, VD,
2139             MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
2140             /*capturedByInit=*/false);
2141         EmitAutoVarCleanups(Emission);
2142       } else {
2143         EmitVarDecl(*VD);
2144       }
2145     }
2146     // Emit the linear steps for the linear clauses.
2147     // If a step is not constant, it is pre-calculated before the loop.
2148     if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
2149       if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
2150         EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
2151         // Emit calculation of the linear step.
2152         EmitIgnoredExpr(CS);
2153       }
2154   }
2155   return HasLinears;
2156 }
2157 
2158 void CodeGenFunction::EmitOMPLinearClauseFinal(
2159     const OMPLoopDirective &D,
2160     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2161   if (!HaveInsertPoint())
2162     return;
2163   llvm::BasicBlock *DoneBB = nullptr;
2164   // Emit the final values of the linear variables.
2165   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2166     auto IC = C->varlist_begin();
2167     for (const Expr *F : C->finals()) {
2168       if (!DoneBB) {
2169         if (llvm::Value *Cond = CondGen(*this)) {
2170           // If the first post-update expression is found, emit conditional
2171           // block if it was requested.
2172           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
2173           DoneBB = createBasicBlock(".omp.linear.pu.done");
2174           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2175           EmitBlock(ThenBB);
2176         }
2177       }
2178       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
2179       DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD),
2180                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
2181                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
2182       Address OrigAddr = EmitLValue(&DRE).getAddress(*this);
2183       CodeGenFunction::OMPPrivateScope VarScope(*this);
2184       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
2185       (void)VarScope.Privatize();
2186       EmitIgnoredExpr(F);
2187       ++IC;
2188     }
2189     if (const Expr *PostUpdate = C->getPostUpdateExpr())
2190       EmitIgnoredExpr(PostUpdate);
2191   }
2192   if (DoneBB)
2193     EmitBlock(DoneBB, /*IsFinished=*/true);
2194 }
2195 
2196 static void emitAlignedClause(CodeGenFunction &CGF,
2197                               const OMPExecutableDirective &D) {
2198   if (!CGF.HaveInsertPoint())
2199     return;
2200   for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
2201     llvm::APInt ClauseAlignment(64, 0);
2202     if (const Expr *AlignmentExpr = Clause->getAlignment()) {
2203       auto *AlignmentCI =
2204           cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
2205       ClauseAlignment = AlignmentCI->getValue();
2206     }
2207     for (const Expr *E : Clause->varlists()) {
2208       llvm::APInt Alignment(ClauseAlignment);
2209       if (Alignment == 0) {
2210         // OpenMP [2.8.1, Description]
2211         // If no optional parameter is specified, implementation-defined default
2212         // alignments for SIMD instructions on the target platforms are assumed.
2213         Alignment =
2214             CGF.getContext()
2215                 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2216                     E->getType()->getPointeeType()))
2217                 .getQuantity();
2218       }
2219       assert((Alignment == 0 || Alignment.isPowerOf2()) &&
2220              "alignment is not power of 2");
2221       if (Alignment != 0) {
2222         llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
2223         CGF.emitAlignmentAssumption(
2224             PtrValue, E, /*No second loc needed*/ SourceLocation(),
2225             llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment));
2226       }
2227     }
2228   }
2229 }
2230 
2231 void CodeGenFunction::EmitOMPPrivateLoopCounters(
2232     const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
2233   if (!HaveInsertPoint())
2234     return;
2235   auto I = S.private_counters().begin();
2236   for (const Expr *E : S.counters()) {
2237     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2238     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
2239     // Emit var without initialization.
2240     AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
2241     EmitAutoVarCleanups(VarEmission);
2242     LocalDeclMap.erase(PrivateVD);
2243     (void)LoopScope.addPrivate(
2244         VD, [&VarEmission]() { return VarEmission.getAllocatedAddress(); });
2245     if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
2246         VD->hasGlobalStorage()) {
2247       (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
2248         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD),
2249                         LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
2250                         E->getType(), VK_LValue, E->getExprLoc());
2251         return EmitLValue(&DRE).getAddress(*this);
2252       });
2253     } else {
2254       (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
2255         return VarEmission.getAllocatedAddress();
2256       });
2257     }
2258     ++I;
2259   }
2260   // Privatize extra loop counters used in loops for ordered(n) clauses.
2261   for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
2262     if (!C->getNumForLoops())
2263       continue;
2264     for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size();
2265          I < E; ++I) {
2266       const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
2267       const auto *VD = cast<VarDecl>(DRE->getDecl());
2268       // Override only those variables that can be captured to avoid re-emission
2269       // of the variables declared within the loops.
2270       if (DRE->refersToEnclosingVariableOrCapture()) {
2271         (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
2272           return CreateMemTemp(DRE->getType(), VD->getName());
2273         });
2274       }
2275     }
2276   }
2277 }
2278 
2279 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
2280                         const Expr *Cond, llvm::BasicBlock *TrueBlock,
2281                         llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
2282   if (!CGF.HaveInsertPoint())
2283     return;
2284   {
2285     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
2286     CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
2287     (void)PreCondScope.Privatize();
2288     // Get initial values of real counters.
2289     for (const Expr *I : S.inits()) {
2290       CGF.EmitIgnoredExpr(I);
2291     }
2292   }
2293   // Create temp loop control variables with their init values to support
2294   // non-rectangular loops.
2295   CodeGenFunction::OMPMapVars PreCondVars;
2296   for (const Expr *E : S.dependent_counters()) {
2297     if (!E)
2298       continue;
2299     assert(!E->getType().getNonReferenceType()->isRecordType() &&
2300            "dependent counter must not be an iterator.");
2301     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2302     Address CounterAddr =
2303         CGF.CreateMemTemp(VD->getType().getNonReferenceType());
2304     (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr);
2305   }
2306   (void)PreCondVars.apply(CGF);
2307   for (const Expr *E : S.dependent_inits()) {
2308     if (!E)
2309       continue;
2310     CGF.EmitIgnoredExpr(E);
2311   }
2312   // Check that loop is executed at least one time.
2313   CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
2314   PreCondVars.restore(CGF);
2315 }
2316 
2317 void CodeGenFunction::EmitOMPLinearClause(
2318     const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
2319   if (!HaveInsertPoint())
2320     return;
2321   llvm::DenseSet<const VarDecl *> SIMDLCVs;
2322   if (isOpenMPSimdDirective(D.getDirectiveKind())) {
2323     const auto *LoopDirective = cast<OMPLoopDirective>(&D);
2324     for (const Expr *C : LoopDirective->counters()) {
2325       SIMDLCVs.insert(
2326           cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
2327     }
2328   }
2329   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
2330     auto CurPrivate = C->privates().begin();
2331     for (const Expr *E : C->varlists()) {
2332       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2333       const auto *PrivateVD =
2334           cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
2335       if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
2336         bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
2337           // Emit private VarDecl with copy init.
2338           EmitVarDecl(*PrivateVD);
2339           return GetAddrOfLocalVar(PrivateVD);
2340         });
2341         assert(IsRegistered && "linear var already registered as private");
2342         // Silence the warning about unused variable.
2343         (void)IsRegistered;
2344       } else {
2345         EmitVarDecl(*PrivateVD);
2346       }
2347       ++CurPrivate;
2348     }
2349   }
2350 }
2351 
2352 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
2353                                      const OMPExecutableDirective &D) {
2354   if (!CGF.HaveInsertPoint())
2355     return;
2356   if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
2357     RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
2358                                  /*ignoreResult=*/true);
2359     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2360     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2361     // In presence of finite 'safelen', it may be unsafe to mark all
2362     // the memory instructions parallel, because loop-carried
2363     // dependences of 'safelen' iterations are possible.
2364     CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
2365   } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
2366     RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
2367                                  /*ignoreResult=*/true);
2368     auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
2369     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
2370     // In presence of finite 'safelen', it may be unsafe to mark all
2371     // the memory instructions parallel, because loop-carried
2372     // dependences of 'safelen' iterations are possible.
2373     CGF.LoopStack.setParallel(/*Enable=*/false);
2374   }
2375 }
2376 
2377 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) {
2378   // Walk clauses and process safelen/lastprivate.
2379   LoopStack.setParallel(/*Enable=*/true);
2380   LoopStack.setVectorizeEnable();
2381   emitSimdlenSafelenClause(*this, D);
2382   if (const auto *C = D.getSingleClause<OMPOrderClause>())
2383     if (C->getKind() == OMPC_ORDER_concurrent)
2384       LoopStack.setParallel(/*Enable=*/true);
2385   if ((D.getDirectiveKind() == OMPD_simd ||
2386        (getLangOpts().OpenMPSimd &&
2387         isOpenMPSimdDirective(D.getDirectiveKind()))) &&
2388       llvm::any_of(D.getClausesOfKind<OMPReductionClause>(),
2389                    [](const OMPReductionClause *C) {
2390                      return C->getModifier() == OMPC_REDUCTION_inscan;
2391                    }))
2392     // Disable parallel access in case of prefix sum.
2393     LoopStack.setParallel(/*Enable=*/false);
2394 }
2395 
2396 void CodeGenFunction::EmitOMPSimdFinal(
2397     const OMPLoopDirective &D,
2398     const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
2399   if (!HaveInsertPoint())
2400     return;
2401   llvm::BasicBlock *DoneBB = nullptr;
2402   auto IC = D.counters().begin();
2403   auto IPC = D.private_counters().begin();
2404   for (const Expr *F : D.finals()) {
2405     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
2406     const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
2407     const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
2408     if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
2409         OrigVD->hasGlobalStorage() || CED) {
2410       if (!DoneBB) {
2411         if (llvm::Value *Cond = CondGen(*this)) {
2412           // If the first post-update expression is found, emit conditional
2413           // block if it was requested.
2414           llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
2415           DoneBB = createBasicBlock(".omp.final.done");
2416           Builder.CreateCondBr(Cond, ThenBB, DoneBB);
2417           EmitBlock(ThenBB);
2418         }
2419       }
2420       Address OrigAddr = Address::invalid();
2421       if (CED) {
2422         OrigAddr =
2423             EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this);
2424       } else {
2425         DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD),
2426                         /*RefersToEnclosingVariableOrCapture=*/false,
2427                         (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
2428         OrigAddr = EmitLValue(&DRE).getAddress(*this);
2429       }
2430       OMPPrivateScope VarScope(*this);
2431       VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
2432       (void)VarScope.Privatize();
2433       EmitIgnoredExpr(F);
2434     }
2435     ++IC;
2436     ++IPC;
2437   }
2438   if (DoneBB)
2439     EmitBlock(DoneBB, /*IsFinished=*/true);
2440 }
2441 
2442 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
2443                                          const OMPLoopDirective &S,
2444                                          CodeGenFunction::JumpDest LoopExit) {
2445   CGF.EmitOMPLoopBody(S, LoopExit);
2446   CGF.EmitStopPoint(&S);
2447 }
2448 
2449 /// Emit a helper variable and return corresponding lvalue.
2450 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
2451                                const DeclRefExpr *Helper) {
2452   auto VDecl = cast<VarDecl>(Helper->getDecl());
2453   CGF.EmitVarDecl(*VDecl);
2454   return CGF.EmitLValue(Helper);
2455 }
2456 
2457 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
2458                                const RegionCodeGenTy &SimdInitGen,
2459                                const RegionCodeGenTy &BodyCodeGen) {
2460   auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF,
2461                                                     PrePostActionTy &) {
2462     CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S);
2463     CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2464     SimdInitGen(CGF);
2465 
2466     BodyCodeGen(CGF);
2467   };
2468   auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
2469     CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
2470     CGF.LoopStack.setVectorizeEnable(/*Enable=*/false);
2471 
2472     BodyCodeGen(CGF);
2473   };
2474   const Expr *IfCond = nullptr;
2475   if (isOpenMPSimdDirective(S.getDirectiveKind())) {
2476     for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2477       if (CGF.getLangOpts().OpenMP >= 50 &&
2478           (C->getNameModifier() == OMPD_unknown ||
2479            C->getNameModifier() == OMPD_simd)) {
2480         IfCond = C->getCondition();
2481         break;
2482       }
2483     }
2484   }
2485   if (IfCond) {
2486     CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2487   } else {
2488     RegionCodeGenTy ThenRCG(ThenGen);
2489     ThenRCG(CGF);
2490   }
2491 }
2492 
2493 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
2494                               PrePostActionTy &Action) {
2495   Action.Enter(CGF);
2496   assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
2497          "Expected simd directive");
2498   OMPLoopScope PreInitScope(CGF, S);
2499   // if (PreCond) {
2500   //   for (IV in 0..LastIteration) BODY;
2501   //   <Final counter/linear vars updates>;
2502   // }
2503   //
2504   if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
2505       isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
2506       isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
2507     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
2508     (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
2509   }
2510 
2511   // Emit: if (PreCond) - begin.
2512   // If the condition constant folds and can be elided, avoid emitting the
2513   // whole loop.
2514   bool CondConstant;
2515   llvm::BasicBlock *ContBlock = nullptr;
2516   if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
2517     if (!CondConstant)
2518       return;
2519   } else {
2520     llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
2521     ContBlock = CGF.createBasicBlock("simd.if.end");
2522     emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
2523                 CGF.getProfileCount(&S));
2524     CGF.EmitBlock(ThenBlock);
2525     CGF.incrementProfileCounter(&S);
2526   }
2527 
2528   // Emit the loop iteration variable.
2529   const Expr *IVExpr = S.getIterationVariable();
2530   const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
2531   CGF.EmitVarDecl(*IVDecl);
2532   CGF.EmitIgnoredExpr(S.getInit());
2533 
2534   // Emit the iterations count variable.
2535   // If it is not a variable, Sema decided to calculate iterations count on
2536   // each iteration (e.g., it is foldable into a constant).
2537   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
2538     CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
2539     // Emit calculation of the iterations count.
2540     CGF.EmitIgnoredExpr(S.getCalcLastIteration());
2541   }
2542 
2543   emitAlignedClause(CGF, S);
2544   (void)CGF.EmitOMPLinearClauseInit(S);
2545   {
2546     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
2547     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
2548     CGF.EmitOMPLinearClause(S, LoopScope);
2549     CGF.EmitOMPPrivateClause(S, LoopScope);
2550     CGF.EmitOMPReductionClauseInit(S, LoopScope);
2551     CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
2552         CGF, S, CGF.EmitLValue(S.getIterationVariable()));
2553     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
2554     (void)LoopScope.Privatize();
2555     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
2556       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
2557 
2558     emitCommonSimdLoop(
2559         CGF, S,
2560         [&S](CodeGenFunction &CGF, PrePostActionTy &) {
2561           CGF.EmitOMPSimdInit(S);
2562         },
2563         [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2564           CGF.EmitOMPInnerLoop(
2565               S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
2566               [&S](CodeGenFunction &CGF) {
2567                 emitOMPLoopBodyWithStopPoint(CGF, S,
2568                                              CodeGenFunction::JumpDest());
2569               },
2570               [](CodeGenFunction &) {});
2571         });
2572     CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
2573     // Emit final copy of the lastprivate variables at the end of loops.
2574     if (HasLastprivateClause)
2575       CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
2576     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
2577     emitPostUpdateForReductionClause(CGF, S,
2578                                      [](CodeGenFunction &) { return nullptr; });
2579   }
2580   CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
2581   // Emit: if (PreCond) - end.
2582   if (ContBlock) {
2583     CGF.EmitBranch(ContBlock);
2584     CGF.EmitBlock(ContBlock, true);
2585   }
2586 }
2587 
2588 static bool isSupportedByOpenMPIRBuilder(const OMPExecutableDirective &S) {
2589   // Check for unsupported clauses
2590   if (!S.clauses().empty()) {
2591     // Currently no clause is supported
2592     return false;
2593   }
2594 
2595   // Check if we have a statement with the ordered directive.
2596   // Visit the statement hierarchy to find a compound statement
2597   // with a ordered directive in it.
2598   if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(S.getRawStmt())) {
2599     if (const Stmt *SyntacticalLoop = CanonLoop->getLoopStmt()) {
2600       for (const Stmt *SubStmt : SyntacticalLoop->children()) {
2601         if (!SubStmt)
2602           continue;
2603         if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(SubStmt)) {
2604           for (const Stmt *CSSubStmt : CS->children()) {
2605             if (!CSSubStmt)
2606               continue;
2607             if (isa<OMPOrderedDirective>(CSSubStmt)) {
2608               return false;
2609             }
2610           }
2611         }
2612       }
2613     }
2614   }
2615   return true;
2616 }
2617 
2618 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
2619   bool UseOMPIRBuilder =
2620       CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S);
2621   if (UseOMPIRBuilder) {
2622     auto &&CodeGenIRBuilder = [this, &S, UseOMPIRBuilder](CodeGenFunction &CGF,
2623                                                           PrePostActionTy &) {
2624       // Use the OpenMPIRBuilder if enabled.
2625       if (UseOMPIRBuilder) {
2626         // Emit the associated statement and get its loop representation.
2627         llvm::DebugLoc DL = SourceLocToDebugLoc(S.getBeginLoc());
2628         const Stmt *Inner = S.getRawStmt();
2629         llvm::CanonicalLoopInfo *CLI =
2630             EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
2631 
2632         llvm::OpenMPIRBuilder &OMPBuilder =
2633             CGM.getOpenMPRuntime().getOMPBuilder();
2634         // Add SIMD specific metadata
2635         OMPBuilder.applySimd(DL, CLI);
2636         return;
2637       }
2638     };
2639     {
2640       auto LPCRegion =
2641           CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2642       OMPLexicalScope Scope(*this, S, OMPD_unknown);
2643       CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd,
2644                                                   CodeGenIRBuilder);
2645     }
2646     return;
2647   }
2648 
2649   ParentLoopDirectiveForScanRegion ScanRegion(*this, S);
2650   OMPFirstScanLoop = true;
2651   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
2652     emitOMPSimdRegion(CGF, S, Action);
2653   };
2654   {
2655     auto LPCRegion =
2656         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
2657     OMPLexicalScope Scope(*this, S, OMPD_unknown);
2658     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
2659   }
2660   // Check for outer lastprivate conditional update.
2661   checkForLastprivateConditionalUpdate(*this, S);
2662 }
2663 
2664 void CodeGenFunction::EmitOMPTileDirective(const OMPTileDirective &S) {
2665   // Emit the de-sugared statement.
2666   OMPTransformDirectiveScopeRAII TileScope(*this, &S);
2667   EmitStmt(S.getTransformedStmt());
2668 }
2669 
2670 void CodeGenFunction::EmitOMPUnrollDirective(const OMPUnrollDirective &S) {
2671   bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder;
2672 
2673   if (UseOMPIRBuilder) {
2674     auto DL = SourceLocToDebugLoc(S.getBeginLoc());
2675     const Stmt *Inner = S.getRawStmt();
2676 
2677     // Consume nested loop. Clear the entire remaining loop stack because a
2678     // fully unrolled loop is non-transformable. For partial unrolling the
2679     // generated outer loop is pushed back to the stack.
2680     llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
2681     OMPLoopNestStack.clear();
2682 
2683     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
2684 
2685     bool NeedsUnrolledCLI = ExpectedOMPLoopDepth >= 1;
2686     llvm::CanonicalLoopInfo *UnrolledCLI = nullptr;
2687 
2688     if (S.hasClausesOfKind<OMPFullClause>()) {
2689       assert(ExpectedOMPLoopDepth == 0);
2690       OMPBuilder.unrollLoopFull(DL, CLI);
2691     } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
2692       uint64_t Factor = 0;
2693       if (Expr *FactorExpr = PartialClause->getFactor()) {
2694         Factor = FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
2695         assert(Factor >= 1 && "Only positive factors are valid");
2696       }
2697       OMPBuilder.unrollLoopPartial(DL, CLI, Factor,
2698                                    NeedsUnrolledCLI ? &UnrolledCLI : nullptr);
2699     } else {
2700       OMPBuilder.unrollLoopHeuristic(DL, CLI);
2701     }
2702 
2703     assert((!NeedsUnrolledCLI || UnrolledCLI) &&
2704            "NeedsUnrolledCLI implies UnrolledCLI to be set");
2705     if (UnrolledCLI)
2706       OMPLoopNestStack.push_back(UnrolledCLI);
2707 
2708     return;
2709   }
2710 
2711   // This function is only called if the unrolled loop is not consumed by any
2712   // other loop-associated construct. Such a loop-associated construct will have
2713   // used the transformed AST.
2714 
2715   // Set the unroll metadata for the next emitted loop.
2716   LoopStack.setUnrollState(LoopAttributes::Enable);
2717 
2718   if (S.hasClausesOfKind<OMPFullClause>()) {
2719     LoopStack.setUnrollState(LoopAttributes::Full);
2720   } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) {
2721     if (Expr *FactorExpr = PartialClause->getFactor()) {
2722       uint64_t Factor =
2723           FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue();
2724       assert(Factor >= 1 && "Only positive factors are valid");
2725       LoopStack.setUnrollCount(Factor);
2726     }
2727   }
2728 
2729   EmitStmt(S.getAssociatedStmt());
2730 }
2731 
2732 void CodeGenFunction::EmitOMPOuterLoop(
2733     bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
2734     CodeGenFunction::OMPPrivateScope &LoopScope,
2735     const CodeGenFunction::OMPLoopArguments &LoopArgs,
2736     const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
2737     const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
2738   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2739 
2740   const Expr *IVExpr = S.getIterationVariable();
2741   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2742   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2743 
2744   JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
2745 
2746   // Start the loop with a block that tests the condition.
2747   llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
2748   EmitBlock(CondBlock);
2749   const SourceRange R = S.getSourceRange();
2750   OMPLoopNestStack.clear();
2751   LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
2752                  SourceLocToDebugLoc(R.getEnd()));
2753 
2754   llvm::Value *BoolCondVal = nullptr;
2755   if (!DynamicOrOrdered) {
2756     // UB = min(UB, GlobalUB) or
2757     // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
2758     // 'distribute parallel for')
2759     EmitIgnoredExpr(LoopArgs.EUB);
2760     // IV = LB
2761     EmitIgnoredExpr(LoopArgs.Init);
2762     // IV < UB
2763     BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
2764   } else {
2765     BoolCondVal =
2766         RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
2767                        LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
2768   }
2769 
2770   // If there are any cleanups between here and the loop-exit scope,
2771   // create a block to stage a loop exit along.
2772   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
2773   if (LoopScope.requiresCleanups())
2774     ExitBlock = createBasicBlock("omp.dispatch.cleanup");
2775 
2776   llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
2777   Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
2778   if (ExitBlock != LoopExit.getBlock()) {
2779     EmitBlock(ExitBlock);
2780     EmitBranchThroughCleanup(LoopExit);
2781   }
2782   EmitBlock(LoopBody);
2783 
2784   // Emit "IV = LB" (in case of static schedule, we have already calculated new
2785   // LB for loop condition and emitted it above).
2786   if (DynamicOrOrdered)
2787     EmitIgnoredExpr(LoopArgs.Init);
2788 
2789   // Create a block for the increment.
2790   JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
2791   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
2792 
2793   emitCommonSimdLoop(
2794       *this, S,
2795       [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) {
2796         // Generate !llvm.loop.parallel metadata for loads and stores for loops
2797         // with dynamic/guided scheduling and without ordered clause.
2798         if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
2799           CGF.LoopStack.setParallel(!IsMonotonic);
2800           if (const auto *C = S.getSingleClause<OMPOrderClause>())
2801             if (C->getKind() == OMPC_ORDER_concurrent)
2802               CGF.LoopStack.setParallel(/*Enable=*/true);
2803         } else {
2804           CGF.EmitOMPSimdInit(S);
2805         }
2806       },
2807       [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered,
2808        &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
2809         SourceLocation Loc = S.getBeginLoc();
2810         // when 'distribute' is not combined with a 'for':
2811         // while (idx <= UB) { BODY; ++idx; }
2812         // when 'distribute' is combined with a 'for'
2813         // (e.g. 'distribute parallel for')
2814         // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
2815         CGF.EmitOMPInnerLoop(
2816             S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
2817             [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
2818               CodeGenLoop(CGF, S, LoopExit);
2819             },
2820             [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
2821               CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
2822             });
2823       });
2824 
2825   EmitBlock(Continue.getBlock());
2826   BreakContinueStack.pop_back();
2827   if (!DynamicOrOrdered) {
2828     // Emit "LB = LB + Stride", "UB = UB + Stride".
2829     EmitIgnoredExpr(LoopArgs.NextLB);
2830     EmitIgnoredExpr(LoopArgs.NextUB);
2831   }
2832 
2833   EmitBranch(CondBlock);
2834   OMPLoopNestStack.clear();
2835   LoopStack.pop();
2836   // Emit the fall-through block.
2837   EmitBlock(LoopExit.getBlock());
2838 
2839   // Tell the runtime we are done.
2840   auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
2841     if (!DynamicOrOrdered)
2842       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
2843                                                      S.getDirectiveKind());
2844   };
2845   OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
2846 }
2847 
2848 void CodeGenFunction::EmitOMPForOuterLoop(
2849     const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
2850     const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2851     const OMPLoopArguments &LoopArgs,
2852     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
2853   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2854 
2855   // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
2856   const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind.Schedule);
2857 
2858   assert((Ordered || !RT.isStaticNonchunked(ScheduleKind.Schedule,
2859                                             LoopArgs.Chunk != nullptr)) &&
2860          "static non-chunked schedule does not need outer loop");
2861 
2862   // Emit outer loop.
2863   //
2864   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2865   // When schedule(dynamic,chunk_size) is specified, the iterations are
2866   // distributed to threads in the team in chunks as the threads request them.
2867   // Each thread executes a chunk of iterations, then requests another chunk,
2868   // until no chunks remain to be distributed. Each chunk contains chunk_size
2869   // iterations, except for the last chunk to be distributed, which may have
2870   // fewer iterations. When no chunk_size is specified, it defaults to 1.
2871   //
2872   // When schedule(guided,chunk_size) is specified, the iterations are assigned
2873   // to threads in the team in chunks as the executing threads request them.
2874   // Each thread executes a chunk of iterations, then requests another chunk,
2875   // until no chunks remain to be assigned. For a chunk_size of 1, the size of
2876   // each chunk is proportional to the number of unassigned iterations divided
2877   // by the number of threads in the team, decreasing to 1. For a chunk_size
2878   // with value k (greater than 1), the size of each chunk is determined in the
2879   // same way, with the restriction that the chunks do not contain fewer than k
2880   // iterations (except for the last chunk to be assigned, which may have fewer
2881   // than k iterations).
2882   //
2883   // When schedule(auto) is specified, the decision regarding scheduling is
2884   // delegated to the compiler and/or runtime system. The programmer gives the
2885   // implementation the freedom to choose any possible mapping of iterations to
2886   // threads in the team.
2887   //
2888   // When schedule(runtime) is specified, the decision regarding scheduling is
2889   // deferred until run time, and the schedule and chunk size are taken from the
2890   // run-sched-var ICV. If the ICV is set to auto, the schedule is
2891   // implementation defined
2892   //
2893   // while(__kmpc_dispatch_next(&LB, &UB)) {
2894   //   idx = LB;
2895   //   while (idx <= UB) { BODY; ++idx;
2896   //   __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
2897   //   } // inner loop
2898   // }
2899   //
2900   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
2901   // When schedule(static, chunk_size) is specified, iterations are divided into
2902   // chunks of size chunk_size, and the chunks are assigned to the threads in
2903   // the team in a round-robin fashion in the order of the thread number.
2904   //
2905   // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
2906   //   while (idx <= UB) { BODY; ++idx; } // inner loop
2907   //   LB = LB + ST;
2908   //   UB = UB + ST;
2909   // }
2910   //
2911 
2912   const Expr *IVExpr = S.getIterationVariable();
2913   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2914   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2915 
2916   if (DynamicOrOrdered) {
2917     const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
2918         CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
2919     llvm::Value *LBVal = DispatchBounds.first;
2920     llvm::Value *UBVal = DispatchBounds.second;
2921     CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
2922                                                              LoopArgs.Chunk};
2923     RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
2924                            IVSigned, Ordered, DipatchRTInputValues);
2925   } else {
2926     CGOpenMPRuntime::StaticRTInput StaticInit(
2927         IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
2928         LoopArgs.ST, LoopArgs.Chunk);
2929     RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
2930                          ScheduleKind, StaticInit);
2931   }
2932 
2933   auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
2934                                     const unsigned IVSize,
2935                                     const bool IVSigned) {
2936     if (Ordered) {
2937       CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
2938                                                             IVSigned);
2939     }
2940   };
2941 
2942   OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
2943                                  LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
2944   OuterLoopArgs.IncExpr = S.getInc();
2945   OuterLoopArgs.Init = S.getInit();
2946   OuterLoopArgs.Cond = S.getCond();
2947   OuterLoopArgs.NextLB = S.getNextLowerBound();
2948   OuterLoopArgs.NextUB = S.getNextUpperBound();
2949   EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
2950                    emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
2951 }
2952 
2953 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
2954                              const unsigned IVSize, const bool IVSigned) {}
2955 
2956 void CodeGenFunction::EmitOMPDistributeOuterLoop(
2957     OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
2958     OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
2959     const CodeGenLoopTy &CodeGenLoopContent) {
2960 
2961   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
2962 
2963   // Emit outer loop.
2964   // Same behavior as a OMPForOuterLoop, except that schedule cannot be
2965   // dynamic
2966   //
2967 
2968   const Expr *IVExpr = S.getIterationVariable();
2969   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
2970   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
2971 
2972   CGOpenMPRuntime::StaticRTInput StaticInit(
2973       IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
2974       LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
2975   RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
2976 
2977   // for combined 'distribute' and 'for' the increment expression of distribute
2978   // is stored in DistInc. For 'distribute' alone, it is in Inc.
2979   Expr *IncExpr;
2980   if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
2981     IncExpr = S.getDistInc();
2982   else
2983     IncExpr = S.getInc();
2984 
2985   // this routine is shared by 'omp distribute parallel for' and
2986   // 'omp distribute': select the right EUB expression depending on the
2987   // directive
2988   OMPLoopArguments OuterLoopArgs;
2989   OuterLoopArgs.LB = LoopArgs.LB;
2990   OuterLoopArgs.UB = LoopArgs.UB;
2991   OuterLoopArgs.ST = LoopArgs.ST;
2992   OuterLoopArgs.IL = LoopArgs.IL;
2993   OuterLoopArgs.Chunk = LoopArgs.Chunk;
2994   OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2995                           ? S.getCombinedEnsureUpperBound()
2996                           : S.getEnsureUpperBound();
2997   OuterLoopArgs.IncExpr = IncExpr;
2998   OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
2999                            ? S.getCombinedInit()
3000                            : S.getInit();
3001   OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3002                            ? S.getCombinedCond()
3003                            : S.getCond();
3004   OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3005                              ? S.getCombinedNextLowerBound()
3006                              : S.getNextLowerBound();
3007   OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3008                              ? S.getCombinedNextUpperBound()
3009                              : S.getNextUpperBound();
3010 
3011   EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
3012                    LoopScope, OuterLoopArgs, CodeGenLoopContent,
3013                    emitEmptyOrdered);
3014 }
3015 
3016 static std::pair<LValue, LValue>
3017 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
3018                                      const OMPExecutableDirective &S) {
3019   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
3020   LValue LB =
3021       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
3022   LValue UB =
3023       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
3024 
3025   // When composing 'distribute' with 'for' (e.g. as in 'distribute
3026   // parallel for') we need to use the 'distribute'
3027   // chunk lower and upper bounds rather than the whole loop iteration
3028   // space. These are parameters to the outlined function for 'parallel'
3029   // and we copy the bounds of the previous schedule into the
3030   // the current ones.
3031   LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
3032   LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
3033   llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
3034       PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
3035   PrevLBVal = CGF.EmitScalarConversion(
3036       PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
3037       LS.getIterationVariable()->getType(),
3038       LS.getPrevLowerBoundVariable()->getExprLoc());
3039   llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
3040       PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
3041   PrevUBVal = CGF.EmitScalarConversion(
3042       PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
3043       LS.getIterationVariable()->getType(),
3044       LS.getPrevUpperBoundVariable()->getExprLoc());
3045 
3046   CGF.EmitStoreOfScalar(PrevLBVal, LB);
3047   CGF.EmitStoreOfScalar(PrevUBVal, UB);
3048 
3049   return {LB, UB};
3050 }
3051 
3052 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
3053 /// we need to use the LB and UB expressions generated by the worksharing
3054 /// code generation support, whereas in non combined situations we would
3055 /// just emit 0 and the LastIteration expression
3056 /// This function is necessary due to the difference of the LB and UB
3057 /// types for the RT emission routines for 'for_static_init' and
3058 /// 'for_dispatch_init'
3059 static std::pair<llvm::Value *, llvm::Value *>
3060 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
3061                                         const OMPExecutableDirective &S,
3062                                         Address LB, Address UB) {
3063   const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
3064   const Expr *IVExpr = LS.getIterationVariable();
3065   // when implementing a dynamic schedule for a 'for' combined with a
3066   // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
3067   // is not normalized as each team only executes its own assigned
3068   // distribute chunk
3069   QualType IteratorTy = IVExpr->getType();
3070   llvm::Value *LBVal =
3071       CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3072   llvm::Value *UBVal =
3073       CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
3074   return {LBVal, UBVal};
3075 }
3076 
3077 static void emitDistributeParallelForDistributeInnerBoundParams(
3078     CodeGenFunction &CGF, const OMPExecutableDirective &S,
3079     llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
3080   const auto &Dir = cast<OMPLoopDirective>(S);
3081   LValue LB =
3082       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
3083   llvm::Value *LBCast =
3084       CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)),
3085                                 CGF.SizeTy, /*isSigned=*/false);
3086   CapturedVars.push_back(LBCast);
3087   LValue UB =
3088       CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
3089 
3090   llvm::Value *UBCast =
3091       CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)),
3092                                 CGF.SizeTy, /*isSigned=*/false);
3093   CapturedVars.push_back(UBCast);
3094 }
3095 
3096 static void
3097 emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
3098                                  const OMPLoopDirective &S,
3099                                  CodeGenFunction::JumpDest LoopExit) {
3100   auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
3101                                          PrePostActionTy &Action) {
3102     Action.Enter(CGF);
3103     bool HasCancel = false;
3104     if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
3105       if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
3106         HasCancel = D->hasCancel();
3107       else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
3108         HasCancel = D->hasCancel();
3109       else if (const auto *D =
3110                    dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
3111         HasCancel = D->hasCancel();
3112     }
3113     CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
3114                                                      HasCancel);
3115     CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
3116                                emitDistributeParallelForInnerBounds,
3117                                emitDistributeParallelForDispatchBounds);
3118   };
3119 
3120   emitCommonOMPParallelDirective(
3121       CGF, S,
3122       isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
3123       CGInlinedWorksharingLoop,
3124       emitDistributeParallelForDistributeInnerBoundParams);
3125 }
3126 
3127 void CodeGenFunction::EmitOMPDistributeParallelForDirective(
3128     const OMPDistributeParallelForDirective &S) {
3129   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3130     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3131                               S.getDistInc());
3132   };
3133   OMPLexicalScope Scope(*this, S, OMPD_parallel);
3134   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3135 }
3136 
3137 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
3138     const OMPDistributeParallelForSimdDirective &S) {
3139   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3140     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
3141                               S.getDistInc());
3142   };
3143   OMPLexicalScope Scope(*this, S, OMPD_parallel);
3144   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3145 }
3146 
3147 void CodeGenFunction::EmitOMPDistributeSimdDirective(
3148     const OMPDistributeSimdDirective &S) {
3149   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3150     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3151   };
3152   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3153   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
3154 }
3155 
3156 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
3157     CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
3158   // Emit SPMD target parallel for region as a standalone region.
3159   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3160     emitOMPSimdRegion(CGF, S, Action);
3161   };
3162   llvm::Function *Fn;
3163   llvm::Constant *Addr;
3164   // Emit target region as a standalone region.
3165   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
3166       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
3167   assert(Fn && Addr && "Target device function emission failed.");
3168 }
3169 
3170 void CodeGenFunction::EmitOMPTargetSimdDirective(
3171     const OMPTargetSimdDirective &S) {
3172   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3173     emitOMPSimdRegion(CGF, S, Action);
3174   };
3175   emitCommonOMPTargetDirective(*this, S, CodeGen);
3176 }
3177 
3178 namespace {
3179 struct ScheduleKindModifiersTy {
3180   OpenMPScheduleClauseKind Kind;
3181   OpenMPScheduleClauseModifier M1;
3182   OpenMPScheduleClauseModifier M2;
3183   ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
3184                           OpenMPScheduleClauseModifier M1,
3185                           OpenMPScheduleClauseModifier M2)
3186       : Kind(Kind), M1(M1), M2(M2) {}
3187 };
3188 } // namespace
3189 
3190 bool CodeGenFunction::EmitOMPWorksharingLoop(
3191     const OMPLoopDirective &S, Expr *EUB,
3192     const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3193     const CodeGenDispatchBoundsTy &CGDispatchBounds) {
3194   // Emit the loop iteration variable.
3195   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3196   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3197   EmitVarDecl(*IVDecl);
3198 
3199   // Emit the iterations count variable.
3200   // If it is not a variable, Sema decided to calculate iterations count on each
3201   // iteration (e.g., it is foldable into a constant).
3202   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3203     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3204     // Emit calculation of the iterations count.
3205     EmitIgnoredExpr(S.getCalcLastIteration());
3206   }
3207 
3208   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3209 
3210   bool HasLastprivateClause;
3211   // Check pre-condition.
3212   {
3213     OMPLoopScope PreInitScope(*this, S);
3214     // Skip the entire loop if we don't meet the precondition.
3215     // If the condition constant folds and can be elided, avoid emitting the
3216     // whole loop.
3217     bool CondConstant;
3218     llvm::BasicBlock *ContBlock = nullptr;
3219     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3220       if (!CondConstant)
3221         return false;
3222     } else {
3223       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3224       ContBlock = createBasicBlock("omp.precond.end");
3225       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3226                   getProfileCount(&S));
3227       EmitBlock(ThenBlock);
3228       incrementProfileCounter(&S);
3229     }
3230 
3231     RunCleanupsScope DoacrossCleanupScope(*this);
3232     bool Ordered = false;
3233     if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
3234       if (OrderedClause->getNumForLoops())
3235         RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
3236       else
3237         Ordered = true;
3238     }
3239 
3240     llvm::DenseSet<const Expr *> EmittedFinals;
3241     emitAlignedClause(*this, S);
3242     bool HasLinears = EmitOMPLinearClauseInit(S);
3243     // Emit helper vars inits.
3244 
3245     std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
3246     LValue LB = Bounds.first;
3247     LValue UB = Bounds.second;
3248     LValue ST =
3249         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3250     LValue IL =
3251         EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3252 
3253     // Emit 'then' code.
3254     {
3255       OMPPrivateScope LoopScope(*this);
3256       if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
3257         // Emit implicit barrier to synchronize threads and avoid data races on
3258         // initialization of firstprivate variables and post-update of
3259         // lastprivate variables.
3260         CGM.getOpenMPRuntime().emitBarrierCall(
3261             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3262             /*ForceSimpleCall=*/true);
3263       }
3264       EmitOMPPrivateClause(S, LoopScope);
3265       CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(
3266           *this, S, EmitLValue(S.getIterationVariable()));
3267       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3268       EmitOMPReductionClauseInit(S, LoopScope);
3269       EmitOMPPrivateLoopCounters(S, LoopScope);
3270       EmitOMPLinearClause(S, LoopScope);
3271       (void)LoopScope.Privatize();
3272       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3273         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
3274 
3275       // Detect the loop schedule kind and chunk.
3276       const Expr *ChunkExpr = nullptr;
3277       OpenMPScheduleTy ScheduleKind;
3278       if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
3279         ScheduleKind.Schedule = C->getScheduleKind();
3280         ScheduleKind.M1 = C->getFirstScheduleModifier();
3281         ScheduleKind.M2 = C->getSecondScheduleModifier();
3282         ChunkExpr = C->getChunkSize();
3283       } else {
3284         // Default behaviour for schedule clause.
3285         CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
3286             *this, S, ScheduleKind.Schedule, ChunkExpr);
3287       }
3288       bool HasChunkSizeOne = false;
3289       llvm::Value *Chunk = nullptr;
3290       if (ChunkExpr) {
3291         Chunk = EmitScalarExpr(ChunkExpr);
3292         Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(),
3293                                      S.getIterationVariable()->getType(),
3294                                      S.getBeginLoc());
3295         Expr::EvalResult Result;
3296         if (ChunkExpr->EvaluateAsInt(Result, getContext())) {
3297           llvm::APSInt EvaluatedChunk = Result.Val.getInt();
3298           HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1);
3299         }
3300       }
3301       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3302       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3303       // OpenMP 4.5, 2.7.1 Loop Construct, Description.
3304       // If the static schedule kind is specified or if the ordered clause is
3305       // specified, and if no monotonic modifier is specified, the effect will
3306       // be as if the monotonic modifier was specified.
3307       bool StaticChunkedOne =
3308           RT.isStaticChunked(ScheduleKind.Schedule,
3309                              /* Chunked */ Chunk != nullptr) &&
3310           HasChunkSizeOne &&
3311           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
3312       bool IsMonotonic =
3313           Ordered ||
3314           (ScheduleKind.Schedule == OMPC_SCHEDULE_static &&
3315            !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3316              ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) ||
3317           ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
3318           ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
3319       if ((RT.isStaticNonchunked(ScheduleKind.Schedule,
3320                                  /* Chunked */ Chunk != nullptr) ||
3321            StaticChunkedOne) &&
3322           !Ordered) {
3323         JumpDest LoopExit =
3324             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3325         emitCommonSimdLoop(
3326             *this, S,
3327             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3328               if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3329                 CGF.EmitOMPSimdInit(S);
3330               } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) {
3331                 if (C->getKind() == OMPC_ORDER_concurrent)
3332                   CGF.LoopStack.setParallel(/*Enable=*/true);
3333               }
3334             },
3335             [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk,
3336              &S, ScheduleKind, LoopExit,
3337              &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
3338               // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
3339               // When no chunk_size is specified, the iteration space is divided
3340               // into chunks that are approximately equal in size, and at most
3341               // one chunk is distributed to each thread. Note that the size of
3342               // the chunks is unspecified in this case.
3343               CGOpenMPRuntime::StaticRTInput StaticInit(
3344                   IVSize, IVSigned, Ordered, IL.getAddress(CGF),
3345                   LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF),
3346                   StaticChunkedOne ? Chunk : nullptr);
3347               CGF.CGM.getOpenMPRuntime().emitForStaticInit(
3348                   CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind,
3349                   StaticInit);
3350               // UB = min(UB, GlobalUB);
3351               if (!StaticChunkedOne)
3352                 CGF.EmitIgnoredExpr(S.getEnsureUpperBound());
3353               // IV = LB;
3354               CGF.EmitIgnoredExpr(S.getInit());
3355               // For unchunked static schedule generate:
3356               //
3357               // while (idx <= UB) {
3358               //   BODY;
3359               //   ++idx;
3360               // }
3361               //
3362               // For static schedule with chunk one:
3363               //
3364               // while (IV <= PrevUB) {
3365               //   BODY;
3366               //   IV += ST;
3367               // }
3368               CGF.EmitOMPInnerLoop(
3369                   S, LoopScope.requiresCleanups(),
3370                   StaticChunkedOne ? S.getCombinedParForInDistCond()
3371                                    : S.getCond(),
3372                   StaticChunkedOne ? S.getDistInc() : S.getInc(),
3373                   [&S, LoopExit](CodeGenFunction &CGF) {
3374                     emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit);
3375                   },
3376                   [](CodeGenFunction &) {});
3377             });
3378         EmitBlock(LoopExit.getBlock());
3379         // Tell the runtime we are done.
3380         auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3381           CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3382                                                          S.getDirectiveKind());
3383         };
3384         OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
3385       } else {
3386         // Emit the outer loop, which requests its work chunk [LB..UB] from
3387         // runtime and runs the inner loop to process it.
3388         const OMPLoopArguments LoopArguments(
3389             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3390             IL.getAddress(*this), Chunk, EUB);
3391         EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
3392                             LoopArguments, CGDispatchBounds);
3393       }
3394       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3395         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
3396           return CGF.Builder.CreateIsNotNull(
3397               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3398         });
3399       }
3400       EmitOMPReductionClauseFinal(
3401           S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
3402                  ? /*Parallel and Simd*/ OMPD_parallel_for_simd
3403                  : /*Parallel only*/ OMPD_parallel);
3404       // Emit post-update of the reduction variables if IsLastIter != 0.
3405       emitPostUpdateForReductionClause(
3406           *this, S, [IL, &S](CodeGenFunction &CGF) {
3407             return CGF.Builder.CreateIsNotNull(
3408                 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3409           });
3410       // Emit final copy of the lastprivate variables if IsLastIter != 0.
3411       if (HasLastprivateClause)
3412         EmitOMPLastprivateClauseFinal(
3413             S, isOpenMPSimdDirective(S.getDirectiveKind()),
3414             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
3415     }
3416     EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
3417       return CGF.Builder.CreateIsNotNull(
3418           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3419     });
3420     DoacrossCleanupScope.ForceCleanup();
3421     // We're now done with the loop, so jump to the continuation block.
3422     if (ContBlock) {
3423       EmitBranch(ContBlock);
3424       EmitBlock(ContBlock, /*IsFinished=*/true);
3425     }
3426   }
3427   return HasLastprivateClause;
3428 }
3429 
3430 /// The following two functions generate expressions for the loop lower
3431 /// and upper bounds in case of static and dynamic (dispatch) schedule
3432 /// of the associated 'for' or 'distribute' loop.
3433 static std::pair<LValue, LValue>
3434 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
3435   const auto &LS = cast<OMPLoopDirective>(S);
3436   LValue LB =
3437       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
3438   LValue UB =
3439       EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
3440   return {LB, UB};
3441 }
3442 
3443 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
3444 /// consider the lower and upper bound expressions generated by the
3445 /// worksharing loop support, but we use 0 and the iteration space size as
3446 /// constants
3447 static std::pair<llvm::Value *, llvm::Value *>
3448 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
3449                           Address LB, Address UB) {
3450   const auto &LS = cast<OMPLoopDirective>(S);
3451   const Expr *IVExpr = LS.getIterationVariable();
3452   const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
3453   llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
3454   llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
3455   return {LBVal, UBVal};
3456 }
3457 
3458 /// Emits internal temp array declarations for the directive with inscan
3459 /// reductions.
3460 /// The code is the following:
3461 /// \code
3462 /// size num_iters = <num_iters>;
3463 /// <type> buffer[num_iters];
3464 /// \endcode
3465 static void emitScanBasedDirectiveDecls(
3466     CodeGenFunction &CGF, const OMPLoopDirective &S,
3467     llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) {
3468   llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
3469       NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
3470   SmallVector<const Expr *, 4> Shareds;
3471   SmallVector<const Expr *, 4> Privates;
3472   SmallVector<const Expr *, 4> ReductionOps;
3473   SmallVector<const Expr *, 4> CopyArrayTemps;
3474   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3475     assert(C->getModifier() == OMPC_REDUCTION_inscan &&
3476            "Only inscan reductions are expected.");
3477     Shareds.append(C->varlist_begin(), C->varlist_end());
3478     Privates.append(C->privates().begin(), C->privates().end());
3479     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
3480     CopyArrayTemps.append(C->copy_array_temps().begin(),
3481                           C->copy_array_temps().end());
3482   }
3483   {
3484     // Emit buffers for each reduction variables.
3485     // ReductionCodeGen is required to emit correctly the code for array
3486     // reductions.
3487     ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps);
3488     unsigned Count = 0;
3489     auto *ITA = CopyArrayTemps.begin();
3490     for (const Expr *IRef : Privates) {
3491       const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
3492       // Emit variably modified arrays, used for arrays/array sections
3493       // reductions.
3494       if (PrivateVD->getType()->isVariablyModifiedType()) {
3495         RedCG.emitSharedOrigLValue(CGF, Count);
3496         RedCG.emitAggregateType(CGF, Count);
3497       }
3498       CodeGenFunction::OpaqueValueMapping DimMapping(
3499           CGF,
3500           cast<OpaqueValueExpr>(
3501               cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe())
3502                   ->getSizeExpr()),
3503           RValue::get(OMPScanNumIterations));
3504       // Emit temp buffer.
3505       CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl()));
3506       ++ITA;
3507       ++Count;
3508     }
3509   }
3510 }
3511 
3512 /// Emits the code for the directive with inscan reductions.
3513 /// The code is the following:
3514 /// \code
3515 /// #pragma omp ...
3516 /// for (i: 0..<num_iters>) {
3517 ///   <input phase>;
3518 ///   buffer[i] = red;
3519 /// }
3520 /// #pragma omp master // in parallel region
3521 /// for (int k = 0; k != ceil(log2(num_iters)); ++k)
3522 /// for (size cnt = last_iter; cnt >= pow(2, k); --k)
3523 ///   buffer[i] op= buffer[i-pow(2,k)];
3524 /// #pragma omp barrier // in parallel region
3525 /// #pragma omp ...
3526 /// for (0..<num_iters>) {
3527 ///   red = InclusiveScan ? buffer[i] : buffer[i-1];
3528 ///   <scan phase>;
3529 /// }
3530 /// \endcode
3531 static void emitScanBasedDirective(
3532     CodeGenFunction &CGF, const OMPLoopDirective &S,
3533     llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen,
3534     llvm::function_ref<void(CodeGenFunction &)> FirstGen,
3535     llvm::function_ref<void(CodeGenFunction &)> SecondGen) {
3536   llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast(
3537       NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false);
3538   SmallVector<const Expr *, 4> Privates;
3539   SmallVector<const Expr *, 4> ReductionOps;
3540   SmallVector<const Expr *, 4> LHSs;
3541   SmallVector<const Expr *, 4> RHSs;
3542   SmallVector<const Expr *, 4> CopyArrayElems;
3543   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3544     assert(C->getModifier() == OMPC_REDUCTION_inscan &&
3545            "Only inscan reductions are expected.");
3546     Privates.append(C->privates().begin(), C->privates().end());
3547     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
3548     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
3549     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
3550     CopyArrayElems.append(C->copy_array_elems().begin(),
3551                           C->copy_array_elems().end());
3552   }
3553   CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S);
3554   {
3555     // Emit loop with input phase:
3556     // #pragma omp ...
3557     // for (i: 0..<num_iters>) {
3558     //   <input phase>;
3559     //   buffer[i] = red;
3560     // }
3561     CGF.OMPFirstScanLoop = true;
3562     CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
3563     FirstGen(CGF);
3564   }
3565   // #pragma omp barrier // in parallel region
3566   auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems,
3567                     &ReductionOps,
3568                     &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) {
3569     Action.Enter(CGF);
3570     // Emit prefix reduction:
3571     // #pragma omp master // in parallel region
3572     // for (int k = 0; k <= ceil(log2(n)); ++k)
3573     llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock();
3574     llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body");
3575     llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit");
3576     llvm::Function *F =
3577         CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy);
3578     llvm::Value *Arg =
3579         CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy);
3580     llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg);
3581     F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy);
3582     LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal);
3583     LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy);
3584     llvm::Value *NMin1 = CGF.Builder.CreateNUWSub(
3585         OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1));
3586     auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc());
3587     CGF.EmitBlock(LoopBB);
3588     auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2);
3589     // size pow2k = 1;
3590     auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
3591     Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB);
3592     Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB);
3593     // for (size i = n - 1; i >= 2 ^ k; --i)
3594     //   tmp[i] op= tmp[i-pow2k];
3595     llvm::BasicBlock *InnerLoopBB =
3596         CGF.createBasicBlock("omp.inner.log.scan.body");
3597     llvm::BasicBlock *InnerExitBB =
3598         CGF.createBasicBlock("omp.inner.log.scan.exit");
3599     llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K);
3600     CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
3601     CGF.EmitBlock(InnerLoopBB);
3602     auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2);
3603     IVal->addIncoming(NMin1, LoopBB);
3604     {
3605       CodeGenFunction::OMPPrivateScope PrivScope(CGF);
3606       auto *ILHS = LHSs.begin();
3607       auto *IRHS = RHSs.begin();
3608       for (const Expr *CopyArrayElem : CopyArrayElems) {
3609         const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3610         const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
3611         Address LHSAddr = Address::invalid();
3612         {
3613           CodeGenFunction::OpaqueValueMapping IdxMapping(
3614               CGF,
3615               cast<OpaqueValueExpr>(
3616                   cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
3617               RValue::get(IVal));
3618           LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF);
3619         }
3620         PrivScope.addPrivate(LHSVD, [LHSAddr]() { return LHSAddr; });
3621         Address RHSAddr = Address::invalid();
3622         {
3623           llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K);
3624           CodeGenFunction::OpaqueValueMapping IdxMapping(
3625               CGF,
3626               cast<OpaqueValueExpr>(
3627                   cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
3628               RValue::get(OffsetIVal));
3629           RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF);
3630         }
3631         PrivScope.addPrivate(RHSVD, [RHSAddr]() { return RHSAddr; });
3632         ++ILHS;
3633         ++IRHS;
3634       }
3635       PrivScope.Privatize();
3636       CGF.CGM.getOpenMPRuntime().emitReduction(
3637           CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
3638           {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown});
3639     }
3640     llvm::Value *NextIVal =
3641         CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1));
3642     IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock());
3643     CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K);
3644     CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB);
3645     CGF.EmitBlock(InnerExitBB);
3646     llvm::Value *Next =
3647         CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1));
3648     Counter->addIncoming(Next, CGF.Builder.GetInsertBlock());
3649     // pow2k <<= 1;
3650     llvm::Value *NextPow2K =
3651         CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true);
3652     Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock());
3653     llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal);
3654     CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB);
3655     auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc());
3656     CGF.EmitBlock(ExitBB);
3657   };
3658   if (isOpenMPParallelDirective(S.getDirectiveKind())) {
3659     CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3660     CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3661         CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3662         /*ForceSimpleCall=*/true);
3663   } else {
3664     RegionCodeGenTy RCG(CodeGen);
3665     RCG(CGF);
3666   }
3667 
3668   CGF.OMPFirstScanLoop = false;
3669   SecondGen(CGF);
3670 }
3671 
3672 static bool emitWorksharingDirective(CodeGenFunction &CGF,
3673                                      const OMPLoopDirective &S,
3674                                      bool HasCancel) {
3675   bool HasLastprivates;
3676   if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
3677                    [](const OMPReductionClause *C) {
3678                      return C->getModifier() == OMPC_REDUCTION_inscan;
3679                    })) {
3680     const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
3681       CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
3682       OMPLoopScope LoopScope(CGF, S);
3683       return CGF.EmitScalarExpr(S.getNumIterations());
3684     };
3685     const auto &&FirstGen = [&S, HasCancel](CodeGenFunction &CGF) {
3686       CodeGenFunction::OMPCancelStackRAII CancelRegion(
3687           CGF, S.getDirectiveKind(), HasCancel);
3688       (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3689                                        emitForLoopBounds,
3690                                        emitDispatchForLoopBounds);
3691       // Emit an implicit barrier at the end.
3692       CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(),
3693                                                  OMPD_for);
3694     };
3695     const auto &&SecondGen = [&S, HasCancel,
3696                               &HasLastprivates](CodeGenFunction &CGF) {
3697       CodeGenFunction::OMPCancelStackRAII CancelRegion(
3698           CGF, S.getDirectiveKind(), HasCancel);
3699       HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3700                                                    emitForLoopBounds,
3701                                                    emitDispatchForLoopBounds);
3702     };
3703     if (!isOpenMPParallelDirective(S.getDirectiveKind()))
3704       emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen);
3705     emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen);
3706   } else {
3707     CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
3708                                                      HasCancel);
3709     HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
3710                                                  emitForLoopBounds,
3711                                                  emitDispatchForLoopBounds);
3712   }
3713   return HasLastprivates;
3714 }
3715 
3716 static bool isSupportedByOpenMPIRBuilder(const OMPForDirective &S) {
3717   if (S.hasCancel())
3718     return false;
3719   for (OMPClause *C : S.clauses())
3720     if (!isa<OMPNowaitClause>(C))
3721       return false;
3722 
3723   return true;
3724 }
3725 
3726 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
3727   bool HasLastprivates = false;
3728   bool UseOMPIRBuilder =
3729       CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S);
3730   auto &&CodeGen = [this, &S, &HasLastprivates,
3731                     UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) {
3732     // Use the OpenMPIRBuilder if enabled.
3733     if (UseOMPIRBuilder) {
3734       // Emit the associated statement and get its loop representation.
3735       const Stmt *Inner = S.getRawStmt();
3736       llvm::CanonicalLoopInfo *CLI =
3737           EmitOMPCollapsedCanonicalLoopNest(Inner, 1);
3738 
3739       bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>();
3740       llvm::OpenMPIRBuilder &OMPBuilder =
3741           CGM.getOpenMPRuntime().getOMPBuilder();
3742       llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
3743           AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
3744       OMPBuilder.applyWorkshareLoop(Builder.getCurrentDebugLocation(), CLI,
3745                                     AllocaIP, NeedsBarrier);
3746       return;
3747     }
3748 
3749     HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel());
3750   };
3751   {
3752     auto LPCRegion =
3753         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3754     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3755     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
3756                                                 S.hasCancel());
3757   }
3758 
3759   if (!UseOMPIRBuilder) {
3760     // Emit an implicit barrier at the end.
3761     if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
3762       CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
3763   }
3764   // Check for outer lastprivate conditional update.
3765   checkForLastprivateConditionalUpdate(*this, S);
3766 }
3767 
3768 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
3769   bool HasLastprivates = false;
3770   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
3771                                           PrePostActionTy &) {
3772     HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
3773   };
3774   {
3775     auto LPCRegion =
3776         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3777     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3778     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
3779   }
3780 
3781   // Emit an implicit barrier at the end.
3782   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
3783     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
3784   // Check for outer lastprivate conditional update.
3785   checkForLastprivateConditionalUpdate(*this, S);
3786 }
3787 
3788 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
3789                                 const Twine &Name,
3790                                 llvm::Value *Init = nullptr) {
3791   LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
3792   if (Init)
3793     CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
3794   return LVal;
3795 }
3796 
3797 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
3798   const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
3799   const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
3800   bool HasLastprivates = false;
3801   auto &&CodeGen = [&S, CapturedStmt, CS,
3802                     &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
3803     const ASTContext &C = CGF.getContext();
3804     QualType KmpInt32Ty =
3805         C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3806     // Emit helper vars inits.
3807     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
3808                                   CGF.Builder.getInt32(0));
3809     llvm::ConstantInt *GlobalUBVal = CS != nullptr
3810                                          ? CGF.Builder.getInt32(CS->size() - 1)
3811                                          : CGF.Builder.getInt32(0);
3812     LValue UB =
3813         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
3814     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
3815                                   CGF.Builder.getInt32(1));
3816     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
3817                                   CGF.Builder.getInt32(0));
3818     // Loop counter.
3819     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
3820     OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
3821     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
3822     OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
3823     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
3824     // Generate condition for loop.
3825     BinaryOperator *Cond = BinaryOperator::Create(
3826         C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary,
3827         S.getBeginLoc(), FPOptionsOverride());
3828     // Increment for loop counter.
3829     UnaryOperator *Inc = UnaryOperator::Create(
3830         C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary,
3831         S.getBeginLoc(), true, FPOptionsOverride());
3832     auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
3833       // Iterate through all sections and emit a switch construct:
3834       // switch (IV) {
3835       //   case 0:
3836       //     <SectionStmt[0]>;
3837       //     break;
3838       // ...
3839       //   case <NumSection> - 1:
3840       //     <SectionStmt[<NumSection> - 1]>;
3841       //     break;
3842       // }
3843       // .omp.sections.exit:
3844       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
3845       llvm::SwitchInst *SwitchStmt =
3846           CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
3847                                    ExitBB, CS == nullptr ? 1 : CS->size());
3848       if (CS) {
3849         unsigned CaseNumber = 0;
3850         for (const Stmt *SubStmt : CS->children()) {
3851           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
3852           CGF.EmitBlock(CaseBB);
3853           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
3854           CGF.EmitStmt(SubStmt);
3855           CGF.EmitBranch(ExitBB);
3856           ++CaseNumber;
3857         }
3858       } else {
3859         llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
3860         CGF.EmitBlock(CaseBB);
3861         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
3862         CGF.EmitStmt(CapturedStmt);
3863         CGF.EmitBranch(ExitBB);
3864       }
3865       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
3866     };
3867 
3868     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
3869     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
3870       // Emit implicit barrier to synchronize threads and avoid data races on
3871       // initialization of firstprivate variables and post-update of lastprivate
3872       // variables.
3873       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3874           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3875           /*ForceSimpleCall=*/true);
3876     }
3877     CGF.EmitOMPPrivateClause(S, LoopScope);
3878     CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
3879     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
3880     CGF.EmitOMPReductionClauseInit(S, LoopScope);
3881     (void)LoopScope.Privatize();
3882     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3883       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
3884 
3885     // Emit static non-chunked loop.
3886     OpenMPScheduleTy ScheduleKind;
3887     ScheduleKind.Schedule = OMPC_SCHEDULE_static;
3888     CGOpenMPRuntime::StaticRTInput StaticInit(
3889         /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
3890         LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
3891     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
3892         CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
3893     // UB = min(UB, GlobalUB);
3894     llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
3895     llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
3896         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
3897     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
3898     // IV = LB;
3899     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
3900     // while (idx <= UB) { BODY; ++idx; }
3901     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen,
3902                          [](CodeGenFunction &) {});
3903     // Tell the runtime we are done.
3904     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3905       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3906                                                      S.getDirectiveKind());
3907     };
3908     CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
3909     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3910     // Emit post-update of the reduction variables if IsLastIter != 0.
3911     emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
3912       return CGF.Builder.CreateIsNotNull(
3913           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3914     });
3915 
3916     // Emit final copy of the lastprivate variables if IsLastIter != 0.
3917     if (HasLastprivates)
3918       CGF.EmitOMPLastprivateClauseFinal(
3919           S, /*NoFinals=*/false,
3920           CGF.Builder.CreateIsNotNull(
3921               CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
3922   };
3923 
3924   bool HasCancel = false;
3925   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
3926     HasCancel = OSD->hasCancel();
3927   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
3928     HasCancel = OPSD->hasCancel();
3929   OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
3930   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
3931                                               HasCancel);
3932   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
3933   // clause. Otherwise the barrier will be generated by the codegen for the
3934   // directive.
3935   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
3936     // Emit implicit barrier to synchronize threads and avoid data races on
3937     // initialization of firstprivate variables.
3938     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3939                                            OMPD_unknown);
3940   }
3941 }
3942 
3943 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
3944   if (CGM.getLangOpts().OpenMPIRBuilder) {
3945     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
3946     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3947     using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
3948 
3949     auto FiniCB = [this](InsertPointTy IP) {
3950       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3951     };
3952 
3953     const CapturedStmt *ICS = S.getInnermostCapturedStmt();
3954     const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
3955     const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
3956     llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
3957     if (CS) {
3958       for (const Stmt *SubStmt : CS->children()) {
3959         auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
3960                                          InsertPointTy CodeGenIP,
3961                                          llvm::BasicBlock &FiniBB) {
3962           OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
3963                                                          FiniBB);
3964           OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP,
3965                                                  FiniBB);
3966         };
3967         SectionCBVector.push_back(SectionCB);
3968       }
3969     } else {
3970       auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
3971                                             InsertPointTy CodeGenIP,
3972                                             llvm::BasicBlock &FiniBB) {
3973         OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3974         OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP,
3975                                                FiniBB);
3976       };
3977       SectionCBVector.push_back(SectionCB);
3978     }
3979 
3980     // Privatization callback that performs appropriate action for
3981     // shared/private/firstprivate/lastprivate/copyin/... variables.
3982     //
3983     // TODO: This defaults to shared right now.
3984     auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
3985                      llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
3986       // The next line is appropriate only for variables (Val) with the
3987       // data-sharing attribute "shared".
3988       ReplVal = &Val;
3989 
3990       return CodeGenIP;
3991     };
3992 
3993     CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
3994     CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
3995     llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
3996         AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
3997     Builder.restoreIP(OMPBuilder.createSections(
3998         Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(),
3999         S.getSingleClause<OMPNowaitClause>()));
4000     return;
4001   }
4002   {
4003     auto LPCRegion =
4004         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4005     OMPLexicalScope Scope(*this, S, OMPD_unknown);
4006     EmitSections(S);
4007   }
4008   // Emit an implicit barrier at the end.
4009   if (!S.getSingleClause<OMPNowaitClause>()) {
4010     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
4011                                            OMPD_sections);
4012   }
4013   // Check for outer lastprivate conditional update.
4014   checkForLastprivateConditionalUpdate(*this, S);
4015 }
4016 
4017 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
4018   if (CGM.getLangOpts().OpenMPIRBuilder) {
4019     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4020     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4021 
4022     const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt();
4023     auto FiniCB = [this](InsertPointTy IP) {
4024       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4025     };
4026 
4027     auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP,
4028                                                    InsertPointTy CodeGenIP,
4029                                                    llvm::BasicBlock &FiniBB) {
4030       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4031       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SectionRegionBodyStmt,
4032                                              CodeGenIP, FiniBB);
4033     };
4034 
4035     LexicalScope Scope(*this, S.getSourceRange());
4036     EmitStopPoint(&S);
4037     Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB));
4038 
4039     return;
4040   }
4041   LexicalScope Scope(*this, S.getSourceRange());
4042   EmitStopPoint(&S);
4043   EmitStmt(S.getAssociatedStmt());
4044 }
4045 
4046 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
4047   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
4048   llvm::SmallVector<const Expr *, 8> DestExprs;
4049   llvm::SmallVector<const Expr *, 8> SrcExprs;
4050   llvm::SmallVector<const Expr *, 8> AssignmentOps;
4051   // Check if there are any 'copyprivate' clauses associated with this
4052   // 'single' construct.
4053   // Build a list of copyprivate variables along with helper expressions
4054   // (<source>, <destination>, <destination>=<source> expressions)
4055   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
4056     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
4057     DestExprs.append(C->destination_exprs().begin(),
4058                      C->destination_exprs().end());
4059     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
4060     AssignmentOps.append(C->assignment_ops().begin(),
4061                          C->assignment_ops().end());
4062   }
4063   // Emit code for 'single' region along with 'copyprivate' clauses
4064   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4065     Action.Enter(CGF);
4066     OMPPrivateScope SingleScope(CGF);
4067     (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
4068     CGF.EmitOMPPrivateClause(S, SingleScope);
4069     (void)SingleScope.Privatize();
4070     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4071   };
4072   {
4073     auto LPCRegion =
4074         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4075     OMPLexicalScope Scope(*this, S, OMPD_unknown);
4076     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
4077                                             CopyprivateVars, DestExprs,
4078                                             SrcExprs, AssignmentOps);
4079   }
4080   // Emit an implicit barrier at the end (to avoid data race on firstprivate
4081   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
4082   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
4083     CGM.getOpenMPRuntime().emitBarrierCall(
4084         *this, S.getBeginLoc(),
4085         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
4086   }
4087   // Check for outer lastprivate conditional update.
4088   checkForLastprivateConditionalUpdate(*this, S);
4089 }
4090 
4091 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
4092   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4093     Action.Enter(CGF);
4094     CGF.EmitStmt(S.getRawStmt());
4095   };
4096   CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
4097 }
4098 
4099 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
4100   if (CGM.getLangOpts().OpenMPIRBuilder) {
4101     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4102     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4103 
4104     const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt();
4105 
4106     auto FiniCB = [this](InsertPointTy IP) {
4107       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4108     };
4109 
4110     auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP,
4111                                                   InsertPointTy CodeGenIP,
4112                                                   llvm::BasicBlock &FiniBB) {
4113       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4114       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt,
4115                                              CodeGenIP, FiniBB);
4116     };
4117 
4118     LexicalScope Scope(*this, S.getSourceRange());
4119     EmitStopPoint(&S);
4120     Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
4121 
4122     return;
4123   }
4124   LexicalScope Scope(*this, S.getSourceRange());
4125   EmitStopPoint(&S);
4126   emitMaster(*this, S);
4127 }
4128 
4129 static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
4130   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4131     Action.Enter(CGF);
4132     CGF.EmitStmt(S.getRawStmt());
4133   };
4134   Expr *Filter = nullptr;
4135   if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4136     Filter = FilterClause->getThreadID();
4137   CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(),
4138                                               Filter);
4139 }
4140 
4141 void CodeGenFunction::EmitOMPMaskedDirective(const OMPMaskedDirective &S) {
4142   if (CGM.getLangOpts().OpenMPIRBuilder) {
4143     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4144     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4145 
4146     const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt();
4147     const Expr *Filter = nullptr;
4148     if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4149       Filter = FilterClause->getThreadID();
4150     llvm::Value *FilterVal = Filter
4151                                  ? EmitScalarExpr(Filter, CGM.Int32Ty)
4152                                  : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
4153 
4154     auto FiniCB = [this](InsertPointTy IP) {
4155       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4156     };
4157 
4158     auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP,
4159                                                   InsertPointTy CodeGenIP,
4160                                                   llvm::BasicBlock &FiniBB) {
4161       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4162       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MaskedRegionBodyStmt,
4163                                              CodeGenIP, FiniBB);
4164     };
4165 
4166     LexicalScope Scope(*this, S.getSourceRange());
4167     EmitStopPoint(&S);
4168     Builder.restoreIP(
4169         OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal));
4170 
4171     return;
4172   }
4173   LexicalScope Scope(*this, S.getSourceRange());
4174   EmitStopPoint(&S);
4175   emitMasked(*this, S);
4176 }
4177 
4178 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
4179   if (CGM.getLangOpts().OpenMPIRBuilder) {
4180     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4181     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4182 
4183     const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt();
4184     const Expr *Hint = nullptr;
4185     if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4186       Hint = HintClause->getHint();
4187 
4188     // TODO: This is slightly different from what's currently being done in
4189     // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
4190     // about typing is final.
4191     llvm::Value *HintInst = nullptr;
4192     if (Hint)
4193       HintInst =
4194           Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
4195 
4196     auto FiniCB = [this](InsertPointTy IP) {
4197       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4198     };
4199 
4200     auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP,
4201                                                     InsertPointTy CodeGenIP,
4202                                                     llvm::BasicBlock &FiniBB) {
4203       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4204       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt,
4205                                              CodeGenIP, FiniBB);
4206     };
4207 
4208     LexicalScope Scope(*this, S.getSourceRange());
4209     EmitStopPoint(&S);
4210     Builder.restoreIP(OMPBuilder.createCritical(
4211         Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(),
4212         HintInst));
4213 
4214     return;
4215   }
4216 
4217   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4218     Action.Enter(CGF);
4219     CGF.EmitStmt(S.getAssociatedStmt());
4220   };
4221   const Expr *Hint = nullptr;
4222   if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4223     Hint = HintClause->getHint();
4224   LexicalScope Scope(*this, S.getSourceRange());
4225   EmitStopPoint(&S);
4226   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
4227                                             S.getDirectiveName().getAsString(),
4228                                             CodeGen, S.getBeginLoc(), Hint);
4229 }
4230 
4231 void CodeGenFunction::EmitOMPParallelForDirective(
4232     const OMPParallelForDirective &S) {
4233   // Emit directive as a combined directive that consists of two implicit
4234   // directives: 'parallel' with 'for' directive.
4235   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4236     Action.Enter(CGF);
4237     (void)emitWorksharingDirective(CGF, S, S.hasCancel());
4238   };
4239   {
4240     if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4241                      [](const OMPReductionClause *C) {
4242                        return C->getModifier() == OMPC_REDUCTION_inscan;
4243                      })) {
4244       const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4245         CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4246         CGCapturedStmtInfo CGSI(CR_OpenMP);
4247         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4248         OMPLoopScope LoopScope(CGF, S);
4249         return CGF.EmitScalarExpr(S.getNumIterations());
4250       };
4251       emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4252     }
4253     auto LPCRegion =
4254         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4255     emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
4256                                    emitEmptyBoundParameters);
4257   }
4258   // Check for outer lastprivate conditional update.
4259   checkForLastprivateConditionalUpdate(*this, S);
4260 }
4261 
4262 void CodeGenFunction::EmitOMPParallelForSimdDirective(
4263     const OMPParallelForSimdDirective &S) {
4264   // Emit directive as a combined directive that consists of two implicit
4265   // directives: 'parallel' with 'for' directive.
4266   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4267     Action.Enter(CGF);
4268     (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
4269   };
4270   {
4271     if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4272                      [](const OMPReductionClause *C) {
4273                        return C->getModifier() == OMPC_REDUCTION_inscan;
4274                      })) {
4275       const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4276         CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4277         CGCapturedStmtInfo CGSI(CR_OpenMP);
4278         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4279         OMPLoopScope LoopScope(CGF, S);
4280         return CGF.EmitScalarExpr(S.getNumIterations());
4281       };
4282       emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4283     }
4284     auto LPCRegion =
4285         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4286     emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen,
4287                                    emitEmptyBoundParameters);
4288   }
4289   // Check for outer lastprivate conditional update.
4290   checkForLastprivateConditionalUpdate(*this, S);
4291 }
4292 
4293 void CodeGenFunction::EmitOMPParallelMasterDirective(
4294     const OMPParallelMasterDirective &S) {
4295   // Emit directive as a combined directive that consists of two implicit
4296   // directives: 'parallel' with 'master' directive.
4297   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4298     Action.Enter(CGF);
4299     OMPPrivateScope PrivateScope(CGF);
4300     bool Copyins = CGF.EmitOMPCopyinClause(S);
4301     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4302     if (Copyins) {
4303       // Emit implicit barrier to synchronize threads and avoid data races on
4304       // propagation master's thread values of threadprivate variables to local
4305       // instances of that variables of all other implicit threads.
4306       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
4307           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
4308           /*ForceSimpleCall=*/true);
4309     }
4310     CGF.EmitOMPPrivateClause(S, PrivateScope);
4311     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4312     (void)PrivateScope.Privatize();
4313     emitMaster(CGF, S);
4314     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4315   };
4316   {
4317     auto LPCRegion =
4318         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4319     emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
4320                                    emitEmptyBoundParameters);
4321     emitPostUpdateForReductionClause(*this, S,
4322                                      [](CodeGenFunction &) { return nullptr; });
4323   }
4324   // Check for outer lastprivate conditional update.
4325   checkForLastprivateConditionalUpdate(*this, S);
4326 }
4327 
4328 void CodeGenFunction::EmitOMPParallelSectionsDirective(
4329     const OMPParallelSectionsDirective &S) {
4330   // Emit directive as a combined directive that consists of two implicit
4331   // directives: 'parallel' with 'sections' directive.
4332   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4333     Action.Enter(CGF);
4334     CGF.EmitSections(S);
4335   };
4336   {
4337     auto LPCRegion =
4338         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4339     emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
4340                                    emitEmptyBoundParameters);
4341   }
4342   // Check for outer lastprivate conditional update.
4343   checkForLastprivateConditionalUpdate(*this, S);
4344 }
4345 
4346 namespace {
4347 /// Get the list of variables declared in the context of the untied tasks.
4348 class CheckVarsEscapingUntiedTaskDeclContext final
4349     : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> {
4350   llvm::SmallVector<const VarDecl *, 4> PrivateDecls;
4351 
4352 public:
4353   explicit CheckVarsEscapingUntiedTaskDeclContext() = default;
4354   virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default;
4355   void VisitDeclStmt(const DeclStmt *S) {
4356     if (!S)
4357       return;
4358     // Need to privatize only local vars, static locals can be processed as is.
4359     for (const Decl *D : S->decls()) {
4360       if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
4361         if (VD->hasLocalStorage())
4362           PrivateDecls.push_back(VD);
4363     }
4364   }
4365   void VisitOMPExecutableDirective(const OMPExecutableDirective *) {}
4366   void VisitCapturedStmt(const CapturedStmt *) {}
4367   void VisitLambdaExpr(const LambdaExpr *) {}
4368   void VisitBlockExpr(const BlockExpr *) {}
4369   void VisitStmt(const Stmt *S) {
4370     if (!S)
4371       return;
4372     for (const Stmt *Child : S->children())
4373       if (Child)
4374         Visit(Child);
4375   }
4376 
4377   /// Swaps list of vars with the provided one.
4378   ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; }
4379 };
4380 } // anonymous namespace
4381 
4382 void CodeGenFunction::EmitOMPTaskBasedDirective(
4383     const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
4384     const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
4385     OMPTaskDataTy &Data) {
4386   // Emit outlined function for task construct.
4387   const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
4388   auto I = CS->getCapturedDecl()->param_begin();
4389   auto PartId = std::next(I);
4390   auto TaskT = std::next(I, 4);
4391   // Check if the task is final
4392   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
4393     // If the condition constant folds and can be elided, try to avoid emitting
4394     // the condition and the dead arm of the if/else.
4395     const Expr *Cond = Clause->getCondition();
4396     bool CondConstant;
4397     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
4398       Data.Final.setInt(CondConstant);
4399     else
4400       Data.Final.setPointer(EvaluateExprAsBool(Cond));
4401   } else {
4402     // By default the task is not final.
4403     Data.Final.setInt(/*IntVal=*/false);
4404   }
4405   // Check if the task has 'priority' clause.
4406   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
4407     const Expr *Prio = Clause->getPriority();
4408     Data.Priority.setInt(/*IntVal=*/true);
4409     Data.Priority.setPointer(EmitScalarConversion(
4410         EmitScalarExpr(Prio), Prio->getType(),
4411         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4412         Prio->getExprLoc()));
4413   }
4414   // The first function argument for tasks is a thread id, the second one is a
4415   // part id (0 for tied tasks, >=0 for untied task).
4416   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
4417   // Get list of private variables.
4418   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
4419     auto IRef = C->varlist_begin();
4420     for (const Expr *IInit : C->private_copies()) {
4421       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4422       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4423         Data.PrivateVars.push_back(*IRef);
4424         Data.PrivateCopies.push_back(IInit);
4425       }
4426       ++IRef;
4427     }
4428   }
4429   EmittedAsPrivate.clear();
4430   // Get list of firstprivate variables.
4431   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
4432     auto IRef = C->varlist_begin();
4433     auto IElemInitRef = C->inits().begin();
4434     for (const Expr *IInit : C->private_copies()) {
4435       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4436       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4437         Data.FirstprivateVars.push_back(*IRef);
4438         Data.FirstprivateCopies.push_back(IInit);
4439         Data.FirstprivateInits.push_back(*IElemInitRef);
4440       }
4441       ++IRef;
4442       ++IElemInitRef;
4443     }
4444   }
4445   // Get list of lastprivate variables (for taskloops).
4446   llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
4447   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
4448     auto IRef = C->varlist_begin();
4449     auto ID = C->destination_exprs().begin();
4450     for (const Expr *IInit : C->private_copies()) {
4451       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4452       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4453         Data.LastprivateVars.push_back(*IRef);
4454         Data.LastprivateCopies.push_back(IInit);
4455       }
4456       LastprivateDstsOrigs.insert(
4457           std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
4458                          cast<DeclRefExpr>(*IRef)));
4459       ++IRef;
4460       ++ID;
4461     }
4462   }
4463   SmallVector<const Expr *, 4> LHSs;
4464   SmallVector<const Expr *, 4> RHSs;
4465   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4466     Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
4467     Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
4468     Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
4469     Data.ReductionOps.append(C->reduction_ops().begin(),
4470                              C->reduction_ops().end());
4471     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4472     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4473   }
4474   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
4475       *this, S.getBeginLoc(), LHSs, RHSs, Data);
4476   // Build list of dependences.
4477   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4478     OMPTaskDataTy::DependData &DD =
4479         Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4480     DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4481   }
4482   // Get list of local vars for untied tasks.
4483   if (!Data.Tied) {
4484     CheckVarsEscapingUntiedTaskDeclContext Checker;
4485     Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt());
4486     Data.PrivateLocals.append(Checker.getPrivateDecls().begin(),
4487                               Checker.getPrivateDecls().end());
4488   }
4489   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
4490                     CapturedRegion](CodeGenFunction &CGF,
4491                                     PrePostActionTy &Action) {
4492     llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
4493                     std::pair<Address, Address>>
4494         UntiedLocalVars;
4495     // Set proper addresses for generated private copies.
4496     OMPPrivateScope Scope(CGF);
4497     // Generate debug info for variables present in shared clause.
4498     if (auto *DI = CGF.getDebugInfo()) {
4499       llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields =
4500           CGF.CapturedStmtInfo->getCaptureFields();
4501       llvm::Value *ContextValue = CGF.CapturedStmtInfo->getContextValue();
4502       if (CaptureFields.size() && ContextValue) {
4503         unsigned CharWidth = CGF.getContext().getCharWidth();
4504         // The shared variables are packed together as members of structure.
4505         // So the address of each shared variable can be computed by adding
4506         // offset of it (within record) to the base address of record. For each
4507         // shared variable, debug intrinsic llvm.dbg.declare is generated with
4508         // appropriate expressions (DIExpression).
4509         // Ex:
4510         //  %12 = load %struct.anon*, %struct.anon** %__context.addr.i
4511         //  call void @llvm.dbg.declare(metadata %struct.anon* %12,
4512         //            metadata !svar1,
4513         //            metadata !DIExpression(DW_OP_deref))
4514         //  call void @llvm.dbg.declare(metadata %struct.anon* %12,
4515         //            metadata !svar2,
4516         //            metadata !DIExpression(DW_OP_plus_uconst, 8, DW_OP_deref))
4517         for (auto It = CaptureFields.begin(); It != CaptureFields.end(); ++It) {
4518           const VarDecl *SharedVar = It->first;
4519           RecordDecl *CaptureRecord = It->second->getParent();
4520           const ASTRecordLayout &Layout =
4521               CGF.getContext().getASTRecordLayout(CaptureRecord);
4522           unsigned Offset =
4523               Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth;
4524           if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
4525             (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue,
4526                                                 CGF.Builder, false);
4527           llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back();
4528           // Get the call dbg.declare instruction we just created and update
4529           // its DIExpression to add offset to base address.
4530           if (auto DDI = dyn_cast<llvm::DbgVariableIntrinsic>(&Last)) {
4531             SmallVector<uint64_t, 8> Ops;
4532             // Add offset to the base address if non zero.
4533             if (Offset) {
4534               Ops.push_back(llvm::dwarf::DW_OP_plus_uconst);
4535               Ops.push_back(Offset);
4536             }
4537             Ops.push_back(llvm::dwarf::DW_OP_deref);
4538             auto &Ctx = DDI->getContext();
4539             llvm::DIExpression *DIExpr = llvm::DIExpression::get(Ctx, Ops);
4540             Last.setOperand(2, llvm::MetadataAsValue::get(Ctx, DIExpr));
4541           }
4542         }
4543       }
4544     }
4545     llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs;
4546     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
4547         !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) {
4548       enum { PrivatesParam = 2, CopyFnParam = 3 };
4549       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
4550           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
4551       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
4552           CS->getCapturedDecl()->getParam(PrivatesParam)));
4553       // Map privates.
4554       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
4555       llvm::SmallVector<llvm::Value *, 16> CallArgs;
4556       llvm::SmallVector<llvm::Type *, 4> ParamTypes;
4557       CallArgs.push_back(PrivatesPtr);
4558       ParamTypes.push_back(PrivatesPtr->getType());
4559       for (const Expr *E : Data.PrivateVars) {
4560         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4561         Address PrivatePtr = CGF.CreateMemTemp(
4562             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
4563         PrivatePtrs.emplace_back(VD, PrivatePtr);
4564         CallArgs.push_back(PrivatePtr.getPointer());
4565         ParamTypes.push_back(PrivatePtr.getType());
4566       }
4567       for (const Expr *E : Data.FirstprivateVars) {
4568         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4569         Address PrivatePtr =
4570             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4571                               ".firstpriv.ptr.addr");
4572         PrivatePtrs.emplace_back(VD, PrivatePtr);
4573         FirstprivatePtrs.emplace_back(VD, PrivatePtr);
4574         CallArgs.push_back(PrivatePtr.getPointer());
4575         ParamTypes.push_back(PrivatePtr.getType());
4576       }
4577       for (const Expr *E : Data.LastprivateVars) {
4578         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4579         Address PrivatePtr =
4580             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4581                               ".lastpriv.ptr.addr");
4582         PrivatePtrs.emplace_back(VD, PrivatePtr);
4583         CallArgs.push_back(PrivatePtr.getPointer());
4584         ParamTypes.push_back(PrivatePtr.getType());
4585       }
4586       for (const VarDecl *VD : Data.PrivateLocals) {
4587         QualType Ty = VD->getType().getNonReferenceType();
4588         if (VD->getType()->isLValueReferenceType())
4589           Ty = CGF.getContext().getPointerType(Ty);
4590         if (isAllocatableDecl(VD))
4591           Ty = CGF.getContext().getPointerType(Ty);
4592         Address PrivatePtr = CGF.CreateMemTemp(
4593             CGF.getContext().getPointerType(Ty), ".local.ptr.addr");
4594         auto Result = UntiedLocalVars.insert(
4595             std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid())));
4596         // If key exists update in place.
4597         if (Result.second == false)
4598           *Result.first = std::make_pair(
4599               VD, std::make_pair(PrivatePtr, Address::invalid()));
4600         CallArgs.push_back(PrivatePtr.getPointer());
4601         ParamTypes.push_back(PrivatePtr.getType());
4602       }
4603       auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
4604                                                ParamTypes, /*isVarArg=*/false);
4605       CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4606           CopyFn, CopyFnTy->getPointerTo());
4607       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4608           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
4609       for (const auto &Pair : LastprivateDstsOrigs) {
4610         const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
4611         DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
4612                         /*RefersToEnclosingVariableOrCapture=*/
4613                         CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
4614                         Pair.second->getType(), VK_LValue,
4615                         Pair.second->getExprLoc());
4616         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
4617           return CGF.EmitLValue(&DRE).getAddress(CGF);
4618         });
4619       }
4620       for (const auto &Pair : PrivatePtrs) {
4621         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4622                             CGF.getContext().getDeclAlign(Pair.first));
4623         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
4624         if (auto *DI = CGF.getDebugInfo())
4625           if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo())
4626             (void)DI->EmitDeclareOfAutoVariable(
4627                 Pair.first, Pair.second.getPointer(), CGF.Builder,
4628                 /*UsePointerValue*/ true);
4629       }
4630       // Adjust mapping for internal locals by mapping actual memory instead of
4631       // a pointer to this memory.
4632       for (auto &Pair : UntiedLocalVars) {
4633         if (isAllocatableDecl(Pair.first)) {
4634           llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4635           Address Replacement(Ptr, CGF.getPointerAlign());
4636           Pair.second.first = Replacement;
4637           Ptr = CGF.Builder.CreateLoad(Replacement);
4638           Replacement = Address(Ptr, CGF.getContext().getDeclAlign(Pair.first));
4639           Pair.second.second = Replacement;
4640         } else {
4641           llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4642           Address Replacement(Ptr, CGF.getContext().getDeclAlign(Pair.first));
4643           Pair.second.first = Replacement;
4644         }
4645       }
4646     }
4647     if (Data.Reductions) {
4648       OMPPrivateScope FirstprivateScope(CGF);
4649       for (const auto &Pair : FirstprivatePtrs) {
4650         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4651                             CGF.getContext().getDeclAlign(Pair.first));
4652         FirstprivateScope.addPrivate(Pair.first,
4653                                      [Replacement]() { return Replacement; });
4654       }
4655       (void)FirstprivateScope.Privatize();
4656       OMPLexicalScope LexScope(CGF, S, CapturedRegion);
4657       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
4658                              Data.ReductionCopies, Data.ReductionOps);
4659       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
4660           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
4661       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
4662         RedCG.emitSharedOrigLValue(CGF, Cnt);
4663         RedCG.emitAggregateType(CGF, Cnt);
4664         // FIXME: This must removed once the runtime library is fixed.
4665         // Emit required threadprivate variables for
4666         // initializer/combiner/finalizer.
4667         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
4668                                                            RedCG, Cnt);
4669         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
4670             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
4671         Replacement =
4672             Address(CGF.EmitScalarConversion(
4673                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
4674                         CGF.getContext().getPointerType(
4675                             Data.ReductionCopies[Cnt]->getType()),
4676                         Data.ReductionCopies[Cnt]->getExprLoc()),
4677                     Replacement.getAlignment());
4678         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
4679         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
4680                          [Replacement]() { return Replacement; });
4681       }
4682     }
4683     // Privatize all private variables except for in_reduction items.
4684     (void)Scope.Privatize();
4685     SmallVector<const Expr *, 4> InRedVars;
4686     SmallVector<const Expr *, 4> InRedPrivs;
4687     SmallVector<const Expr *, 4> InRedOps;
4688     SmallVector<const Expr *, 4> TaskgroupDescriptors;
4689     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
4690       auto IPriv = C->privates().begin();
4691       auto IRed = C->reduction_ops().begin();
4692       auto ITD = C->taskgroup_descriptors().begin();
4693       for (const Expr *Ref : C->varlists()) {
4694         InRedVars.emplace_back(Ref);
4695         InRedPrivs.emplace_back(*IPriv);
4696         InRedOps.emplace_back(*IRed);
4697         TaskgroupDescriptors.emplace_back(*ITD);
4698         std::advance(IPriv, 1);
4699         std::advance(IRed, 1);
4700         std::advance(ITD, 1);
4701       }
4702     }
4703     // Privatize in_reduction items here, because taskgroup descriptors must be
4704     // privatized earlier.
4705     OMPPrivateScope InRedScope(CGF);
4706     if (!InRedVars.empty()) {
4707       ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
4708       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
4709         RedCG.emitSharedOrigLValue(CGF, Cnt);
4710         RedCG.emitAggregateType(CGF, Cnt);
4711         // The taskgroup descriptor variable is always implicit firstprivate and
4712         // privatized already during processing of the firstprivates.
4713         // FIXME: This must removed once the runtime library is fixed.
4714         // Emit required threadprivate variables for
4715         // initializer/combiner/finalizer.
4716         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
4717                                                            RedCG, Cnt);
4718         llvm::Value *ReductionsPtr;
4719         if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
4720           ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr),
4721                                                TRExpr->getExprLoc());
4722         } else {
4723           ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4724         }
4725         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
4726             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
4727         Replacement = Address(
4728             CGF.EmitScalarConversion(
4729                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
4730                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
4731                 InRedPrivs[Cnt]->getExprLoc()),
4732             Replacement.getAlignment());
4733         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
4734         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
4735                               [Replacement]() { return Replacement; });
4736       }
4737     }
4738     (void)InRedScope.Privatize();
4739 
4740     CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF,
4741                                                              UntiedLocalVars);
4742     Action.Enter(CGF);
4743     BodyGen(CGF);
4744   };
4745   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
4746       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
4747       Data.NumberOfParts);
4748   OMPLexicalScope Scope(*this, S, llvm::None,
4749                         !isOpenMPParallelDirective(S.getDirectiveKind()) &&
4750                             !isOpenMPSimdDirective(S.getDirectiveKind()));
4751   TaskGen(*this, OutlinedFn, Data);
4752 }
4753 
4754 static ImplicitParamDecl *
4755 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
4756                                   QualType Ty, CapturedDecl *CD,
4757                                   SourceLocation Loc) {
4758   auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
4759                                            ImplicitParamDecl::Other);
4760   auto *OrigRef = DeclRefExpr::Create(
4761       C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
4762       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
4763   auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
4764                                               ImplicitParamDecl::Other);
4765   auto *PrivateRef = DeclRefExpr::Create(
4766       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
4767       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
4768   QualType ElemType = C.getBaseElementType(Ty);
4769   auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
4770                                            ImplicitParamDecl::Other);
4771   auto *InitRef = DeclRefExpr::Create(
4772       C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
4773       /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
4774   PrivateVD->setInitStyle(VarDecl::CInit);
4775   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
4776                                               InitRef, /*BasePath=*/nullptr,
4777                                               VK_PRValue, FPOptionsOverride()));
4778   Data.FirstprivateVars.emplace_back(OrigRef);
4779   Data.FirstprivateCopies.emplace_back(PrivateRef);
4780   Data.FirstprivateInits.emplace_back(InitRef);
4781   return OrigVD;
4782 }
4783 
4784 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
4785     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
4786     OMPTargetDataInfo &InputInfo) {
4787   // Emit outlined function for task construct.
4788   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
4789   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4790   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4791   auto I = CS->getCapturedDecl()->param_begin();
4792   auto PartId = std::next(I);
4793   auto TaskT = std::next(I, 4);
4794   OMPTaskDataTy Data;
4795   // The task is not final.
4796   Data.Final.setInt(/*IntVal=*/false);
4797   // Get list of firstprivate variables.
4798   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
4799     auto IRef = C->varlist_begin();
4800     auto IElemInitRef = C->inits().begin();
4801     for (auto *IInit : C->private_copies()) {
4802       Data.FirstprivateVars.push_back(*IRef);
4803       Data.FirstprivateCopies.push_back(IInit);
4804       Data.FirstprivateInits.push_back(*IElemInitRef);
4805       ++IRef;
4806       ++IElemInitRef;
4807     }
4808   }
4809   OMPPrivateScope TargetScope(*this);
4810   VarDecl *BPVD = nullptr;
4811   VarDecl *PVD = nullptr;
4812   VarDecl *SVD = nullptr;
4813   VarDecl *MVD = nullptr;
4814   if (InputInfo.NumberOfTargetItems > 0) {
4815     auto *CD = CapturedDecl::Create(
4816         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
4817     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
4818     QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType(
4819         getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
4820         /*IndexTypeQuals=*/0);
4821     BPVD = createImplicitFirstprivateForType(
4822         getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4823     PVD = createImplicitFirstprivateForType(
4824         getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4825     QualType SizesType = getContext().getConstantArrayType(
4826         getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
4827         ArrSize, nullptr, ArrayType::Normal,
4828         /*IndexTypeQuals=*/0);
4829     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
4830                                             S.getBeginLoc());
4831     TargetScope.addPrivate(
4832         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
4833     TargetScope.addPrivate(PVD,
4834                            [&InputInfo]() { return InputInfo.PointersArray; });
4835     TargetScope.addPrivate(SVD,
4836                            [&InputInfo]() { return InputInfo.SizesArray; });
4837     // If there is no user-defined mapper, the mapper array will be nullptr. In
4838     // this case, we don't need to privatize it.
4839     if (!isa_and_nonnull<llvm::ConstantPointerNull>(
4840             InputInfo.MappersArray.getPointer())) {
4841       MVD = createImplicitFirstprivateForType(
4842           getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4843       TargetScope.addPrivate(MVD,
4844                              [&InputInfo]() { return InputInfo.MappersArray; });
4845     }
4846   }
4847   (void)TargetScope.Privatize();
4848   // Build list of dependences.
4849   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4850     OMPTaskDataTy::DependData &DD =
4851         Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4852     DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4853   }
4854   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD,
4855                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
4856     // Set proper addresses for generated private copies.
4857     OMPPrivateScope Scope(CGF);
4858     if (!Data.FirstprivateVars.empty()) {
4859       enum { PrivatesParam = 2, CopyFnParam = 3 };
4860       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
4861           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
4862       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
4863           CS->getCapturedDecl()->getParam(PrivatesParam)));
4864       // Map privates.
4865       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
4866       llvm::SmallVector<llvm::Value *, 16> CallArgs;
4867       llvm::SmallVector<llvm::Type *, 4> ParamTypes;
4868       CallArgs.push_back(PrivatesPtr);
4869       ParamTypes.push_back(PrivatesPtr->getType());
4870       for (const Expr *E : Data.FirstprivateVars) {
4871         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4872         Address PrivatePtr =
4873             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4874                               ".firstpriv.ptr.addr");
4875         PrivatePtrs.emplace_back(VD, PrivatePtr);
4876         CallArgs.push_back(PrivatePtr.getPointer());
4877         ParamTypes.push_back(PrivatePtr.getType());
4878       }
4879       auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
4880                                                ParamTypes, /*isVarArg=*/false);
4881       CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4882           CopyFn, CopyFnTy->getPointerTo());
4883       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4884           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
4885       for (const auto &Pair : PrivatePtrs) {
4886         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4887                             CGF.getContext().getDeclAlign(Pair.first));
4888         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
4889       }
4890     }
4891     // Privatize all private variables except for in_reduction items.
4892     (void)Scope.Privatize();
4893     if (InputInfo.NumberOfTargetItems > 0) {
4894       InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
4895           CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
4896       InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
4897           CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
4898       InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
4899           CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
4900       // If MVD is nullptr, the mapper array is not privatized
4901       if (MVD)
4902         InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
4903             CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
4904     }
4905 
4906     Action.Enter(CGF);
4907     OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
4908     BodyGen(CGF);
4909   };
4910   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
4911       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
4912       Data.NumberOfParts);
4913   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
4914   IntegerLiteral IfCond(getContext(), TrueOrFalse,
4915                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4916                         SourceLocation());
4917 
4918   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
4919                                       SharedsTy, CapturedStruct, &IfCond, Data);
4920 }
4921 
4922 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
4923   // Emit outlined function for task construct.
4924   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
4925   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4926   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4927   const Expr *IfCond = nullptr;
4928   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4929     if (C->getNameModifier() == OMPD_unknown ||
4930         C->getNameModifier() == OMPD_task) {
4931       IfCond = C->getCondition();
4932       break;
4933     }
4934   }
4935 
4936   OMPTaskDataTy Data;
4937   // Check if we should emit tied or untied task.
4938   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
4939   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
4940     CGF.EmitStmt(CS->getCapturedStmt());
4941   };
4942   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4943                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
4944                             const OMPTaskDataTy &Data) {
4945     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
4946                                             SharedsTy, CapturedStruct, IfCond,
4947                                             Data);
4948   };
4949   auto LPCRegion =
4950       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4951   EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
4952 }
4953 
4954 void CodeGenFunction::EmitOMPTaskyieldDirective(
4955     const OMPTaskyieldDirective &S) {
4956   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
4957 }
4958 
4959 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
4960   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
4961 }
4962 
4963 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
4964   OMPTaskDataTy Data;
4965   // Build list of dependences
4966   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4967     OMPTaskDataTy::DependData &DD =
4968         Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4969     DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4970   }
4971   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc(), Data);
4972 }
4973 
4974 void CodeGenFunction::EmitOMPTaskgroupDirective(
4975     const OMPTaskgroupDirective &S) {
4976   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4977     Action.Enter(CGF);
4978     if (const Expr *E = S.getReductionRef()) {
4979       SmallVector<const Expr *, 4> LHSs;
4980       SmallVector<const Expr *, 4> RHSs;
4981       OMPTaskDataTy Data;
4982       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
4983         Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
4984         Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
4985         Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
4986         Data.ReductionOps.append(C->reduction_ops().begin(),
4987                                  C->reduction_ops().end());
4988         LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4989         RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4990       }
4991       llvm::Value *ReductionDesc =
4992           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
4993                                                            LHSs, RHSs, Data);
4994       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4995       CGF.EmitVarDecl(*VD);
4996       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
4997                             /*Volatile=*/false, E->getType());
4998     }
4999     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5000   };
5001   OMPLexicalScope Scope(*this, S, OMPD_unknown);
5002   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
5003 }
5004 
5005 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
5006   llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
5007                                 ? llvm::AtomicOrdering::NotAtomic
5008                                 : llvm::AtomicOrdering::AcquireRelease;
5009   CGM.getOpenMPRuntime().emitFlush(
5010       *this,
5011       [&S]() -> ArrayRef<const Expr *> {
5012         if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
5013           return llvm::makeArrayRef(FlushClause->varlist_begin(),
5014                                     FlushClause->varlist_end());
5015         return llvm::None;
5016       }(),
5017       S.getBeginLoc(), AO);
5018 }
5019 
5020 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) {
5021   const auto *DO = S.getSingleClause<OMPDepobjClause>();
5022   LValue DOLVal = EmitLValue(DO->getDepobj());
5023   if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
5024     OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
5025                                            DC->getModifier());
5026     Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
5027     Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause(
5028         *this, Dependencies, DC->getBeginLoc());
5029     EmitStoreOfScalar(DepAddr.getPointer(), DOLVal);
5030     return;
5031   }
5032   if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) {
5033     CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc());
5034     return;
5035   }
5036   if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) {
5037     CGM.getOpenMPRuntime().emitUpdateClause(
5038         *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc());
5039     return;
5040   }
5041 }
5042 
5043 void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) {
5044   if (!OMPParentLoopDirectiveForScan)
5045     return;
5046   const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan;
5047   bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>();
5048   SmallVector<const Expr *, 4> Shareds;
5049   SmallVector<const Expr *, 4> Privates;
5050   SmallVector<const Expr *, 4> LHSs;
5051   SmallVector<const Expr *, 4> RHSs;
5052   SmallVector<const Expr *, 4> ReductionOps;
5053   SmallVector<const Expr *, 4> CopyOps;
5054   SmallVector<const Expr *, 4> CopyArrayTemps;
5055   SmallVector<const Expr *, 4> CopyArrayElems;
5056   for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) {
5057     if (C->getModifier() != OMPC_REDUCTION_inscan)
5058       continue;
5059     Shareds.append(C->varlist_begin(), C->varlist_end());
5060     Privates.append(C->privates().begin(), C->privates().end());
5061     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
5062     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
5063     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
5064     CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
5065     CopyArrayTemps.append(C->copy_array_temps().begin(),
5066                           C->copy_array_temps().end());
5067     CopyArrayElems.append(C->copy_array_elems().begin(),
5068                           C->copy_array_elems().end());
5069   }
5070   if (ParentDir.getDirectiveKind() == OMPD_simd ||
5071       (getLangOpts().OpenMPSimd &&
5072        isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) {
5073     // For simd directive and simd-based directives in simd only mode, use the
5074     // following codegen:
5075     // int x = 0;
5076     // #pragma omp simd reduction(inscan, +: x)
5077     // for (..) {
5078     //   <first part>
5079     //   #pragma omp scan inclusive(x)
5080     //   <second part>
5081     //  }
5082     // is transformed to:
5083     // int x = 0;
5084     // for (..) {
5085     //   int x_priv = 0;
5086     //   <first part>
5087     //   x = x_priv + x;
5088     //   x_priv = x;
5089     //   <second part>
5090     // }
5091     // and
5092     // int x = 0;
5093     // #pragma omp simd reduction(inscan, +: x)
5094     // for (..) {
5095     //   <first part>
5096     //   #pragma omp scan exclusive(x)
5097     //   <second part>
5098     // }
5099     // to
5100     // int x = 0;
5101     // for (..) {
5102     //   int x_priv = 0;
5103     //   <second part>
5104     //   int temp = x;
5105     //   x = x_priv + x;
5106     //   x_priv = temp;
5107     //   <first part>
5108     // }
5109     llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce");
5110     EmitBranch(IsInclusive
5111                    ? OMPScanReduce
5112                    : BreakContinueStack.back().ContinueBlock.getBlock());
5113     EmitBlock(OMPScanDispatch);
5114     {
5115       // New scope for correct construction/destruction of temp variables for
5116       // exclusive scan.
5117       LexicalScope Scope(*this, S.getSourceRange());
5118       EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock);
5119       EmitBlock(OMPScanReduce);
5120       if (!IsInclusive) {
5121         // Create temp var and copy LHS value to this temp value.
5122         // TMP = LHS;
5123         for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5124           const Expr *PrivateExpr = Privates[I];
5125           const Expr *TempExpr = CopyArrayTemps[I];
5126           EmitAutoVarDecl(
5127               *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl()));
5128           LValue DestLVal = EmitLValue(TempExpr);
5129           LValue SrcLVal = EmitLValue(LHSs[I]);
5130           EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5131                       SrcLVal.getAddress(*this),
5132                       cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5133                       cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5134                       CopyOps[I]);
5135         }
5136       }
5137       CGM.getOpenMPRuntime().emitReduction(
5138           *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
5139           {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd});
5140       for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5141         const Expr *PrivateExpr = Privates[I];
5142         LValue DestLVal;
5143         LValue SrcLVal;
5144         if (IsInclusive) {
5145           DestLVal = EmitLValue(RHSs[I]);
5146           SrcLVal = EmitLValue(LHSs[I]);
5147         } else {
5148           const Expr *TempExpr = CopyArrayTemps[I];
5149           DestLVal = EmitLValue(RHSs[I]);
5150           SrcLVal = EmitLValue(TempExpr);
5151         }
5152         EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5153                     SrcLVal.getAddress(*this),
5154                     cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5155                     cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5156                     CopyOps[I]);
5157       }
5158     }
5159     EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock);
5160     OMPScanExitBlock = IsInclusive
5161                            ? BreakContinueStack.back().ContinueBlock.getBlock()
5162                            : OMPScanReduce;
5163     EmitBlock(OMPAfterScanBlock);
5164     return;
5165   }
5166   if (!IsInclusive) {
5167     EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5168     EmitBlock(OMPScanExitBlock);
5169   }
5170   if (OMPFirstScanLoop) {
5171     // Emit buffer[i] = red; at the end of the input phase.
5172     const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
5173                              .getIterationVariable()
5174                              ->IgnoreParenImpCasts();
5175     LValue IdxLVal = EmitLValue(IVExpr);
5176     llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
5177     IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
5178     for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5179       const Expr *PrivateExpr = Privates[I];
5180       const Expr *OrigExpr = Shareds[I];
5181       const Expr *CopyArrayElem = CopyArrayElems[I];
5182       OpaqueValueMapping IdxMapping(
5183           *this,
5184           cast<OpaqueValueExpr>(
5185               cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5186           RValue::get(IdxVal));
5187       LValue DestLVal = EmitLValue(CopyArrayElem);
5188       LValue SrcLVal = EmitLValue(OrigExpr);
5189       EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5190                   SrcLVal.getAddress(*this),
5191                   cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5192                   cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5193                   CopyOps[I]);
5194     }
5195   }
5196   EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5197   if (IsInclusive) {
5198     EmitBlock(OMPScanExitBlock);
5199     EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5200   }
5201   EmitBlock(OMPScanDispatch);
5202   if (!OMPFirstScanLoop) {
5203     // Emit red = buffer[i]; at the entrance to the scan phase.
5204     const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
5205                              .getIterationVariable()
5206                              ->IgnoreParenImpCasts();
5207     LValue IdxLVal = EmitLValue(IVExpr);
5208     llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
5209     IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
5210     llvm::BasicBlock *ExclusiveExitBB = nullptr;
5211     if (!IsInclusive) {
5212       llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec");
5213       ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit");
5214       llvm::Value *Cmp = Builder.CreateIsNull(IdxVal);
5215       Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB);
5216       EmitBlock(ContBB);
5217       // Use idx - 1 iteration for exclusive scan.
5218       IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1));
5219     }
5220     for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5221       const Expr *PrivateExpr = Privates[I];
5222       const Expr *OrigExpr = Shareds[I];
5223       const Expr *CopyArrayElem = CopyArrayElems[I];
5224       OpaqueValueMapping IdxMapping(
5225           *this,
5226           cast<OpaqueValueExpr>(
5227               cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5228           RValue::get(IdxVal));
5229       LValue SrcLVal = EmitLValue(CopyArrayElem);
5230       LValue DestLVal = EmitLValue(OrigExpr);
5231       EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5232                   SrcLVal.getAddress(*this),
5233                   cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5234                   cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5235                   CopyOps[I]);
5236     }
5237     if (!IsInclusive) {
5238       EmitBlock(ExclusiveExitBB);
5239     }
5240   }
5241   EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock
5242                                                : OMPAfterScanBlock);
5243   EmitBlock(OMPAfterScanBlock);
5244 }
5245 
5246 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
5247                                             const CodeGenLoopTy &CodeGenLoop,
5248                                             Expr *IncExpr) {
5249   // Emit the loop iteration variable.
5250   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
5251   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
5252   EmitVarDecl(*IVDecl);
5253 
5254   // Emit the iterations count variable.
5255   // If it is not a variable, Sema decided to calculate iterations count on each
5256   // iteration (e.g., it is foldable into a constant).
5257   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5258     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5259     // Emit calculation of the iterations count.
5260     EmitIgnoredExpr(S.getCalcLastIteration());
5261   }
5262 
5263   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
5264 
5265   bool HasLastprivateClause = false;
5266   // Check pre-condition.
5267   {
5268     OMPLoopScope PreInitScope(*this, S);
5269     // Skip the entire loop if we don't meet the precondition.
5270     // If the condition constant folds and can be elided, avoid emitting the
5271     // whole loop.
5272     bool CondConstant;
5273     llvm::BasicBlock *ContBlock = nullptr;
5274     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5275       if (!CondConstant)
5276         return;
5277     } else {
5278       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
5279       ContBlock = createBasicBlock("omp.precond.end");
5280       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
5281                   getProfileCount(&S));
5282       EmitBlock(ThenBlock);
5283       incrementProfileCounter(&S);
5284     }
5285 
5286     emitAlignedClause(*this, S);
5287     // Emit 'then' code.
5288     {
5289       // Emit helper vars inits.
5290 
5291       LValue LB = EmitOMPHelperVar(
5292           *this, cast<DeclRefExpr>(
5293                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5294                           ? S.getCombinedLowerBoundVariable()
5295                           : S.getLowerBoundVariable())));
5296       LValue UB = EmitOMPHelperVar(
5297           *this, cast<DeclRefExpr>(
5298                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5299                           ? S.getCombinedUpperBoundVariable()
5300                           : S.getUpperBoundVariable())));
5301       LValue ST =
5302           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
5303       LValue IL =
5304           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
5305 
5306       OMPPrivateScope LoopScope(*this);
5307       if (EmitOMPFirstprivateClause(S, LoopScope)) {
5308         // Emit implicit barrier to synchronize threads and avoid data races
5309         // on initialization of firstprivate variables and post-update of
5310         // lastprivate variables.
5311         CGM.getOpenMPRuntime().emitBarrierCall(
5312             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
5313             /*ForceSimpleCall=*/true);
5314       }
5315       EmitOMPPrivateClause(S, LoopScope);
5316       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5317           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5318           !isOpenMPTeamsDirective(S.getDirectiveKind()))
5319         EmitOMPReductionClauseInit(S, LoopScope);
5320       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
5321       EmitOMPPrivateLoopCounters(S, LoopScope);
5322       (void)LoopScope.Privatize();
5323       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5324         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
5325 
5326       // Detect the distribute schedule kind and chunk.
5327       llvm::Value *Chunk = nullptr;
5328       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
5329       if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
5330         ScheduleKind = C->getDistScheduleKind();
5331         if (const Expr *Ch = C->getChunkSize()) {
5332           Chunk = EmitScalarExpr(Ch);
5333           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
5334                                        S.getIterationVariable()->getType(),
5335                                        S.getBeginLoc());
5336         }
5337       } else {
5338         // Default behaviour for dist_schedule clause.
5339         CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
5340             *this, S, ScheduleKind, Chunk);
5341       }
5342       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
5343       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
5344 
5345       // OpenMP [2.10.8, distribute Construct, Description]
5346       // If dist_schedule is specified, kind must be static. If specified,
5347       // iterations are divided into chunks of size chunk_size, chunks are
5348       // assigned to the teams of the league in a round-robin fashion in the
5349       // order of the team number. When no chunk_size is specified, the
5350       // iteration space is divided into chunks that are approximately equal
5351       // in size, and at most one chunk is distributed to each team of the
5352       // league. The size of the chunks is unspecified in this case.
5353       bool StaticChunked =
5354           RT.isStaticChunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
5355           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
5356       if (RT.isStaticNonchunked(ScheduleKind,
5357                                 /* Chunked */ Chunk != nullptr) ||
5358           StaticChunked) {
5359         CGOpenMPRuntime::StaticRTInput StaticInit(
5360             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
5361             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
5362             StaticChunked ? Chunk : nullptr);
5363         RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
5364                                     StaticInit);
5365         JumpDest LoopExit =
5366             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
5367         // UB = min(UB, GlobalUB);
5368         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5369                             ? S.getCombinedEnsureUpperBound()
5370                             : S.getEnsureUpperBound());
5371         // IV = LB;
5372         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5373                             ? S.getCombinedInit()
5374                             : S.getInit());
5375 
5376         const Expr *Cond =
5377             isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5378                 ? S.getCombinedCond()
5379                 : S.getCond();
5380 
5381         if (StaticChunked)
5382           Cond = S.getCombinedDistCond();
5383 
5384         // For static unchunked schedules generate:
5385         //
5386         //  1. For distribute alone, codegen
5387         //    while (idx <= UB) {
5388         //      BODY;
5389         //      ++idx;
5390         //    }
5391         //
5392         //  2. When combined with 'for' (e.g. as in 'distribute parallel for')
5393         //    while (idx <= UB) {
5394         //      <CodeGen rest of pragma>(LB, UB);
5395         //      idx += ST;
5396         //    }
5397         //
5398         // For static chunk one schedule generate:
5399         //
5400         // while (IV <= GlobalUB) {
5401         //   <CodeGen rest of pragma>(LB, UB);
5402         //   LB += ST;
5403         //   UB += ST;
5404         //   UB = min(UB, GlobalUB);
5405         //   IV = LB;
5406         // }
5407         //
5408         emitCommonSimdLoop(
5409             *this, S,
5410             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5411               if (isOpenMPSimdDirective(S.getDirectiveKind()))
5412                 CGF.EmitOMPSimdInit(S);
5413             },
5414             [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
5415              StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
5416               CGF.EmitOMPInnerLoop(
5417                   S, LoopScope.requiresCleanups(), Cond, IncExpr,
5418                   [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
5419                     CodeGenLoop(CGF, S, LoopExit);
5420                   },
5421                   [&S, StaticChunked](CodeGenFunction &CGF) {
5422                     if (StaticChunked) {
5423                       CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
5424                       CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
5425                       CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
5426                       CGF.EmitIgnoredExpr(S.getCombinedInit());
5427                     }
5428                   });
5429             });
5430         EmitBlock(LoopExit.getBlock());
5431         // Tell the runtime we are done.
5432         RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
5433       } else {
5434         // Emit the outer loop, which requests its work chunk [LB..UB] from
5435         // runtime and runs the inner loop to process it.
5436         const OMPLoopArguments LoopArguments = {
5437             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
5438             IL.getAddress(*this), Chunk};
5439         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
5440                                    CodeGenLoop);
5441       }
5442       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
5443         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
5444           return CGF.Builder.CreateIsNotNull(
5445               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5446         });
5447       }
5448       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5449           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5450           !isOpenMPTeamsDirective(S.getDirectiveKind())) {
5451         EmitOMPReductionClauseFinal(S, OMPD_simd);
5452         // Emit post-update of the reduction variables if IsLastIter != 0.
5453         emitPostUpdateForReductionClause(
5454             *this, S, [IL, &S](CodeGenFunction &CGF) {
5455               return CGF.Builder.CreateIsNotNull(
5456                   CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5457             });
5458       }
5459       // Emit final copy of the lastprivate variables if IsLastIter != 0.
5460       if (HasLastprivateClause) {
5461         EmitOMPLastprivateClauseFinal(
5462             S, /*NoFinals=*/false,
5463             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
5464       }
5465     }
5466 
5467     // We're now done with the loop, so jump to the continuation block.
5468     if (ContBlock) {
5469       EmitBranch(ContBlock);
5470       EmitBlock(ContBlock, true);
5471     }
5472   }
5473 }
5474 
5475 void CodeGenFunction::EmitOMPDistributeDirective(
5476     const OMPDistributeDirective &S) {
5477   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5478     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
5479   };
5480   OMPLexicalScope Scope(*this, S, OMPD_unknown);
5481   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
5482 }
5483 
5484 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
5485                                                    const CapturedStmt *S,
5486                                                    SourceLocation Loc) {
5487   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
5488   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
5489   CGF.CapturedStmtInfo = &CapStmtInfo;
5490   llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
5491   Fn->setDoesNotRecurse();
5492   return Fn;
5493 }
5494 
5495 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
5496   if (CGM.getLangOpts().OpenMPIRBuilder) {
5497     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
5498     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5499 
5500     if (S.hasClausesOfKind<OMPDependClause>()) {
5501       // The ordered directive with depend clause.
5502       assert(!S.hasAssociatedStmt() &&
5503              "No associated statement must be in ordered depend construct.");
5504       InsertPointTy AllocaIP(AllocaInsertPt->getParent(),
5505                              AllocaInsertPt->getIterator());
5506       for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) {
5507         unsigned NumLoops = DC->getNumLoops();
5508         QualType Int64Ty = CGM.getContext().getIntTypeForBitwidth(
5509             /*DestWidth=*/64, /*Signed=*/1);
5510         llvm::SmallVector<llvm::Value *> StoreValues;
5511         for (unsigned I = 0; I < NumLoops; I++) {
5512           const Expr *CounterVal = DC->getLoopData(I);
5513           assert(CounterVal);
5514           llvm::Value *StoreValue = EmitScalarConversion(
5515               EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
5516               CounterVal->getExprLoc());
5517           StoreValues.emplace_back(StoreValue);
5518         }
5519         bool IsDependSource = false;
5520         if (DC->getDependencyKind() == OMPC_DEPEND_source)
5521           IsDependSource = true;
5522         Builder.restoreIP(OMPBuilder.createOrderedDepend(
5523             Builder, AllocaIP, NumLoops, StoreValues, ".cnt.addr",
5524             IsDependSource));
5525       }
5526     } else {
5527       // The ordered directive with threads or simd clause, or without clause.
5528       // Without clause, it behaves as if the threads clause is specified.
5529       const auto *C = S.getSingleClause<OMPSIMDClause>();
5530 
5531       auto FiniCB = [this](InsertPointTy IP) {
5532         OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
5533       };
5534 
5535       auto BodyGenCB = [&S, C, this](InsertPointTy AllocaIP,
5536                                      InsertPointTy CodeGenIP,
5537                                      llvm::BasicBlock &FiniBB) {
5538         const CapturedStmt *CS = S.getInnermostCapturedStmt();
5539         if (C) {
5540           llvm::SmallVector<llvm::Value *, 16> CapturedVars;
5541           GenerateOpenMPCapturedVars(*CS, CapturedVars);
5542           llvm::Function *OutlinedFn =
5543               emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
5544           assert(S.getBeginLoc().isValid() &&
5545                  "Outlined function call location must be valid.");
5546           ApplyDebugLocation::CreateDefaultArtificial(*this, S.getBeginLoc());
5547           OMPBuilderCBHelpers::EmitCaptureStmt(*this, CodeGenIP, FiniBB,
5548                                                OutlinedFn, CapturedVars);
5549         } else {
5550           OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
5551                                                          FiniBB);
5552           OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CS->getCapturedStmt(),
5553                                                  CodeGenIP, FiniBB);
5554         }
5555       };
5556 
5557       OMPLexicalScope Scope(*this, S, OMPD_unknown);
5558       Builder.restoreIP(
5559           OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, !C));
5560     }
5561     return;
5562   }
5563 
5564   if (S.hasClausesOfKind<OMPDependClause>()) {
5565     assert(!S.hasAssociatedStmt() &&
5566            "No associated statement must be in ordered depend construct.");
5567     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
5568       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
5569     return;
5570   }
5571   const auto *C = S.getSingleClause<OMPSIMDClause>();
5572   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
5573                                  PrePostActionTy &Action) {
5574     const CapturedStmt *CS = S.getInnermostCapturedStmt();
5575     if (C) {
5576       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
5577       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
5578       llvm::Function *OutlinedFn =
5579           emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
5580       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
5581                                                       OutlinedFn, CapturedVars);
5582     } else {
5583       Action.Enter(CGF);
5584       CGF.EmitStmt(CS->getCapturedStmt());
5585     }
5586   };
5587   OMPLexicalScope Scope(*this, S, OMPD_unknown);
5588   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
5589 }
5590 
5591 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
5592                                          QualType SrcType, QualType DestType,
5593                                          SourceLocation Loc) {
5594   assert(CGF.hasScalarEvaluationKind(DestType) &&
5595          "DestType must have scalar evaluation kind.");
5596   assert(!Val.isAggregate() && "Must be a scalar or complex.");
5597   return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
5598                                                    DestType, Loc)
5599                         : CGF.EmitComplexToScalarConversion(
5600                               Val.getComplexVal(), SrcType, DestType, Loc);
5601 }
5602 
5603 static CodeGenFunction::ComplexPairTy
5604 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
5605                       QualType DestType, SourceLocation Loc) {
5606   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
5607          "DestType must have complex evaluation kind.");
5608   CodeGenFunction::ComplexPairTy ComplexVal;
5609   if (Val.isScalar()) {
5610     // Convert the input element to the element type of the complex.
5611     QualType DestElementType =
5612         DestType->castAs<ComplexType>()->getElementType();
5613     llvm::Value *ScalarVal = CGF.EmitScalarConversion(
5614         Val.getScalarVal(), SrcType, DestElementType, Loc);
5615     ComplexVal = CodeGenFunction::ComplexPairTy(
5616         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
5617   } else {
5618     assert(Val.isComplex() && "Must be a scalar or complex.");
5619     QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
5620     QualType DestElementType =
5621         DestType->castAs<ComplexType>()->getElementType();
5622     ComplexVal.first = CGF.EmitScalarConversion(
5623         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
5624     ComplexVal.second = CGF.EmitScalarConversion(
5625         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
5626   }
5627   return ComplexVal;
5628 }
5629 
5630 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
5631                                   LValue LVal, RValue RVal) {
5632   if (LVal.isGlobalReg())
5633     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
5634   else
5635     CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
5636 }
5637 
5638 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF,
5639                                    llvm::AtomicOrdering AO, LValue LVal,
5640                                    SourceLocation Loc) {
5641   if (LVal.isGlobalReg())
5642     return CGF.EmitLoadOfLValue(LVal, Loc);
5643   return CGF.EmitAtomicLoad(
5644       LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
5645       LVal.isVolatile());
5646 }
5647 
5648 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
5649                                          QualType RValTy, SourceLocation Loc) {
5650   switch (getEvaluationKind(LVal.getType())) {
5651   case TEK_Scalar:
5652     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
5653                                *this, RVal, RValTy, LVal.getType(), Loc)),
5654                            LVal);
5655     break;
5656   case TEK_Complex:
5657     EmitStoreOfComplex(
5658         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
5659         /*isInit=*/false);
5660     break;
5661   case TEK_Aggregate:
5662     llvm_unreachable("Must be a scalar or complex.");
5663   }
5664 }
5665 
5666 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
5667                                   const Expr *X, const Expr *V,
5668                                   SourceLocation Loc) {
5669   // v = x;
5670   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
5671   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
5672   LValue XLValue = CGF.EmitLValue(X);
5673   LValue VLValue = CGF.EmitLValue(V);
5674   RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
5675   // OpenMP, 2.17.7, atomic Construct
5676   // If the read or capture clause is specified and the acquire, acq_rel, or
5677   // seq_cst clause is specified then the strong flush on exit from the atomic
5678   // operation is also an acquire flush.
5679   switch (AO) {
5680   case llvm::AtomicOrdering::Acquire:
5681   case llvm::AtomicOrdering::AcquireRelease:
5682   case llvm::AtomicOrdering::SequentiallyConsistent:
5683     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5684                                          llvm::AtomicOrdering::Acquire);
5685     break;
5686   case llvm::AtomicOrdering::Monotonic:
5687   case llvm::AtomicOrdering::Release:
5688     break;
5689   case llvm::AtomicOrdering::NotAtomic:
5690   case llvm::AtomicOrdering::Unordered:
5691     llvm_unreachable("Unexpected ordering.");
5692   }
5693   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
5694   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
5695 }
5696 
5697 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF,
5698                                    llvm::AtomicOrdering AO, const Expr *X,
5699                                    const Expr *E, SourceLocation Loc) {
5700   // x = expr;
5701   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
5702   emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
5703   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5704   // OpenMP, 2.17.7, atomic Construct
5705   // If the write, update, or capture clause is specified and the release,
5706   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5707   // the atomic operation is also a release flush.
5708   switch (AO) {
5709   case llvm::AtomicOrdering::Release:
5710   case llvm::AtomicOrdering::AcquireRelease:
5711   case llvm::AtomicOrdering::SequentiallyConsistent:
5712     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5713                                          llvm::AtomicOrdering::Release);
5714     break;
5715   case llvm::AtomicOrdering::Acquire:
5716   case llvm::AtomicOrdering::Monotonic:
5717     break;
5718   case llvm::AtomicOrdering::NotAtomic:
5719   case llvm::AtomicOrdering::Unordered:
5720     llvm_unreachable("Unexpected ordering.");
5721   }
5722 }
5723 
5724 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
5725                                                 RValue Update,
5726                                                 BinaryOperatorKind BO,
5727                                                 llvm::AtomicOrdering AO,
5728                                                 bool IsXLHSInRHSPart) {
5729   ASTContext &Context = CGF.getContext();
5730   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
5731   // expression is simple and atomic is allowed for the given type for the
5732   // target platform.
5733   if (BO == BO_Comma || !Update.isScalar() ||
5734       !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
5735       (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
5736        (Update.getScalarVal()->getType() !=
5737         X.getAddress(CGF).getElementType())) ||
5738       !X.getAddress(CGF).getElementType()->isIntegerTy() ||
5739       !Context.getTargetInfo().hasBuiltinAtomic(
5740           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
5741     return std::make_pair(false, RValue::get(nullptr));
5742 
5743   llvm::AtomicRMWInst::BinOp RMWOp;
5744   switch (BO) {
5745   case BO_Add:
5746     RMWOp = llvm::AtomicRMWInst::Add;
5747     break;
5748   case BO_Sub:
5749     if (!IsXLHSInRHSPart)
5750       return std::make_pair(false, RValue::get(nullptr));
5751     RMWOp = llvm::AtomicRMWInst::Sub;
5752     break;
5753   case BO_And:
5754     RMWOp = llvm::AtomicRMWInst::And;
5755     break;
5756   case BO_Or:
5757     RMWOp = llvm::AtomicRMWInst::Or;
5758     break;
5759   case BO_Xor:
5760     RMWOp = llvm::AtomicRMWInst::Xor;
5761     break;
5762   case BO_LT:
5763     RMWOp = X.getType()->hasSignedIntegerRepresentation()
5764                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
5765                                    : llvm::AtomicRMWInst::Max)
5766                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
5767                                    : llvm::AtomicRMWInst::UMax);
5768     break;
5769   case BO_GT:
5770     RMWOp = X.getType()->hasSignedIntegerRepresentation()
5771                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
5772                                    : llvm::AtomicRMWInst::Min)
5773                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
5774                                    : llvm::AtomicRMWInst::UMin);
5775     break;
5776   case BO_Assign:
5777     RMWOp = llvm::AtomicRMWInst::Xchg;
5778     break;
5779   case BO_Mul:
5780   case BO_Div:
5781   case BO_Rem:
5782   case BO_Shl:
5783   case BO_Shr:
5784   case BO_LAnd:
5785   case BO_LOr:
5786     return std::make_pair(false, RValue::get(nullptr));
5787   case BO_PtrMemD:
5788   case BO_PtrMemI:
5789   case BO_LE:
5790   case BO_GE:
5791   case BO_EQ:
5792   case BO_NE:
5793   case BO_Cmp:
5794   case BO_AddAssign:
5795   case BO_SubAssign:
5796   case BO_AndAssign:
5797   case BO_OrAssign:
5798   case BO_XorAssign:
5799   case BO_MulAssign:
5800   case BO_DivAssign:
5801   case BO_RemAssign:
5802   case BO_ShlAssign:
5803   case BO_ShrAssign:
5804   case BO_Comma:
5805     llvm_unreachable("Unsupported atomic update operation");
5806   }
5807   llvm::Value *UpdateVal = Update.getScalarVal();
5808   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
5809     UpdateVal = CGF.Builder.CreateIntCast(
5810         IC, X.getAddress(CGF).getElementType(),
5811         X.getType()->hasSignedIntegerRepresentation());
5812   }
5813   llvm::Value *Res =
5814       CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
5815   return std::make_pair(true, RValue::get(Res));
5816 }
5817 
5818 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
5819     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
5820     llvm::AtomicOrdering AO, SourceLocation Loc,
5821     const llvm::function_ref<RValue(RValue)> CommonGen) {
5822   // Update expressions are allowed to have the following forms:
5823   // x binop= expr; -> xrval + expr;
5824   // x++, ++x -> xrval + 1;
5825   // x--, --x -> xrval - 1;
5826   // x = x binop expr; -> xrval binop expr
5827   // x = expr Op x; - > expr binop xrval;
5828   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
5829   if (!Res.first) {
5830     if (X.isGlobalReg()) {
5831       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
5832       // 'xrval'.
5833       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
5834     } else {
5835       // Perform compare-and-swap procedure.
5836       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
5837     }
5838   }
5839   return Res;
5840 }
5841 
5842 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF,
5843                                     llvm::AtomicOrdering AO, const Expr *X,
5844                                     const Expr *E, const Expr *UE,
5845                                     bool IsXLHSInRHSPart, SourceLocation Loc) {
5846   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
5847          "Update expr in 'atomic update' must be a binary operator.");
5848   const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
5849   // Update expressions are allowed to have the following forms:
5850   // x binop= expr; -> xrval + expr;
5851   // x++, ++x -> xrval + 1;
5852   // x--, --x -> xrval - 1;
5853   // x = x binop expr; -> xrval binop expr
5854   // x = expr Op x; - > expr binop xrval;
5855   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
5856   LValue XLValue = CGF.EmitLValue(X);
5857   RValue ExprRValue = CGF.EmitAnyExpr(E);
5858   const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
5859   const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
5860   const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
5861   const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
5862   auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
5863     CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5864     CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
5865     return CGF.EmitAnyExpr(UE);
5866   };
5867   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
5868       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
5869   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5870   // OpenMP, 2.17.7, atomic Construct
5871   // If the write, update, or capture clause is specified and the release,
5872   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5873   // the atomic operation is also a release flush.
5874   switch (AO) {
5875   case llvm::AtomicOrdering::Release:
5876   case llvm::AtomicOrdering::AcquireRelease:
5877   case llvm::AtomicOrdering::SequentiallyConsistent:
5878     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5879                                          llvm::AtomicOrdering::Release);
5880     break;
5881   case llvm::AtomicOrdering::Acquire:
5882   case llvm::AtomicOrdering::Monotonic:
5883     break;
5884   case llvm::AtomicOrdering::NotAtomic:
5885   case llvm::AtomicOrdering::Unordered:
5886     llvm_unreachable("Unexpected ordering.");
5887   }
5888 }
5889 
5890 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
5891                             QualType SourceType, QualType ResType,
5892                             SourceLocation Loc) {
5893   switch (CGF.getEvaluationKind(ResType)) {
5894   case TEK_Scalar:
5895     return RValue::get(
5896         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
5897   case TEK_Complex: {
5898     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
5899     return RValue::getComplex(Res.first, Res.second);
5900   }
5901   case TEK_Aggregate:
5902     break;
5903   }
5904   llvm_unreachable("Must be a scalar or complex.");
5905 }
5906 
5907 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF,
5908                                      llvm::AtomicOrdering AO,
5909                                      bool IsPostfixUpdate, const Expr *V,
5910                                      const Expr *X, const Expr *E,
5911                                      const Expr *UE, bool IsXLHSInRHSPart,
5912                                      SourceLocation Loc) {
5913   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
5914   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
5915   RValue NewVVal;
5916   LValue VLValue = CGF.EmitLValue(V);
5917   LValue XLValue = CGF.EmitLValue(X);
5918   RValue ExprRValue = CGF.EmitAnyExpr(E);
5919   QualType NewVValType;
5920   if (UE) {
5921     // 'x' is updated with some additional value.
5922     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
5923            "Update expr in 'atomic capture' must be a binary operator.");
5924     const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
5925     // Update expressions are allowed to have the following forms:
5926     // x binop= expr; -> xrval + expr;
5927     // x++, ++x -> xrval + 1;
5928     // x--, --x -> xrval - 1;
5929     // x = x binop expr; -> xrval binop expr
5930     // x = expr Op x; - > expr binop xrval;
5931     const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
5932     const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
5933     const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
5934     NewVValType = XRValExpr->getType();
5935     const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
5936     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
5937                   IsPostfixUpdate](RValue XRValue) {
5938       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5939       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
5940       RValue Res = CGF.EmitAnyExpr(UE);
5941       NewVVal = IsPostfixUpdate ? XRValue : Res;
5942       return Res;
5943     };
5944     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
5945         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
5946     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5947     if (Res.first) {
5948       // 'atomicrmw' instruction was generated.
5949       if (IsPostfixUpdate) {
5950         // Use old value from 'atomicrmw'.
5951         NewVVal = Res.second;
5952       } else {
5953         // 'atomicrmw' does not provide new value, so evaluate it using old
5954         // value of 'x'.
5955         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5956         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
5957         NewVVal = CGF.EmitAnyExpr(UE);
5958       }
5959     }
5960   } else {
5961     // 'x' is simply rewritten with some 'expr'.
5962     NewVValType = X->getType().getNonReferenceType();
5963     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
5964                                X->getType().getNonReferenceType(), Loc);
5965     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
5966       NewVVal = XRValue;
5967       return ExprRValue;
5968     };
5969     // Try to perform atomicrmw xchg, otherwise simple exchange.
5970     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
5971         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
5972         Loc, Gen);
5973     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5974     if (Res.first) {
5975       // 'atomicrmw' instruction was generated.
5976       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
5977     }
5978   }
5979   // Emit post-update store to 'v' of old/new 'x' value.
5980   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
5981   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
5982   // OpenMP 5.1 removes the required flush for capture clause.
5983   if (CGF.CGM.getLangOpts().OpenMP < 51) {
5984     // OpenMP, 2.17.7, atomic Construct
5985     // If the write, update, or capture clause is specified and the release,
5986     // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5987     // the atomic operation is also a release flush.
5988     // If the read or capture clause is specified and the acquire, acq_rel, or
5989     // seq_cst clause is specified then the strong flush on exit from the atomic
5990     // operation is also an acquire flush.
5991     switch (AO) {
5992     case llvm::AtomicOrdering::Release:
5993       CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5994                                            llvm::AtomicOrdering::Release);
5995       break;
5996     case llvm::AtomicOrdering::Acquire:
5997       CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5998                                            llvm::AtomicOrdering::Acquire);
5999       break;
6000     case llvm::AtomicOrdering::AcquireRelease:
6001     case llvm::AtomicOrdering::SequentiallyConsistent:
6002       CGF.CGM.getOpenMPRuntime().emitFlush(
6003           CGF, llvm::None, Loc, llvm::AtomicOrdering::AcquireRelease);
6004       break;
6005     case llvm::AtomicOrdering::Monotonic:
6006       break;
6007     case llvm::AtomicOrdering::NotAtomic:
6008     case llvm::AtomicOrdering::Unordered:
6009       llvm_unreachable("Unexpected ordering.");
6010     }
6011   }
6012 }
6013 
6014 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
6015                               llvm::AtomicOrdering AO, bool IsPostfixUpdate,
6016                               const Expr *X, const Expr *V, const Expr *E,
6017                               const Expr *UE, bool IsXLHSInRHSPart,
6018                               SourceLocation Loc) {
6019   switch (Kind) {
6020   case OMPC_read:
6021     emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
6022     break;
6023   case OMPC_write:
6024     emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
6025     break;
6026   case OMPC_unknown:
6027   case OMPC_update:
6028     emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
6029     break;
6030   case OMPC_capture:
6031     emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
6032                              IsXLHSInRHSPart, Loc);
6033     break;
6034   case OMPC_compare:
6035     // Do nothing here as we already emit an error.
6036     break;
6037   case OMPC_if:
6038   case OMPC_final:
6039   case OMPC_num_threads:
6040   case OMPC_private:
6041   case OMPC_firstprivate:
6042   case OMPC_lastprivate:
6043   case OMPC_reduction:
6044   case OMPC_task_reduction:
6045   case OMPC_in_reduction:
6046   case OMPC_safelen:
6047   case OMPC_simdlen:
6048   case OMPC_sizes:
6049   case OMPC_full:
6050   case OMPC_partial:
6051   case OMPC_allocator:
6052   case OMPC_allocate:
6053   case OMPC_collapse:
6054   case OMPC_default:
6055   case OMPC_seq_cst:
6056   case OMPC_acq_rel:
6057   case OMPC_acquire:
6058   case OMPC_release:
6059   case OMPC_relaxed:
6060   case OMPC_shared:
6061   case OMPC_linear:
6062   case OMPC_aligned:
6063   case OMPC_copyin:
6064   case OMPC_copyprivate:
6065   case OMPC_flush:
6066   case OMPC_depobj:
6067   case OMPC_proc_bind:
6068   case OMPC_schedule:
6069   case OMPC_ordered:
6070   case OMPC_nowait:
6071   case OMPC_untied:
6072   case OMPC_threadprivate:
6073   case OMPC_depend:
6074   case OMPC_mergeable:
6075   case OMPC_device:
6076   case OMPC_threads:
6077   case OMPC_simd:
6078   case OMPC_map:
6079   case OMPC_num_teams:
6080   case OMPC_thread_limit:
6081   case OMPC_priority:
6082   case OMPC_grainsize:
6083   case OMPC_nogroup:
6084   case OMPC_num_tasks:
6085   case OMPC_hint:
6086   case OMPC_dist_schedule:
6087   case OMPC_defaultmap:
6088   case OMPC_uniform:
6089   case OMPC_to:
6090   case OMPC_from:
6091   case OMPC_use_device_ptr:
6092   case OMPC_use_device_addr:
6093   case OMPC_is_device_ptr:
6094   case OMPC_unified_address:
6095   case OMPC_unified_shared_memory:
6096   case OMPC_reverse_offload:
6097   case OMPC_dynamic_allocators:
6098   case OMPC_atomic_default_mem_order:
6099   case OMPC_device_type:
6100   case OMPC_match:
6101   case OMPC_nontemporal:
6102   case OMPC_order:
6103   case OMPC_destroy:
6104   case OMPC_detach:
6105   case OMPC_inclusive:
6106   case OMPC_exclusive:
6107   case OMPC_uses_allocators:
6108   case OMPC_affinity:
6109   case OMPC_init:
6110   case OMPC_inbranch:
6111   case OMPC_notinbranch:
6112   case OMPC_link:
6113   case OMPC_indirect:
6114   case OMPC_use:
6115   case OMPC_novariants:
6116   case OMPC_nocontext:
6117   case OMPC_filter:
6118   case OMPC_when:
6119   case OMPC_adjust_args:
6120   case OMPC_append_args:
6121   case OMPC_memory_order:
6122   case OMPC_bind:
6123   case OMPC_align:
6124     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
6125   }
6126 }
6127 
6128 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
6129   llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic;
6130   bool MemOrderingSpecified = false;
6131   if (S.getSingleClause<OMPSeqCstClause>()) {
6132     AO = llvm::AtomicOrdering::SequentiallyConsistent;
6133     MemOrderingSpecified = true;
6134   } else if (S.getSingleClause<OMPAcqRelClause>()) {
6135     AO = llvm::AtomicOrdering::AcquireRelease;
6136     MemOrderingSpecified = true;
6137   } else if (S.getSingleClause<OMPAcquireClause>()) {
6138     AO = llvm::AtomicOrdering::Acquire;
6139     MemOrderingSpecified = true;
6140   } else if (S.getSingleClause<OMPReleaseClause>()) {
6141     AO = llvm::AtomicOrdering::Release;
6142     MemOrderingSpecified = true;
6143   } else if (S.getSingleClause<OMPRelaxedClause>()) {
6144     AO = llvm::AtomicOrdering::Monotonic;
6145     MemOrderingSpecified = true;
6146   }
6147   OpenMPClauseKind Kind = OMPC_unknown;
6148   for (const OMPClause *C : S.clauses()) {
6149     // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause,
6150     // if it is first).
6151     if (C->getClauseKind() != OMPC_seq_cst &&
6152         C->getClauseKind() != OMPC_acq_rel &&
6153         C->getClauseKind() != OMPC_acquire &&
6154         C->getClauseKind() != OMPC_release &&
6155         C->getClauseKind() != OMPC_relaxed && C->getClauseKind() != OMPC_hint) {
6156       Kind = C->getClauseKind();
6157       break;
6158     }
6159   }
6160   if (!MemOrderingSpecified) {
6161     llvm::AtomicOrdering DefaultOrder =
6162         CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
6163     if (DefaultOrder == llvm::AtomicOrdering::Monotonic ||
6164         DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent ||
6165         (DefaultOrder == llvm::AtomicOrdering::AcquireRelease &&
6166          Kind == OMPC_capture)) {
6167       AO = DefaultOrder;
6168     } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) {
6169       if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) {
6170         AO = llvm::AtomicOrdering::Release;
6171       } else if (Kind == OMPC_read) {
6172         assert(Kind == OMPC_read && "Unexpected atomic kind.");
6173         AO = llvm::AtomicOrdering::Acquire;
6174       }
6175     }
6176   }
6177 
6178   LexicalScope Scope(*this, S.getSourceRange());
6179   EmitStopPoint(S.getAssociatedStmt());
6180   emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(),
6181                     S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(),
6182                     S.getBeginLoc());
6183 }
6184 
6185 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
6186                                          const OMPExecutableDirective &S,
6187                                          const RegionCodeGenTy &CodeGen) {
6188   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
6189   CodeGenModule &CGM = CGF.CGM;
6190 
6191   // On device emit this construct as inlined code.
6192   if (CGM.getLangOpts().OpenMPIsDevice) {
6193     OMPLexicalScope Scope(CGF, S, OMPD_target);
6194     CGM.getOpenMPRuntime().emitInlinedDirective(
6195         CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6196           CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
6197         });
6198     return;
6199   }
6200 
6201   auto LPCRegion = CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
6202   llvm::Function *Fn = nullptr;
6203   llvm::Constant *FnID = nullptr;
6204 
6205   const Expr *IfCond = nullptr;
6206   // Check for the at most one if clause associated with the target region.
6207   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
6208     if (C->getNameModifier() == OMPD_unknown ||
6209         C->getNameModifier() == OMPD_target) {
6210       IfCond = C->getCondition();
6211       break;
6212     }
6213   }
6214 
6215   // Check if we have any device clause associated with the directive.
6216   llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device(
6217       nullptr, OMPC_DEVICE_unknown);
6218   if (auto *C = S.getSingleClause<OMPDeviceClause>())
6219     Device.setPointerAndInt(C->getDevice(), C->getModifier());
6220 
6221   // Check if we have an if clause whose conditional always evaluates to false
6222   // or if we do not have any targets specified. If so the target region is not
6223   // an offload entry point.
6224   bool IsOffloadEntry = true;
6225   if (IfCond) {
6226     bool Val;
6227     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
6228       IsOffloadEntry = false;
6229   }
6230   if (CGM.getLangOpts().OMPTargetTriples.empty())
6231     IsOffloadEntry = false;
6232 
6233   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
6234   StringRef ParentName;
6235   // In case we have Ctors/Dtors we use the complete type variant to produce
6236   // the mangling of the device outlined kernel.
6237   if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
6238     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
6239   else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
6240     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
6241   else
6242     ParentName =
6243         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
6244 
6245   // Emit target region as a standalone region.
6246   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
6247                                                     IsOffloadEntry, CodeGen);
6248   OMPLexicalScope Scope(CGF, S, OMPD_task);
6249   auto &&SizeEmitter =
6250       [IsOffloadEntry](CodeGenFunction &CGF,
6251                        const OMPLoopDirective &D) -> llvm::Value * {
6252     if (IsOffloadEntry) {
6253       OMPLoopScope(CGF, D);
6254       // Emit calculation of the iterations count.
6255       llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
6256       NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
6257                                                 /*isSigned=*/false);
6258       return NumIterations;
6259     }
6260     return nullptr;
6261   };
6262   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
6263                                         SizeEmitter);
6264 }
6265 
6266 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
6267                              PrePostActionTy &Action) {
6268   Action.Enter(CGF);
6269   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6270   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6271   CGF.EmitOMPPrivateClause(S, PrivateScope);
6272   (void)PrivateScope.Privatize();
6273   if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6274     CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
6275 
6276   CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
6277   CGF.EnsureInsertPoint();
6278 }
6279 
6280 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
6281                                                   StringRef ParentName,
6282                                                   const OMPTargetDirective &S) {
6283   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6284     emitTargetRegion(CGF, S, Action);
6285   };
6286   llvm::Function *Fn;
6287   llvm::Constant *Addr;
6288   // Emit target region as a standalone region.
6289   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6290       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6291   assert(Fn && Addr && "Target device function emission failed.");
6292 }
6293 
6294 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
6295   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6296     emitTargetRegion(CGF, S, Action);
6297   };
6298   emitCommonOMPTargetDirective(*this, S, CodeGen);
6299 }
6300 
6301 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
6302                                         const OMPExecutableDirective &S,
6303                                         OpenMPDirectiveKind InnermostKind,
6304                                         const RegionCodeGenTy &CodeGen) {
6305   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
6306   llvm::Function *OutlinedFn =
6307       CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
6308           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
6309 
6310   const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
6311   const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
6312   if (NT || TL) {
6313     const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
6314     const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
6315 
6316     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
6317                                                   S.getBeginLoc());
6318   }
6319 
6320   OMPTeamsScope Scope(CGF, S);
6321   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
6322   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
6323   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
6324                                            CapturedVars);
6325 }
6326 
6327 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
6328   // Emit teams region as a standalone region.
6329   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6330     Action.Enter(CGF);
6331     OMPPrivateScope PrivateScope(CGF);
6332     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6333     CGF.EmitOMPPrivateClause(S, PrivateScope);
6334     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6335     (void)PrivateScope.Privatize();
6336     CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
6337     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6338   };
6339   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
6340   emitPostUpdateForReductionClause(*this, S,
6341                                    [](CodeGenFunction &) { return nullptr; });
6342 }
6343 
6344 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
6345                                   const OMPTargetTeamsDirective &S) {
6346   auto *CS = S.getCapturedStmt(OMPD_teams);
6347   Action.Enter(CGF);
6348   // Emit teams region as a standalone region.
6349   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
6350     Action.Enter(CGF);
6351     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6352     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6353     CGF.EmitOMPPrivateClause(S, PrivateScope);
6354     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6355     (void)PrivateScope.Privatize();
6356     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6357       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
6358     CGF.EmitStmt(CS->getCapturedStmt());
6359     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6360   };
6361   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
6362   emitPostUpdateForReductionClause(CGF, S,
6363                                    [](CodeGenFunction &) { return nullptr; });
6364 }
6365 
6366 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6367     CodeGenModule &CGM, StringRef ParentName,
6368     const OMPTargetTeamsDirective &S) {
6369   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6370     emitTargetTeamsRegion(CGF, Action, S);
6371   };
6372   llvm::Function *Fn;
6373   llvm::Constant *Addr;
6374   // Emit target region as a standalone region.
6375   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6376       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6377   assert(Fn && Addr && "Target device function emission failed.");
6378 }
6379 
6380 void CodeGenFunction::EmitOMPTargetTeamsDirective(
6381     const OMPTargetTeamsDirective &S) {
6382   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6383     emitTargetTeamsRegion(CGF, Action, S);
6384   };
6385   emitCommonOMPTargetDirective(*this, S, CodeGen);
6386 }
6387 
6388 static void
6389 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
6390                                 const OMPTargetTeamsDistributeDirective &S) {
6391   Action.Enter(CGF);
6392   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6393     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6394   };
6395 
6396   // Emit teams region as a standalone region.
6397   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6398                                             PrePostActionTy &Action) {
6399     Action.Enter(CGF);
6400     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6401     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6402     (void)PrivateScope.Privatize();
6403     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6404                                                     CodeGenDistribute);
6405     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6406   };
6407   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
6408   emitPostUpdateForReductionClause(CGF, S,
6409                                    [](CodeGenFunction &) { return nullptr; });
6410 }
6411 
6412 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
6413     CodeGenModule &CGM, StringRef ParentName,
6414     const OMPTargetTeamsDistributeDirective &S) {
6415   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6416     emitTargetTeamsDistributeRegion(CGF, Action, S);
6417   };
6418   llvm::Function *Fn;
6419   llvm::Constant *Addr;
6420   // Emit target region as a standalone region.
6421   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6422       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6423   assert(Fn && Addr && "Target device function emission failed.");
6424 }
6425 
6426 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
6427     const OMPTargetTeamsDistributeDirective &S) {
6428   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6429     emitTargetTeamsDistributeRegion(CGF, Action, S);
6430   };
6431   emitCommonOMPTargetDirective(*this, S, CodeGen);
6432 }
6433 
6434 static void emitTargetTeamsDistributeSimdRegion(
6435     CodeGenFunction &CGF, PrePostActionTy &Action,
6436     const OMPTargetTeamsDistributeSimdDirective &S) {
6437   Action.Enter(CGF);
6438   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6439     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6440   };
6441 
6442   // Emit teams region as a standalone region.
6443   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6444                                             PrePostActionTy &Action) {
6445     Action.Enter(CGF);
6446     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6447     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6448     (void)PrivateScope.Privatize();
6449     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6450                                                     CodeGenDistribute);
6451     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6452   };
6453   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
6454   emitPostUpdateForReductionClause(CGF, S,
6455                                    [](CodeGenFunction &) { return nullptr; });
6456 }
6457 
6458 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
6459     CodeGenModule &CGM, StringRef ParentName,
6460     const OMPTargetTeamsDistributeSimdDirective &S) {
6461   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6462     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
6463   };
6464   llvm::Function *Fn;
6465   llvm::Constant *Addr;
6466   // Emit target region as a standalone region.
6467   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6468       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6469   assert(Fn && Addr && "Target device function emission failed.");
6470 }
6471 
6472 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
6473     const OMPTargetTeamsDistributeSimdDirective &S) {
6474   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6475     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
6476   };
6477   emitCommonOMPTargetDirective(*this, S, CodeGen);
6478 }
6479 
6480 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
6481     const OMPTeamsDistributeDirective &S) {
6482 
6483   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6484     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6485   };
6486 
6487   // Emit teams region as a standalone region.
6488   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6489                                             PrePostActionTy &Action) {
6490     Action.Enter(CGF);
6491     OMPPrivateScope PrivateScope(CGF);
6492     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6493     (void)PrivateScope.Privatize();
6494     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6495                                                     CodeGenDistribute);
6496     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6497   };
6498   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
6499   emitPostUpdateForReductionClause(*this, S,
6500                                    [](CodeGenFunction &) { return nullptr; });
6501 }
6502 
6503 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
6504     const OMPTeamsDistributeSimdDirective &S) {
6505   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6506     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6507   };
6508 
6509   // Emit teams region as a standalone region.
6510   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6511                                             PrePostActionTy &Action) {
6512     Action.Enter(CGF);
6513     OMPPrivateScope PrivateScope(CGF);
6514     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6515     (void)PrivateScope.Privatize();
6516     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
6517                                                     CodeGenDistribute);
6518     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6519   };
6520   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
6521   emitPostUpdateForReductionClause(*this, S,
6522                                    [](CodeGenFunction &) { return nullptr; });
6523 }
6524 
6525 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
6526     const OMPTeamsDistributeParallelForDirective &S) {
6527   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6528     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6529                               S.getDistInc());
6530   };
6531 
6532   // Emit teams region as a standalone region.
6533   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6534                                             PrePostActionTy &Action) {
6535     Action.Enter(CGF);
6536     OMPPrivateScope PrivateScope(CGF);
6537     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6538     (void)PrivateScope.Privatize();
6539     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6540                                                     CodeGenDistribute);
6541     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6542   };
6543   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
6544   emitPostUpdateForReductionClause(*this, S,
6545                                    [](CodeGenFunction &) { return nullptr; });
6546 }
6547 
6548 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
6549     const OMPTeamsDistributeParallelForSimdDirective &S) {
6550   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6551     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6552                               S.getDistInc());
6553   };
6554 
6555   // Emit teams region as a standalone region.
6556   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6557                                             PrePostActionTy &Action) {
6558     Action.Enter(CGF);
6559     OMPPrivateScope PrivateScope(CGF);
6560     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6561     (void)PrivateScope.Privatize();
6562     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6563         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6564     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6565   };
6566   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
6567                               CodeGen);
6568   emitPostUpdateForReductionClause(*this, S,
6569                                    [](CodeGenFunction &) { return nullptr; });
6570 }
6571 
6572 void CodeGenFunction::EmitOMPInteropDirective(const OMPInteropDirective &S) {
6573   llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
6574   llvm::Value *Device = nullptr;
6575   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
6576     Device = EmitScalarExpr(C->getDevice());
6577 
6578   llvm::Value *NumDependences = nullptr;
6579   llvm::Value *DependenceAddress = nullptr;
6580   if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
6581     OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
6582                                            DC->getModifier());
6583     Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
6584     std::pair<llvm::Value *, Address> DependencePair =
6585         CGM.getOpenMPRuntime().emitDependClause(*this, Dependencies,
6586                                                 DC->getBeginLoc());
6587     NumDependences = DependencePair.first;
6588     DependenceAddress = Builder.CreatePointerCast(
6589         DependencePair.second.getPointer(), CGM.Int8PtrTy);
6590   }
6591 
6592   assert(!(S.hasClausesOfKind<OMPNowaitClause>() &&
6593            !(S.getSingleClause<OMPInitClause>() ||
6594              S.getSingleClause<OMPDestroyClause>() ||
6595              S.getSingleClause<OMPUseClause>())) &&
6596          "OMPNowaitClause clause is used separately in OMPInteropDirective.");
6597 
6598   if (const auto *C = S.getSingleClause<OMPInitClause>()) {
6599     llvm::Value *InteropvarPtr =
6600         EmitLValue(C->getInteropVar()).getPointer(*this);
6601     llvm::omp::OMPInteropType InteropType = llvm::omp::OMPInteropType::Unknown;
6602     if (C->getIsTarget()) {
6603       InteropType = llvm::omp::OMPInteropType::Target;
6604     } else {
6605       assert(C->getIsTargetSync() && "Expected interop-type target/targetsync");
6606       InteropType = llvm::omp::OMPInteropType::TargetSync;
6607     }
6608     OMPBuilder.createOMPInteropInit(Builder, InteropvarPtr, InteropType, Device,
6609                                     NumDependences, DependenceAddress,
6610                                     S.hasClausesOfKind<OMPNowaitClause>());
6611   } else if (const auto *C = S.getSingleClause<OMPDestroyClause>()) {
6612     llvm::Value *InteropvarPtr =
6613         EmitLValue(C->getInteropVar()).getPointer(*this);
6614     OMPBuilder.createOMPInteropDestroy(Builder, InteropvarPtr, Device,
6615                                        NumDependences, DependenceAddress,
6616                                        S.hasClausesOfKind<OMPNowaitClause>());
6617   } else if (const auto *C = S.getSingleClause<OMPUseClause>()) {
6618     llvm::Value *InteropvarPtr =
6619         EmitLValue(C->getInteropVar()).getPointer(*this);
6620     OMPBuilder.createOMPInteropUse(Builder, InteropvarPtr, Device,
6621                                    NumDependences, DependenceAddress,
6622                                    S.hasClausesOfKind<OMPNowaitClause>());
6623   }
6624 }
6625 
6626 static void emitTargetTeamsDistributeParallelForRegion(
6627     CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
6628     PrePostActionTy &Action) {
6629   Action.Enter(CGF);
6630   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6631     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6632                               S.getDistInc());
6633   };
6634 
6635   // Emit teams region as a standalone region.
6636   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6637                                                  PrePostActionTy &Action) {
6638     Action.Enter(CGF);
6639     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6640     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6641     (void)PrivateScope.Privatize();
6642     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6643         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6644     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6645   };
6646 
6647   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
6648                               CodeGenTeams);
6649   emitPostUpdateForReductionClause(CGF, S,
6650                                    [](CodeGenFunction &) { return nullptr; });
6651 }
6652 
6653 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
6654     CodeGenModule &CGM, StringRef ParentName,
6655     const OMPTargetTeamsDistributeParallelForDirective &S) {
6656   // Emit SPMD target teams distribute parallel for region as a standalone
6657   // region.
6658   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6659     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
6660   };
6661   llvm::Function *Fn;
6662   llvm::Constant *Addr;
6663   // Emit target region as a standalone region.
6664   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6665       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6666   assert(Fn && Addr && "Target device function emission failed.");
6667 }
6668 
6669 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
6670     const OMPTargetTeamsDistributeParallelForDirective &S) {
6671   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6672     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
6673   };
6674   emitCommonOMPTargetDirective(*this, S, CodeGen);
6675 }
6676 
6677 static void emitTargetTeamsDistributeParallelForSimdRegion(
6678     CodeGenFunction &CGF,
6679     const OMPTargetTeamsDistributeParallelForSimdDirective &S,
6680     PrePostActionTy &Action) {
6681   Action.Enter(CGF);
6682   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6683     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6684                               S.getDistInc());
6685   };
6686 
6687   // Emit teams region as a standalone region.
6688   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6689                                                  PrePostActionTy &Action) {
6690     Action.Enter(CGF);
6691     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6692     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6693     (void)PrivateScope.Privatize();
6694     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6695         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6696     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6697   };
6698 
6699   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
6700                               CodeGenTeams);
6701   emitPostUpdateForReductionClause(CGF, S,
6702                                    [](CodeGenFunction &) { return nullptr; });
6703 }
6704 
6705 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
6706     CodeGenModule &CGM, StringRef ParentName,
6707     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
6708   // Emit SPMD target teams distribute parallel for simd region as a standalone
6709   // region.
6710   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6711     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
6712   };
6713   llvm::Function *Fn;
6714   llvm::Constant *Addr;
6715   // Emit target region as a standalone region.
6716   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6717       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6718   assert(Fn && Addr && "Target device function emission failed.");
6719 }
6720 
6721 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
6722     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
6723   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6724     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
6725   };
6726   emitCommonOMPTargetDirective(*this, S, CodeGen);
6727 }
6728 
6729 void CodeGenFunction::EmitOMPCancellationPointDirective(
6730     const OMPCancellationPointDirective &S) {
6731   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
6732                                                    S.getCancelRegion());
6733 }
6734 
6735 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
6736   const Expr *IfCond = nullptr;
6737   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
6738     if (C->getNameModifier() == OMPD_unknown ||
6739         C->getNameModifier() == OMPD_cancel) {
6740       IfCond = C->getCondition();
6741       break;
6742     }
6743   }
6744   if (CGM.getLangOpts().OpenMPIRBuilder) {
6745     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
6746     // TODO: This check is necessary as we only generate `omp parallel` through
6747     // the OpenMPIRBuilder for now.
6748     if (S.getCancelRegion() == OMPD_parallel ||
6749         S.getCancelRegion() == OMPD_sections ||
6750         S.getCancelRegion() == OMPD_section) {
6751       llvm::Value *IfCondition = nullptr;
6752       if (IfCond)
6753         IfCondition = EmitScalarExpr(IfCond,
6754                                      /*IgnoreResultAssign=*/true);
6755       return Builder.restoreIP(
6756           OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion()));
6757     }
6758   }
6759 
6760   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
6761                                         S.getCancelRegion());
6762 }
6763 
6764 CodeGenFunction::JumpDest
6765 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
6766   if (Kind == OMPD_parallel || Kind == OMPD_task ||
6767       Kind == OMPD_target_parallel || Kind == OMPD_taskloop ||
6768       Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop)
6769     return ReturnBlock;
6770   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
6771          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
6772          Kind == OMPD_distribute_parallel_for ||
6773          Kind == OMPD_target_parallel_for ||
6774          Kind == OMPD_teams_distribute_parallel_for ||
6775          Kind == OMPD_target_teams_distribute_parallel_for);
6776   return OMPCancelStack.getExitBlock();
6777 }
6778 
6779 void CodeGenFunction::EmitOMPUseDevicePtrClause(
6780     const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
6781     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
6782   auto OrigVarIt = C.varlist_begin();
6783   auto InitIt = C.inits().begin();
6784   for (const Expr *PvtVarIt : C.private_copies()) {
6785     const auto *OrigVD =
6786         cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
6787     const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
6788     const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
6789 
6790     // In order to identify the right initializer we need to match the
6791     // declaration used by the mapping logic. In some cases we may get
6792     // OMPCapturedExprDecl that refers to the original declaration.
6793     const ValueDecl *MatchingVD = OrigVD;
6794     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
6795       // OMPCapturedExprDecl are used to privative fields of the current
6796       // structure.
6797       const auto *ME = cast<MemberExpr>(OED->getInit());
6798       assert(isa<CXXThisExpr>(ME->getBase()) &&
6799              "Base should be the current struct!");
6800       MatchingVD = ME->getMemberDecl();
6801     }
6802 
6803     // If we don't have information about the current list item, move on to
6804     // the next one.
6805     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
6806     if (InitAddrIt == CaptureDeviceAddrMap.end())
6807       continue;
6808 
6809     bool IsRegistered = PrivateScope.addPrivate(
6810         OrigVD, [this, OrigVD, InitAddrIt, InitVD, PvtVD]() {
6811           // Initialize the temporary initialization variable with the address
6812           // we get from the runtime library. We have to cast the source address
6813           // because it is always a void *. References are materialized in the
6814           // privatization scope, so the initialization here disregards the fact
6815           // the original variable is a reference.
6816           QualType AddrQTy = getContext().getPointerType(
6817               OrigVD->getType().getNonReferenceType());
6818           llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
6819           Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
6820           setAddrOfLocalVar(InitVD, InitAddr);
6821 
6822           // Emit private declaration, it will be initialized by the value we
6823           // declaration we just added to the local declarations map.
6824           EmitDecl(*PvtVD);
6825 
6826           // The initialization variables reached its purpose in the emission
6827           // of the previous declaration, so we don't need it anymore.
6828           LocalDeclMap.erase(InitVD);
6829 
6830           // Return the address of the private variable.
6831           return GetAddrOfLocalVar(PvtVD);
6832         });
6833     assert(IsRegistered && "firstprivate var already registered as private");
6834     // Silence the warning about unused variable.
6835     (void)IsRegistered;
6836 
6837     ++OrigVarIt;
6838     ++InitIt;
6839   }
6840 }
6841 
6842 static const VarDecl *getBaseDecl(const Expr *Ref) {
6843   const Expr *Base = Ref->IgnoreParenImpCasts();
6844   while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base))
6845     Base = OASE->getBase()->IgnoreParenImpCasts();
6846   while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base))
6847     Base = ASE->getBase()->IgnoreParenImpCasts();
6848   return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl());
6849 }
6850 
6851 void CodeGenFunction::EmitOMPUseDeviceAddrClause(
6852     const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
6853     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
6854   llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
6855   for (const Expr *Ref : C.varlists()) {
6856     const VarDecl *OrigVD = getBaseDecl(Ref);
6857     if (!Processed.insert(OrigVD).second)
6858       continue;
6859     // In order to identify the right initializer we need to match the
6860     // declaration used by the mapping logic. In some cases we may get
6861     // OMPCapturedExprDecl that refers to the original declaration.
6862     const ValueDecl *MatchingVD = OrigVD;
6863     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
6864       // OMPCapturedExprDecl are used to privative fields of the current
6865       // structure.
6866       const auto *ME = cast<MemberExpr>(OED->getInit());
6867       assert(isa<CXXThisExpr>(ME->getBase()) &&
6868              "Base should be the current struct!");
6869       MatchingVD = ME->getMemberDecl();
6870     }
6871 
6872     // If we don't have information about the current list item, move on to
6873     // the next one.
6874     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
6875     if (InitAddrIt == CaptureDeviceAddrMap.end())
6876       continue;
6877 
6878     Address PrivAddr = InitAddrIt->getSecond();
6879     // For declrefs and variable length array need to load the pointer for
6880     // correct mapping, since the pointer to the data was passed to the runtime.
6881     if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) ||
6882         MatchingVD->getType()->isArrayType())
6883       PrivAddr =
6884           EmitLoadOfPointer(PrivAddr, getContext()
6885                                           .getPointerType(OrigVD->getType())
6886                                           ->castAs<PointerType>());
6887     llvm::Type *RealTy =
6888         ConvertTypeForMem(OrigVD->getType().getNonReferenceType())
6889             ->getPointerTo();
6890     PrivAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy);
6891 
6892     (void)PrivateScope.addPrivate(OrigVD, [PrivAddr]() { return PrivAddr; });
6893   }
6894 }
6895 
6896 // Generate the instructions for '#pragma omp target data' directive.
6897 void CodeGenFunction::EmitOMPTargetDataDirective(
6898     const OMPTargetDataDirective &S) {
6899   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true,
6900                                        /*SeparateBeginEndCalls=*/true);
6901 
6902   // Create a pre/post action to signal the privatization of the device pointer.
6903   // This action can be replaced by the OpenMP runtime code generation to
6904   // deactivate privatization.
6905   bool PrivatizeDevicePointers = false;
6906   class DevicePointerPrivActionTy : public PrePostActionTy {
6907     bool &PrivatizeDevicePointers;
6908 
6909   public:
6910     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
6911         : PrivatizeDevicePointers(PrivatizeDevicePointers) {}
6912     void Enter(CodeGenFunction &CGF) override {
6913       PrivatizeDevicePointers = true;
6914     }
6915   };
6916   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
6917 
6918   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
6919                        CodeGenFunction &CGF, PrePostActionTy &Action) {
6920     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6921       CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
6922     };
6923 
6924     // Codegen that selects whether to generate the privatization code or not.
6925     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
6926                           &InnermostCodeGen](CodeGenFunction &CGF,
6927                                              PrePostActionTy &Action) {
6928       RegionCodeGenTy RCG(InnermostCodeGen);
6929       PrivatizeDevicePointers = false;
6930 
6931       // Call the pre-action to change the status of PrivatizeDevicePointers if
6932       // needed.
6933       Action.Enter(CGF);
6934 
6935       if (PrivatizeDevicePointers) {
6936         OMPPrivateScope PrivateScope(CGF);
6937         // Emit all instances of the use_device_ptr clause.
6938         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
6939           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
6940                                         Info.CaptureDeviceAddrMap);
6941         for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
6942           CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope,
6943                                          Info.CaptureDeviceAddrMap);
6944         (void)PrivateScope.Privatize();
6945         RCG(CGF);
6946       } else {
6947         OMPLexicalScope Scope(CGF, S, OMPD_unknown);
6948         RCG(CGF);
6949       }
6950     };
6951 
6952     // Forward the provided action to the privatization codegen.
6953     RegionCodeGenTy PrivRCG(PrivCodeGen);
6954     PrivRCG.setAction(Action);
6955 
6956     // Notwithstanding the body of the region is emitted as inlined directive,
6957     // we don't use an inline scope as changes in the references inside the
6958     // region are expected to be visible outside, so we do not privative them.
6959     OMPLexicalScope Scope(CGF, S);
6960     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
6961                                                     PrivRCG);
6962   };
6963 
6964   RegionCodeGenTy RCG(CodeGen);
6965 
6966   // If we don't have target devices, don't bother emitting the data mapping
6967   // code.
6968   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
6969     RCG(*this);
6970     return;
6971   }
6972 
6973   // Check if we have any if clause associated with the directive.
6974   const Expr *IfCond = nullptr;
6975   if (const auto *C = S.getSingleClause<OMPIfClause>())
6976     IfCond = C->getCondition();
6977 
6978   // Check if we have any device clause associated with the directive.
6979   const Expr *Device = nullptr;
6980   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
6981     Device = C->getDevice();
6982 
6983   // Set the action to signal privatization of device pointers.
6984   RCG.setAction(PrivAction);
6985 
6986   // Emit region code.
6987   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
6988                                              Info);
6989 }
6990 
6991 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
6992     const OMPTargetEnterDataDirective &S) {
6993   // If we don't have target devices, don't bother emitting the data mapping
6994   // code.
6995   if (CGM.getLangOpts().OMPTargetTriples.empty())
6996     return;
6997 
6998   // Check if we have any if clause associated with the directive.
6999   const Expr *IfCond = nullptr;
7000   if (const auto *C = S.getSingleClause<OMPIfClause>())
7001     IfCond = C->getCondition();
7002 
7003   // Check if we have any device clause associated with the directive.
7004   const Expr *Device = nullptr;
7005   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7006     Device = C->getDevice();
7007 
7008   OMPLexicalScope Scope(*this, S, OMPD_task);
7009   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
7010 }
7011 
7012 void CodeGenFunction::EmitOMPTargetExitDataDirective(
7013     const OMPTargetExitDataDirective &S) {
7014   // If we don't have target devices, don't bother emitting the data mapping
7015   // code.
7016   if (CGM.getLangOpts().OMPTargetTriples.empty())
7017     return;
7018 
7019   // Check if we have any if clause associated with the directive.
7020   const Expr *IfCond = nullptr;
7021   if (const auto *C = S.getSingleClause<OMPIfClause>())
7022     IfCond = C->getCondition();
7023 
7024   // Check if we have any device clause associated with the directive.
7025   const Expr *Device = nullptr;
7026   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7027     Device = C->getDevice();
7028 
7029   OMPLexicalScope Scope(*this, S, OMPD_task);
7030   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
7031 }
7032 
7033 static void emitTargetParallelRegion(CodeGenFunction &CGF,
7034                                      const OMPTargetParallelDirective &S,
7035                                      PrePostActionTy &Action) {
7036   // Get the captured statement associated with the 'parallel' region.
7037   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
7038   Action.Enter(CGF);
7039   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
7040     Action.Enter(CGF);
7041     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
7042     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
7043     CGF.EmitOMPPrivateClause(S, PrivateScope);
7044     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
7045     (void)PrivateScope.Privatize();
7046     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
7047       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
7048     // TODO: Add support for clauses.
7049     CGF.EmitStmt(CS->getCapturedStmt());
7050     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
7051   };
7052   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
7053                                  emitEmptyBoundParameters);
7054   emitPostUpdateForReductionClause(CGF, S,
7055                                    [](CodeGenFunction &) { return nullptr; });
7056 }
7057 
7058 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7059     CodeGenModule &CGM, StringRef ParentName,
7060     const OMPTargetParallelDirective &S) {
7061   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7062     emitTargetParallelRegion(CGF, S, Action);
7063   };
7064   llvm::Function *Fn;
7065   llvm::Constant *Addr;
7066   // Emit target region as a standalone region.
7067   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7068       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7069   assert(Fn && Addr && "Target device function emission failed.");
7070 }
7071 
7072 void CodeGenFunction::EmitOMPTargetParallelDirective(
7073     const OMPTargetParallelDirective &S) {
7074   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7075     emitTargetParallelRegion(CGF, S, Action);
7076   };
7077   emitCommonOMPTargetDirective(*this, S, CodeGen);
7078 }
7079 
7080 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
7081                                         const OMPTargetParallelForDirective &S,
7082                                         PrePostActionTy &Action) {
7083   Action.Enter(CGF);
7084   // Emit directive as a combined directive that consists of two implicit
7085   // directives: 'parallel' with 'for' directive.
7086   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7087     Action.Enter(CGF);
7088     CodeGenFunction::OMPCancelStackRAII CancelRegion(
7089         CGF, OMPD_target_parallel_for, S.hasCancel());
7090     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
7091                                emitDispatchForLoopBounds);
7092   };
7093   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
7094                                  emitEmptyBoundParameters);
7095 }
7096 
7097 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7098     CodeGenModule &CGM, StringRef ParentName,
7099     const OMPTargetParallelForDirective &S) {
7100   // Emit SPMD target parallel for region as a standalone region.
7101   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7102     emitTargetParallelForRegion(CGF, S, Action);
7103   };
7104   llvm::Function *Fn;
7105   llvm::Constant *Addr;
7106   // Emit target region as a standalone region.
7107   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7108       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7109   assert(Fn && Addr && "Target device function emission failed.");
7110 }
7111 
7112 void CodeGenFunction::EmitOMPTargetParallelForDirective(
7113     const OMPTargetParallelForDirective &S) {
7114   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7115     emitTargetParallelForRegion(CGF, S, Action);
7116   };
7117   emitCommonOMPTargetDirective(*this, S, CodeGen);
7118 }
7119 
7120 static void
7121 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
7122                                 const OMPTargetParallelForSimdDirective &S,
7123                                 PrePostActionTy &Action) {
7124   Action.Enter(CGF);
7125   // Emit directive as a combined directive that consists of two implicit
7126   // directives: 'parallel' with 'for' directive.
7127   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7128     Action.Enter(CGF);
7129     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
7130                                emitDispatchForLoopBounds);
7131   };
7132   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
7133                                  emitEmptyBoundParameters);
7134 }
7135 
7136 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7137     CodeGenModule &CGM, StringRef ParentName,
7138     const OMPTargetParallelForSimdDirective &S) {
7139   // Emit SPMD target parallel for region as a standalone region.
7140   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7141     emitTargetParallelForSimdRegion(CGF, S, Action);
7142   };
7143   llvm::Function *Fn;
7144   llvm::Constant *Addr;
7145   // Emit target region as a standalone region.
7146   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
7147       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
7148   assert(Fn && Addr && "Target device function emission failed.");
7149 }
7150 
7151 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
7152     const OMPTargetParallelForSimdDirective &S) {
7153   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7154     emitTargetParallelForSimdRegion(CGF, S, Action);
7155   };
7156   emitCommonOMPTargetDirective(*this, S, CodeGen);
7157 }
7158 
7159 /// Emit a helper variable and return corresponding lvalue.
7160 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
7161                      const ImplicitParamDecl *PVD,
7162                      CodeGenFunction::OMPPrivateScope &Privates) {
7163   const auto *VDecl = cast<VarDecl>(Helper->getDecl());
7164   Privates.addPrivate(VDecl,
7165                       [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
7166 }
7167 
7168 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
7169   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
7170   // Emit outlined function for task construct.
7171   const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
7172   Address CapturedStruct = Address::invalid();
7173   {
7174     OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
7175     CapturedStruct = GenerateCapturedStmtArgument(*CS);
7176   }
7177   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
7178   const Expr *IfCond = nullptr;
7179   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
7180     if (C->getNameModifier() == OMPD_unknown ||
7181         C->getNameModifier() == OMPD_taskloop) {
7182       IfCond = C->getCondition();
7183       break;
7184     }
7185   }
7186 
7187   OMPTaskDataTy Data;
7188   // Check if taskloop must be emitted without taskgroup.
7189   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
7190   // TODO: Check if we should emit tied or untied task.
7191   Data.Tied = true;
7192   // Set scheduling for taskloop
7193   if (const auto *Clause = S.getSingleClause<OMPGrainsizeClause>()) {
7194     // grainsize clause
7195     Data.Schedule.setInt(/*IntVal=*/false);
7196     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
7197   } else if (const auto *Clause = S.getSingleClause<OMPNumTasksClause>()) {
7198     // num_tasks clause
7199     Data.Schedule.setInt(/*IntVal=*/true);
7200     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
7201   }
7202 
7203   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
7204     // if (PreCond) {
7205     //   for (IV in 0..LastIteration) BODY;
7206     //   <Final counter/linear vars updates>;
7207     // }
7208     //
7209 
7210     // Emit: if (PreCond) - begin.
7211     // If the condition constant folds and can be elided, avoid emitting the
7212     // whole loop.
7213     bool CondConstant;
7214     llvm::BasicBlock *ContBlock = nullptr;
7215     OMPLoopScope PreInitScope(CGF, S);
7216     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
7217       if (!CondConstant)
7218         return;
7219     } else {
7220       llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
7221       ContBlock = CGF.createBasicBlock("taskloop.if.end");
7222       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
7223                   CGF.getProfileCount(&S));
7224       CGF.EmitBlock(ThenBlock);
7225       CGF.incrementProfileCounter(&S);
7226     }
7227 
7228     (void)CGF.EmitOMPLinearClauseInit(S);
7229 
7230     OMPPrivateScope LoopScope(CGF);
7231     // Emit helper vars inits.
7232     enum { LowerBound = 5, UpperBound, Stride, LastIter };
7233     auto *I = CS->getCapturedDecl()->param_begin();
7234     auto *LBP = std::next(I, LowerBound);
7235     auto *UBP = std::next(I, UpperBound);
7236     auto *STP = std::next(I, Stride);
7237     auto *LIP = std::next(I, LastIter);
7238     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
7239              LoopScope);
7240     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
7241              LoopScope);
7242     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
7243     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
7244              LoopScope);
7245     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
7246     CGF.EmitOMPLinearClause(S, LoopScope);
7247     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
7248     (void)LoopScope.Privatize();
7249     // Emit the loop iteration variable.
7250     const Expr *IVExpr = S.getIterationVariable();
7251     const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
7252     CGF.EmitVarDecl(*IVDecl);
7253     CGF.EmitIgnoredExpr(S.getInit());
7254 
7255     // Emit the iterations count variable.
7256     // If it is not a variable, Sema decided to calculate iterations count on
7257     // each iteration (e.g., it is foldable into a constant).
7258     if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
7259       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
7260       // Emit calculation of the iterations count.
7261       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
7262     }
7263 
7264     {
7265       OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
7266       emitCommonSimdLoop(
7267           CGF, S,
7268           [&S](CodeGenFunction &CGF, PrePostActionTy &) {
7269             if (isOpenMPSimdDirective(S.getDirectiveKind()))
7270               CGF.EmitOMPSimdInit(S);
7271           },
7272           [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
7273             CGF.EmitOMPInnerLoop(
7274                 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
7275                 [&S](CodeGenFunction &CGF) {
7276                   emitOMPLoopBodyWithStopPoint(CGF, S,
7277                                                CodeGenFunction::JumpDest());
7278                 },
7279                 [](CodeGenFunction &) {});
7280           });
7281     }
7282     // Emit: if (PreCond) - end.
7283     if (ContBlock) {
7284       CGF.EmitBranch(ContBlock);
7285       CGF.EmitBlock(ContBlock, true);
7286     }
7287     // Emit final copy of the lastprivate variables if IsLastIter != 0.
7288     if (HasLastprivateClause) {
7289       CGF.EmitOMPLastprivateClauseFinal(
7290           S, isOpenMPSimdDirective(S.getDirectiveKind()),
7291           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
7292               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
7293               (*LIP)->getType(), S.getBeginLoc())));
7294     }
7295     CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
7296       return CGF.Builder.CreateIsNotNull(
7297           CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
7298                                (*LIP)->getType(), S.getBeginLoc()));
7299     });
7300   };
7301   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
7302                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
7303                             const OMPTaskDataTy &Data) {
7304     auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
7305                       &Data](CodeGenFunction &CGF, PrePostActionTy &) {
7306       OMPLoopScope PreInitScope(CGF, S);
7307       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
7308                                                   OutlinedFn, SharedsTy,
7309                                                   CapturedStruct, IfCond, Data);
7310     };
7311     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
7312                                                     CodeGen);
7313   };
7314   if (Data.Nogroup) {
7315     EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
7316   } else {
7317     CGM.getOpenMPRuntime().emitTaskgroupRegion(
7318         *this,
7319         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
7320                                         PrePostActionTy &Action) {
7321           Action.Enter(CGF);
7322           CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
7323                                         Data);
7324         },
7325         S.getBeginLoc());
7326   }
7327 }
7328 
7329 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
7330   auto LPCRegion =
7331       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7332   EmitOMPTaskLoopBasedDirective(S);
7333 }
7334 
7335 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
7336     const OMPTaskLoopSimdDirective &S) {
7337   auto LPCRegion =
7338       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7339   OMPLexicalScope Scope(*this, S);
7340   EmitOMPTaskLoopBasedDirective(S);
7341 }
7342 
7343 void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
7344     const OMPMasterTaskLoopDirective &S) {
7345   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7346     Action.Enter(CGF);
7347     EmitOMPTaskLoopBasedDirective(S);
7348   };
7349   auto LPCRegion =
7350       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7351   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
7352   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7353 }
7354 
7355 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
7356     const OMPMasterTaskLoopSimdDirective &S) {
7357   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7358     Action.Enter(CGF);
7359     EmitOMPTaskLoopBasedDirective(S);
7360   };
7361   auto LPCRegion =
7362       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7363   OMPLexicalScope Scope(*this, S);
7364   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7365 }
7366 
7367 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
7368     const OMPParallelMasterTaskLoopDirective &S) {
7369   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7370     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7371                                   PrePostActionTy &Action) {
7372       Action.Enter(CGF);
7373       CGF.EmitOMPTaskLoopBasedDirective(S);
7374     };
7375     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7376     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7377                                             S.getBeginLoc());
7378   };
7379   auto LPCRegion =
7380       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7381   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
7382                                  emitEmptyBoundParameters);
7383 }
7384 
7385 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
7386     const OMPParallelMasterTaskLoopSimdDirective &S) {
7387   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7388     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7389                                   PrePostActionTy &Action) {
7390       Action.Enter(CGF);
7391       CGF.EmitOMPTaskLoopBasedDirective(S);
7392     };
7393     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7394     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7395                                             S.getBeginLoc());
7396   };
7397   auto LPCRegion =
7398       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7399   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
7400                                  emitEmptyBoundParameters);
7401 }
7402 
7403 // Generate the instructions for '#pragma omp target update' directive.
7404 void CodeGenFunction::EmitOMPTargetUpdateDirective(
7405     const OMPTargetUpdateDirective &S) {
7406   // If we don't have target devices, don't bother emitting the data mapping
7407   // code.
7408   if (CGM.getLangOpts().OMPTargetTriples.empty())
7409     return;
7410 
7411   // Check if we have any if clause associated with the directive.
7412   const Expr *IfCond = nullptr;
7413   if (const auto *C = S.getSingleClause<OMPIfClause>())
7414     IfCond = C->getCondition();
7415 
7416   // Check if we have any device clause associated with the directive.
7417   const Expr *Device = nullptr;
7418   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7419     Device = C->getDevice();
7420 
7421   OMPLexicalScope Scope(*this, S, OMPD_task);
7422   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
7423 }
7424 
7425 void CodeGenFunction::EmitOMPGenericLoopDirective(
7426     const OMPGenericLoopDirective &S) {
7427   // Unimplemented, just inline the underlying statement for now.
7428   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7429     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
7430   };
7431   OMPLexicalScope Scope(*this, S, OMPD_unknown);
7432   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_loop, CodeGen);
7433 }
7434 
7435 void CodeGenFunction::EmitSimpleOMPExecutableDirective(
7436     const OMPExecutableDirective &D) {
7437   if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) {
7438     EmitOMPScanDirective(*SD);
7439     return;
7440   }
7441   if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
7442     return;
7443   auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
7444     OMPPrivateScope GlobalsScope(CGF);
7445     if (isOpenMPTaskingDirective(D.getDirectiveKind())) {
7446       // Capture global firstprivates to avoid crash.
7447       for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
7448         for (const Expr *Ref : C->varlists()) {
7449           const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
7450           if (!DRE)
7451             continue;
7452           const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7453           if (!VD || VD->hasLocalStorage())
7454             continue;
7455           if (!CGF.LocalDeclMap.count(VD)) {
7456             LValue GlobLVal = CGF.EmitLValue(Ref);
7457             GlobalsScope.addPrivate(
7458                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
7459           }
7460         }
7461       }
7462     }
7463     if (isOpenMPSimdDirective(D.getDirectiveKind())) {
7464       (void)GlobalsScope.Privatize();
7465       ParentLoopDirectiveForScanRegion ScanRegion(CGF, D);
7466       emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
7467     } else {
7468       if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
7469         for (const Expr *E : LD->counters()) {
7470           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
7471           if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
7472             LValue GlobLVal = CGF.EmitLValue(E);
7473             GlobalsScope.addPrivate(
7474                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
7475           }
7476           if (isa<OMPCapturedExprDecl>(VD)) {
7477             // Emit only those that were not explicitly referenced in clauses.
7478             if (!CGF.LocalDeclMap.count(VD))
7479               CGF.EmitVarDecl(*VD);
7480           }
7481         }
7482         for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
7483           if (!C->getNumForLoops())
7484             continue;
7485           for (unsigned I = LD->getLoopsNumber(),
7486                         E = C->getLoopNumIterations().size();
7487                I < E; ++I) {
7488             if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
7489                     cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
7490               // Emit only those that were not explicitly referenced in clauses.
7491               if (!CGF.LocalDeclMap.count(VD))
7492                 CGF.EmitVarDecl(*VD);
7493             }
7494           }
7495         }
7496       }
7497       (void)GlobalsScope.Privatize();
7498       CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
7499     }
7500   };
7501   if (D.getDirectiveKind() == OMPD_atomic ||
7502       D.getDirectiveKind() == OMPD_critical ||
7503       D.getDirectiveKind() == OMPD_section ||
7504       D.getDirectiveKind() == OMPD_master ||
7505       D.getDirectiveKind() == OMPD_masked) {
7506     EmitStmt(D.getAssociatedStmt());
7507   } else {
7508     auto LPCRegion =
7509         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
7510     OMPSimdLexicalScope Scope(*this, D);
7511     CGM.getOpenMPRuntime().emitInlinedDirective(
7512         *this,
7513         isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
7514                                                     : D.getDirectiveKind(),
7515         CodeGen);
7516   }
7517   // Check for outer lastprivate conditional update.
7518   checkForLastprivateConditionalUpdate(*this, D);
7519 }
7520