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