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