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