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