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.applyWorkshareLoop(Builder.getCurrentDebugLocation(), CLI,
3625                                     AllocaIP, NeedsBarrier);
3626       return;
3627     }
3628 
3629     HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel());
3630   };
3631   {
3632     auto LPCRegion =
3633         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3634     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3635     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
3636                                                 S.hasCancel());
3637   }
3638 
3639   if (!UseOMPIRBuilder) {
3640     // Emit an implicit barrier at the end.
3641     if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
3642       CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
3643   }
3644   // Check for outer lastprivate conditional update.
3645   checkForLastprivateConditionalUpdate(*this, S);
3646 }
3647 
3648 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
3649   bool HasLastprivates = false;
3650   auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
3651                                           PrePostActionTy &) {
3652     HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
3653   };
3654   {
3655     auto LPCRegion =
3656         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3657     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3658     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
3659   }
3660 
3661   // Emit an implicit barrier at the end.
3662   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
3663     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
3664   // Check for outer lastprivate conditional update.
3665   checkForLastprivateConditionalUpdate(*this, S);
3666 }
3667 
3668 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
3669                                 const Twine &Name,
3670                                 llvm::Value *Init = nullptr) {
3671   LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
3672   if (Init)
3673     CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
3674   return LVal;
3675 }
3676 
3677 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
3678   const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
3679   const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
3680   bool HasLastprivates = false;
3681   auto &&CodeGen = [&S, CapturedStmt, CS,
3682                     &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
3683     const ASTContext &C = CGF.getContext();
3684     QualType KmpInt32Ty =
3685         C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3686     // Emit helper vars inits.
3687     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
3688                                   CGF.Builder.getInt32(0));
3689     llvm::ConstantInt *GlobalUBVal = CS != nullptr
3690                                          ? CGF.Builder.getInt32(CS->size() - 1)
3691                                          : CGF.Builder.getInt32(0);
3692     LValue UB =
3693         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
3694     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
3695                                   CGF.Builder.getInt32(1));
3696     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
3697                                   CGF.Builder.getInt32(0));
3698     // Loop counter.
3699     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
3700     OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
3701     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
3702     OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
3703     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
3704     // Generate condition for loop.
3705     BinaryOperator *Cond = BinaryOperator::Create(
3706         C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary,
3707         S.getBeginLoc(), FPOptionsOverride());
3708     // Increment for loop counter.
3709     UnaryOperator *Inc = UnaryOperator::Create(
3710         C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary,
3711         S.getBeginLoc(), true, FPOptionsOverride());
3712     auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
3713       // Iterate through all sections and emit a switch construct:
3714       // switch (IV) {
3715       //   case 0:
3716       //     <SectionStmt[0]>;
3717       //     break;
3718       // ...
3719       //   case <NumSection> - 1:
3720       //     <SectionStmt[<NumSection> - 1]>;
3721       //     break;
3722       // }
3723       // .omp.sections.exit:
3724       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
3725       llvm::SwitchInst *SwitchStmt =
3726           CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
3727                                    ExitBB, CS == nullptr ? 1 : CS->size());
3728       if (CS) {
3729         unsigned CaseNumber = 0;
3730         for (const Stmt *SubStmt : CS->children()) {
3731           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
3732           CGF.EmitBlock(CaseBB);
3733           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
3734           CGF.EmitStmt(SubStmt);
3735           CGF.EmitBranch(ExitBB);
3736           ++CaseNumber;
3737         }
3738       } else {
3739         llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
3740         CGF.EmitBlock(CaseBB);
3741         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
3742         CGF.EmitStmt(CapturedStmt);
3743         CGF.EmitBranch(ExitBB);
3744       }
3745       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
3746     };
3747 
3748     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
3749     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
3750       // Emit implicit barrier to synchronize threads and avoid data races on
3751       // initialization of firstprivate variables and post-update of lastprivate
3752       // variables.
3753       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3754           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3755           /*ForceSimpleCall=*/true);
3756     }
3757     CGF.EmitOMPPrivateClause(S, LoopScope);
3758     CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV);
3759     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
3760     CGF.EmitOMPReductionClauseInit(S, LoopScope);
3761     (void)LoopScope.Privatize();
3762     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3763       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
3764 
3765     // Emit static non-chunked loop.
3766     OpenMPScheduleTy ScheduleKind;
3767     ScheduleKind.Schedule = OMPC_SCHEDULE_static;
3768     CGOpenMPRuntime::StaticRTInput StaticInit(
3769         /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF),
3770         LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF));
3771     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
3772         CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
3773     // UB = min(UB, GlobalUB);
3774     llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
3775     llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
3776         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
3777     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
3778     // IV = LB;
3779     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
3780     // while (idx <= UB) { BODY; ++idx; }
3781     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen,
3782                          [](CodeGenFunction &) {});
3783     // Tell the runtime we are done.
3784     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
3785       CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
3786                                                      S.getDirectiveKind());
3787     };
3788     CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
3789     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3790     // Emit post-update of the reduction variables if IsLastIter != 0.
3791     emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
3792       return CGF.Builder.CreateIsNotNull(
3793           CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3794     });
3795 
3796     // Emit final copy of the lastprivate variables if IsLastIter != 0.
3797     if (HasLastprivates)
3798       CGF.EmitOMPLastprivateClauseFinal(
3799           S, /*NoFinals=*/false,
3800           CGF.Builder.CreateIsNotNull(
3801               CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
3802   };
3803 
3804   bool HasCancel = false;
3805   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
3806     HasCancel = OSD->hasCancel();
3807   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
3808     HasCancel = OPSD->hasCancel();
3809   OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
3810   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
3811                                               HasCancel);
3812   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
3813   // clause. Otherwise the barrier will be generated by the codegen for the
3814   // directive.
3815   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
3816     // Emit implicit barrier to synchronize threads and avoid data races on
3817     // initialization of firstprivate variables.
3818     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3819                                            OMPD_unknown);
3820   }
3821 }
3822 
3823 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
3824   if (CGM.getLangOpts().OpenMPIRBuilder) {
3825     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
3826     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3827     using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
3828 
3829     auto FiniCB = [this](InsertPointTy IP) {
3830       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3831     };
3832 
3833     const CapturedStmt *ICS = S.getInnermostCapturedStmt();
3834     const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
3835     const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
3836     llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector;
3837     if (CS) {
3838       for (const Stmt *SubStmt : CS->children()) {
3839         auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
3840                                          InsertPointTy CodeGenIP,
3841                                          llvm::BasicBlock &FiniBB) {
3842           OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
3843                                                          FiniBB);
3844           OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP,
3845                                                  FiniBB);
3846         };
3847         SectionCBVector.push_back(SectionCB);
3848       }
3849     } else {
3850       auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
3851                                             InsertPointTy CodeGenIP,
3852                                             llvm::BasicBlock &FiniBB) {
3853         OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3854         OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP,
3855                                                FiniBB);
3856       };
3857       SectionCBVector.push_back(SectionCB);
3858     }
3859 
3860     // Privatization callback that performs appropriate action for
3861     // shared/private/firstprivate/lastprivate/copyin/... variables.
3862     //
3863     // TODO: This defaults to shared right now.
3864     auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
3865                      llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
3866       // The next line is appropriate only for variables (Val) with the
3867       // data-sharing attribute "shared".
3868       ReplVal = &Val;
3869 
3870       return CodeGenIP;
3871     };
3872 
3873     CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
3874     CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
3875     llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
3876         AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
3877     Builder.restoreIP(OMPBuilder.createSections(
3878         Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(),
3879         S.getSingleClause<OMPNowaitClause>()));
3880     return;
3881   }
3882   {
3883     auto LPCRegion =
3884         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3885     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3886     EmitSections(S);
3887   }
3888   // Emit an implicit barrier at the end.
3889   if (!S.getSingleClause<OMPNowaitClause>()) {
3890     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
3891                                            OMPD_sections);
3892   }
3893   // Check for outer lastprivate conditional update.
3894   checkForLastprivateConditionalUpdate(*this, S);
3895 }
3896 
3897 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
3898   if (CGM.getLangOpts().OpenMPIRBuilder) {
3899     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
3900     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3901 
3902     const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt();
3903     auto FiniCB = [this](InsertPointTy IP) {
3904       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3905     };
3906 
3907     auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP,
3908                                                    InsertPointTy CodeGenIP,
3909                                                    llvm::BasicBlock &FiniBB) {
3910       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3911       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SectionRegionBodyStmt,
3912                                              CodeGenIP, FiniBB);
3913     };
3914 
3915     LexicalScope Scope(*this, S.getSourceRange());
3916     EmitStopPoint(&S);
3917     Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB));
3918 
3919     return;
3920   }
3921   LexicalScope Scope(*this, S.getSourceRange());
3922   EmitStopPoint(&S);
3923   EmitStmt(S.getAssociatedStmt());
3924 }
3925 
3926 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
3927   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
3928   llvm::SmallVector<const Expr *, 8> DestExprs;
3929   llvm::SmallVector<const Expr *, 8> SrcExprs;
3930   llvm::SmallVector<const Expr *, 8> AssignmentOps;
3931   // Check if there are any 'copyprivate' clauses associated with this
3932   // 'single' construct.
3933   // Build a list of copyprivate variables along with helper expressions
3934   // (<source>, <destination>, <destination>=<source> expressions)
3935   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
3936     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
3937     DestExprs.append(C->destination_exprs().begin(),
3938                      C->destination_exprs().end());
3939     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
3940     AssignmentOps.append(C->assignment_ops().begin(),
3941                          C->assignment_ops().end());
3942   }
3943   // Emit code for 'single' region along with 'copyprivate' clauses
3944   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3945     Action.Enter(CGF);
3946     OMPPrivateScope SingleScope(CGF);
3947     (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
3948     CGF.EmitOMPPrivateClause(S, SingleScope);
3949     (void)SingleScope.Privatize();
3950     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3951   };
3952   {
3953     auto LPCRegion =
3954         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3955     OMPLexicalScope Scope(*this, S, OMPD_unknown);
3956     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
3957                                             CopyprivateVars, DestExprs,
3958                                             SrcExprs, AssignmentOps);
3959   }
3960   // Emit an implicit barrier at the end (to avoid data race on firstprivate
3961   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
3962   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
3963     CGM.getOpenMPRuntime().emitBarrierCall(
3964         *this, S.getBeginLoc(),
3965         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
3966   }
3967   // Check for outer lastprivate conditional update.
3968   checkForLastprivateConditionalUpdate(*this, S);
3969 }
3970 
3971 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
3972   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3973     Action.Enter(CGF);
3974     CGF.EmitStmt(S.getRawStmt());
3975   };
3976   CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc());
3977 }
3978 
3979 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
3980   if (CGM.getLangOpts().OpenMPIRBuilder) {
3981     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
3982     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3983 
3984     const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt();
3985 
3986     auto FiniCB = [this](InsertPointTy IP) {
3987       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
3988     };
3989 
3990     auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP,
3991                                                   InsertPointTy CodeGenIP,
3992                                                   llvm::BasicBlock &FiniBB) {
3993       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
3994       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt,
3995                                              CodeGenIP, FiniBB);
3996     };
3997 
3998     LexicalScope Scope(*this, S.getSourceRange());
3999     EmitStopPoint(&S);
4000     Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB));
4001 
4002     return;
4003   }
4004   LexicalScope Scope(*this, S.getSourceRange());
4005   EmitStopPoint(&S);
4006   emitMaster(*this, S);
4007 }
4008 
4009 static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
4010   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4011     Action.Enter(CGF);
4012     CGF.EmitStmt(S.getRawStmt());
4013   };
4014   Expr *Filter = nullptr;
4015   if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4016     Filter = FilterClause->getThreadID();
4017   CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(),
4018                                               Filter);
4019 }
4020 
4021 void CodeGenFunction::EmitOMPMaskedDirective(const OMPMaskedDirective &S) {
4022   if (CGM.getLangOpts().OpenMPIRBuilder) {
4023     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4024     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4025 
4026     const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt();
4027     const Expr *Filter = nullptr;
4028     if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>())
4029       Filter = FilterClause->getThreadID();
4030     llvm::Value *FilterVal = Filter
4031                                  ? EmitScalarExpr(Filter, CGM.Int32Ty)
4032                                  : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0);
4033 
4034     auto FiniCB = [this](InsertPointTy IP) {
4035       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4036     };
4037 
4038     auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP,
4039                                                   InsertPointTy CodeGenIP,
4040                                                   llvm::BasicBlock &FiniBB) {
4041       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4042       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MaskedRegionBodyStmt,
4043                                              CodeGenIP, FiniBB);
4044     };
4045 
4046     LexicalScope Scope(*this, S.getSourceRange());
4047     EmitStopPoint(&S);
4048     Builder.restoreIP(
4049         OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal));
4050 
4051     return;
4052   }
4053   LexicalScope Scope(*this, S.getSourceRange());
4054   EmitStopPoint(&S);
4055   emitMasked(*this, S);
4056 }
4057 
4058 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
4059   if (CGM.getLangOpts().OpenMPIRBuilder) {
4060     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
4061     using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4062 
4063     const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt();
4064     const Expr *Hint = nullptr;
4065     if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4066       Hint = HintClause->getHint();
4067 
4068     // TODO: This is slightly different from what's currently being done in
4069     // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything
4070     // about typing is final.
4071     llvm::Value *HintInst = nullptr;
4072     if (Hint)
4073       HintInst =
4074           Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false);
4075 
4076     auto FiniCB = [this](InsertPointTy IP) {
4077       OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
4078     };
4079 
4080     auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP,
4081                                                     InsertPointTy CodeGenIP,
4082                                                     llvm::BasicBlock &FiniBB) {
4083       OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB);
4084       OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt,
4085                                              CodeGenIP, FiniBB);
4086     };
4087 
4088     LexicalScope Scope(*this, S.getSourceRange());
4089     EmitStopPoint(&S);
4090     Builder.restoreIP(OMPBuilder.createCritical(
4091         Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(),
4092         HintInst));
4093 
4094     return;
4095   }
4096 
4097   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4098     Action.Enter(CGF);
4099     CGF.EmitStmt(S.getAssociatedStmt());
4100   };
4101   const Expr *Hint = nullptr;
4102   if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
4103     Hint = HintClause->getHint();
4104   LexicalScope Scope(*this, S.getSourceRange());
4105   EmitStopPoint(&S);
4106   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
4107                                             S.getDirectiveName().getAsString(),
4108                                             CodeGen, S.getBeginLoc(), Hint);
4109 }
4110 
4111 void CodeGenFunction::EmitOMPParallelForDirective(
4112     const OMPParallelForDirective &S) {
4113   // Emit directive as a combined directive that consists of two implicit
4114   // directives: 'parallel' with 'for' directive.
4115   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4116     Action.Enter(CGF);
4117     (void)emitWorksharingDirective(CGF, S, S.hasCancel());
4118   };
4119   {
4120     if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4121                      [](const OMPReductionClause *C) {
4122                        return C->getModifier() == OMPC_REDUCTION_inscan;
4123                      })) {
4124       const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4125         CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4126         CGCapturedStmtInfo CGSI(CR_OpenMP);
4127         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4128         OMPLoopScope LoopScope(CGF, S);
4129         return CGF.EmitScalarExpr(S.getNumIterations());
4130       };
4131       emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4132     }
4133     auto LPCRegion =
4134         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4135     emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
4136                                    emitEmptyBoundParameters);
4137   }
4138   // Check for outer lastprivate conditional update.
4139   checkForLastprivateConditionalUpdate(*this, S);
4140 }
4141 
4142 void CodeGenFunction::EmitOMPParallelForSimdDirective(
4143     const OMPParallelForSimdDirective &S) {
4144   // Emit directive as a combined directive that consists of two implicit
4145   // directives: 'parallel' with 'for' directive.
4146   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4147     Action.Enter(CGF);
4148     (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
4149   };
4150   {
4151     if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(),
4152                      [](const OMPReductionClause *C) {
4153                        return C->getModifier() == OMPC_REDUCTION_inscan;
4154                      })) {
4155       const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) {
4156         CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF);
4157         CGCapturedStmtInfo CGSI(CR_OpenMP);
4158         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI);
4159         OMPLoopScope LoopScope(CGF, S);
4160         return CGF.EmitScalarExpr(S.getNumIterations());
4161       };
4162       emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen);
4163     }
4164     auto LPCRegion =
4165         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4166     emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen,
4167                                    emitEmptyBoundParameters);
4168   }
4169   // Check for outer lastprivate conditional update.
4170   checkForLastprivateConditionalUpdate(*this, S);
4171 }
4172 
4173 void CodeGenFunction::EmitOMPParallelMasterDirective(
4174     const OMPParallelMasterDirective &S) {
4175   // Emit directive as a combined directive that consists of two implicit
4176   // directives: 'parallel' with 'master' directive.
4177   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4178     Action.Enter(CGF);
4179     OMPPrivateScope PrivateScope(CGF);
4180     bool Copyins = CGF.EmitOMPCopyinClause(S);
4181     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4182     if (Copyins) {
4183       // Emit implicit barrier to synchronize threads and avoid data races on
4184       // propagation master's thread values of threadprivate variables to local
4185       // instances of that variables of all other implicit threads.
4186       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
4187           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
4188           /*ForceSimpleCall=*/true);
4189     }
4190     CGF.EmitOMPPrivateClause(S, PrivateScope);
4191     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4192     (void)PrivateScope.Privatize();
4193     emitMaster(CGF, S);
4194     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
4195   };
4196   {
4197     auto LPCRegion =
4198         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4199     emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
4200                                    emitEmptyBoundParameters);
4201     emitPostUpdateForReductionClause(*this, S,
4202                                      [](CodeGenFunction &) { return nullptr; });
4203   }
4204   // Check for outer lastprivate conditional update.
4205   checkForLastprivateConditionalUpdate(*this, S);
4206 }
4207 
4208 void CodeGenFunction::EmitOMPParallelSectionsDirective(
4209     const OMPParallelSectionsDirective &S) {
4210   // Emit directive as a combined directive that consists of two implicit
4211   // directives: 'parallel' with 'sections' directive.
4212   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4213     Action.Enter(CGF);
4214     CGF.EmitSections(S);
4215   };
4216   {
4217     auto LPCRegion =
4218         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4219     emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
4220                                    emitEmptyBoundParameters);
4221   }
4222   // Check for outer lastprivate conditional update.
4223   checkForLastprivateConditionalUpdate(*this, S);
4224 }
4225 
4226 namespace {
4227 /// Get the list of variables declared in the context of the untied tasks.
4228 class CheckVarsEscapingUntiedTaskDeclContext final
4229     : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> {
4230   llvm::SmallVector<const VarDecl *, 4> PrivateDecls;
4231 
4232 public:
4233   explicit CheckVarsEscapingUntiedTaskDeclContext() = default;
4234   virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default;
4235   void VisitDeclStmt(const DeclStmt *S) {
4236     if (!S)
4237       return;
4238     // Need to privatize only local vars, static locals can be processed as is.
4239     for (const Decl *D : S->decls()) {
4240       if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
4241         if (VD->hasLocalStorage())
4242           PrivateDecls.push_back(VD);
4243     }
4244   }
4245   void VisitOMPExecutableDirective(const OMPExecutableDirective *) { return; }
4246   void VisitCapturedStmt(const CapturedStmt *) { return; }
4247   void VisitLambdaExpr(const LambdaExpr *) { return; }
4248   void VisitBlockExpr(const BlockExpr *) { return; }
4249   void VisitStmt(const Stmt *S) {
4250     if (!S)
4251       return;
4252     for (const Stmt *Child : S->children())
4253       if (Child)
4254         Visit(Child);
4255   }
4256 
4257   /// Swaps list of vars with the provided one.
4258   ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; }
4259 };
4260 } // anonymous namespace
4261 
4262 void CodeGenFunction::EmitOMPTaskBasedDirective(
4263     const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
4264     const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
4265     OMPTaskDataTy &Data) {
4266   // Emit outlined function for task construct.
4267   const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
4268   auto I = CS->getCapturedDecl()->param_begin();
4269   auto PartId = std::next(I);
4270   auto TaskT = std::next(I, 4);
4271   // Check if the task is final
4272   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
4273     // If the condition constant folds and can be elided, try to avoid emitting
4274     // the condition and the dead arm of the if/else.
4275     const Expr *Cond = Clause->getCondition();
4276     bool CondConstant;
4277     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
4278       Data.Final.setInt(CondConstant);
4279     else
4280       Data.Final.setPointer(EvaluateExprAsBool(Cond));
4281   } else {
4282     // By default the task is not final.
4283     Data.Final.setInt(/*IntVal=*/false);
4284   }
4285   // Check if the task has 'priority' clause.
4286   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
4287     const Expr *Prio = Clause->getPriority();
4288     Data.Priority.setInt(/*IntVal=*/true);
4289     Data.Priority.setPointer(EmitScalarConversion(
4290         EmitScalarExpr(Prio), Prio->getType(),
4291         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4292         Prio->getExprLoc()));
4293   }
4294   // The first function argument for tasks is a thread id, the second one is a
4295   // part id (0 for tied tasks, >=0 for untied task).
4296   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
4297   // Get list of private variables.
4298   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
4299     auto IRef = C->varlist_begin();
4300     for (const Expr *IInit : C->private_copies()) {
4301       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4302       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4303         Data.PrivateVars.push_back(*IRef);
4304         Data.PrivateCopies.push_back(IInit);
4305       }
4306       ++IRef;
4307     }
4308   }
4309   EmittedAsPrivate.clear();
4310   // Get list of firstprivate variables.
4311   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
4312     auto IRef = C->varlist_begin();
4313     auto IElemInitRef = C->inits().begin();
4314     for (const Expr *IInit : C->private_copies()) {
4315       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4316       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4317         Data.FirstprivateVars.push_back(*IRef);
4318         Data.FirstprivateCopies.push_back(IInit);
4319         Data.FirstprivateInits.push_back(*IElemInitRef);
4320       }
4321       ++IRef;
4322       ++IElemInitRef;
4323     }
4324   }
4325   // Get list of lastprivate variables (for taskloops).
4326   llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
4327   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
4328     auto IRef = C->varlist_begin();
4329     auto ID = C->destination_exprs().begin();
4330     for (const Expr *IInit : C->private_copies()) {
4331       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
4332       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
4333         Data.LastprivateVars.push_back(*IRef);
4334         Data.LastprivateCopies.push_back(IInit);
4335       }
4336       LastprivateDstsOrigs.insert(
4337           std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
4338                          cast<DeclRefExpr>(*IRef)));
4339       ++IRef;
4340       ++ID;
4341     }
4342   }
4343   SmallVector<const Expr *, 4> LHSs;
4344   SmallVector<const Expr *, 4> RHSs;
4345   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
4346     Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
4347     Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
4348     Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
4349     Data.ReductionOps.append(C->reduction_ops().begin(),
4350                              C->reduction_ops().end());
4351     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4352     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4353   }
4354   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
4355       *this, S.getBeginLoc(), LHSs, RHSs, Data);
4356   // Build list of dependences.
4357   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4358     OMPTaskDataTy::DependData &DD =
4359         Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4360     DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4361   }
4362   // Get list of local vars for untied tasks.
4363   if (!Data.Tied) {
4364     CheckVarsEscapingUntiedTaskDeclContext Checker;
4365     Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt());
4366     Data.PrivateLocals.append(Checker.getPrivateDecls().begin(),
4367                               Checker.getPrivateDecls().end());
4368   }
4369   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
4370                     CapturedRegion](CodeGenFunction &CGF,
4371                                     PrePostActionTy &Action) {
4372     llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
4373                     std::pair<Address, Address>>
4374         UntiedLocalVars;
4375     // Set proper addresses for generated private copies.
4376     OMPPrivateScope Scope(CGF);
4377     llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs;
4378     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
4379         !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) {
4380       enum { PrivatesParam = 2, CopyFnParam = 3 };
4381       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
4382           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
4383       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
4384           CS->getCapturedDecl()->getParam(PrivatesParam)));
4385       // Map privates.
4386       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
4387       llvm::SmallVector<llvm::Value *, 16> CallArgs;
4388       llvm::SmallVector<llvm::Type *, 4> ParamTypes;
4389       CallArgs.push_back(PrivatesPtr);
4390       ParamTypes.push_back(PrivatesPtr->getType());
4391       for (const Expr *E : Data.PrivateVars) {
4392         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4393         Address PrivatePtr = CGF.CreateMemTemp(
4394             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
4395         PrivatePtrs.emplace_back(VD, PrivatePtr);
4396         CallArgs.push_back(PrivatePtr.getPointer());
4397         ParamTypes.push_back(PrivatePtr.getType());
4398       }
4399       for (const Expr *E : Data.FirstprivateVars) {
4400         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4401         Address PrivatePtr =
4402             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4403                               ".firstpriv.ptr.addr");
4404         PrivatePtrs.emplace_back(VD, PrivatePtr);
4405         FirstprivatePtrs.emplace_back(VD, PrivatePtr);
4406         CallArgs.push_back(PrivatePtr.getPointer());
4407         ParamTypes.push_back(PrivatePtr.getType());
4408       }
4409       for (const Expr *E : Data.LastprivateVars) {
4410         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4411         Address PrivatePtr =
4412             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4413                               ".lastpriv.ptr.addr");
4414         PrivatePtrs.emplace_back(VD, PrivatePtr);
4415         CallArgs.push_back(PrivatePtr.getPointer());
4416         ParamTypes.push_back(PrivatePtr.getType());
4417       }
4418       for (const VarDecl *VD : Data.PrivateLocals) {
4419         QualType Ty = VD->getType().getNonReferenceType();
4420         if (VD->getType()->isLValueReferenceType())
4421           Ty = CGF.getContext().getPointerType(Ty);
4422         if (isAllocatableDecl(VD))
4423           Ty = CGF.getContext().getPointerType(Ty);
4424         Address PrivatePtr = CGF.CreateMemTemp(
4425             CGF.getContext().getPointerType(Ty), ".local.ptr.addr");
4426         auto Result = UntiedLocalVars.insert(
4427             std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid())));
4428         // If key exists update in place.
4429         if (Result.second == false)
4430           *Result.first = std::make_pair(
4431               VD, std::make_pair(PrivatePtr, Address::invalid()));
4432         CallArgs.push_back(PrivatePtr.getPointer());
4433         ParamTypes.push_back(PrivatePtr.getType());
4434       }
4435       auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
4436                                                ParamTypes, /*isVarArg=*/false);
4437       CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4438           CopyFn, CopyFnTy->getPointerTo());
4439       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4440           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
4441       for (const auto &Pair : LastprivateDstsOrigs) {
4442         const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
4443         DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
4444                         /*RefersToEnclosingVariableOrCapture=*/
4445                             CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
4446                         Pair.second->getType(), VK_LValue,
4447                         Pair.second->getExprLoc());
4448         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
4449           return CGF.EmitLValue(&DRE).getAddress(CGF);
4450         });
4451       }
4452       for (const auto &Pair : PrivatePtrs) {
4453         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4454                             CGF.getContext().getDeclAlign(Pair.first));
4455         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
4456       }
4457       // Adjust mapping for internal locals by mapping actual memory instead of
4458       // a pointer to this memory.
4459       for (auto &Pair : UntiedLocalVars) {
4460         if (isAllocatableDecl(Pair.first)) {
4461           llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4462           Address Replacement(Ptr, CGF.getPointerAlign());
4463           Pair.second.first = Replacement;
4464           Ptr = CGF.Builder.CreateLoad(Replacement);
4465           Replacement = Address(Ptr, CGF.getContext().getDeclAlign(Pair.first));
4466           Pair.second.second = Replacement;
4467         } else {
4468           llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first);
4469           Address Replacement(Ptr, CGF.getContext().getDeclAlign(Pair.first));
4470           Pair.second.first = Replacement;
4471         }
4472       }
4473     }
4474     if (Data.Reductions) {
4475       OMPPrivateScope FirstprivateScope(CGF);
4476       for (const auto &Pair : FirstprivatePtrs) {
4477         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4478                             CGF.getContext().getDeclAlign(Pair.first));
4479         FirstprivateScope.addPrivate(Pair.first,
4480                                      [Replacement]() { return Replacement; });
4481       }
4482       (void)FirstprivateScope.Privatize();
4483       OMPLexicalScope LexScope(CGF, S, CapturedRegion);
4484       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars,
4485                              Data.ReductionCopies, Data.ReductionOps);
4486       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
4487           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
4488       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
4489         RedCG.emitSharedOrigLValue(CGF, Cnt);
4490         RedCG.emitAggregateType(CGF, Cnt);
4491         // FIXME: This must removed once the runtime library is fixed.
4492         // Emit required threadprivate variables for
4493         // initializer/combiner/finalizer.
4494         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
4495                                                            RedCG, Cnt);
4496         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
4497             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
4498         Replacement =
4499             Address(CGF.EmitScalarConversion(
4500                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
4501                         CGF.getContext().getPointerType(
4502                             Data.ReductionCopies[Cnt]->getType()),
4503                         Data.ReductionCopies[Cnt]->getExprLoc()),
4504                     Replacement.getAlignment());
4505         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
4506         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
4507                          [Replacement]() { return Replacement; });
4508       }
4509     }
4510     // Privatize all private variables except for in_reduction items.
4511     (void)Scope.Privatize();
4512     SmallVector<const Expr *, 4> InRedVars;
4513     SmallVector<const Expr *, 4> InRedPrivs;
4514     SmallVector<const Expr *, 4> InRedOps;
4515     SmallVector<const Expr *, 4> TaskgroupDescriptors;
4516     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
4517       auto IPriv = C->privates().begin();
4518       auto IRed = C->reduction_ops().begin();
4519       auto ITD = C->taskgroup_descriptors().begin();
4520       for (const Expr *Ref : C->varlists()) {
4521         InRedVars.emplace_back(Ref);
4522         InRedPrivs.emplace_back(*IPriv);
4523         InRedOps.emplace_back(*IRed);
4524         TaskgroupDescriptors.emplace_back(*ITD);
4525         std::advance(IPriv, 1);
4526         std::advance(IRed, 1);
4527         std::advance(ITD, 1);
4528       }
4529     }
4530     // Privatize in_reduction items here, because taskgroup descriptors must be
4531     // privatized earlier.
4532     OMPPrivateScope InRedScope(CGF);
4533     if (!InRedVars.empty()) {
4534       ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps);
4535       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
4536         RedCG.emitSharedOrigLValue(CGF, Cnt);
4537         RedCG.emitAggregateType(CGF, Cnt);
4538         // The taskgroup descriptor variable is always implicit firstprivate and
4539         // privatized already during processing of the firstprivates.
4540         // FIXME: This must removed once the runtime library is fixed.
4541         // Emit required threadprivate variables for
4542         // initializer/combiner/finalizer.
4543         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
4544                                                            RedCG, Cnt);
4545         llvm::Value *ReductionsPtr;
4546         if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) {
4547           ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr),
4548                                                TRExpr->getExprLoc());
4549         } else {
4550           ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4551         }
4552         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
4553             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
4554         Replacement = Address(
4555             CGF.EmitScalarConversion(
4556                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
4557                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
4558                 InRedPrivs[Cnt]->getExprLoc()),
4559             Replacement.getAlignment());
4560         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
4561         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
4562                               [Replacement]() { return Replacement; });
4563       }
4564     }
4565     (void)InRedScope.Privatize();
4566 
4567     CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF,
4568                                                              UntiedLocalVars);
4569     Action.Enter(CGF);
4570     BodyGen(CGF);
4571   };
4572   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
4573       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
4574       Data.NumberOfParts);
4575   OMPLexicalScope Scope(*this, S, llvm::None,
4576                         !isOpenMPParallelDirective(S.getDirectiveKind()) &&
4577                             !isOpenMPSimdDirective(S.getDirectiveKind()));
4578   TaskGen(*this, OutlinedFn, Data);
4579 }
4580 
4581 static ImplicitParamDecl *
4582 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
4583                                   QualType Ty, CapturedDecl *CD,
4584                                   SourceLocation Loc) {
4585   auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
4586                                            ImplicitParamDecl::Other);
4587   auto *OrigRef = DeclRefExpr::Create(
4588       C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
4589       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
4590   auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
4591                                               ImplicitParamDecl::Other);
4592   auto *PrivateRef = DeclRefExpr::Create(
4593       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
4594       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
4595   QualType ElemType = C.getBaseElementType(Ty);
4596   auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
4597                                            ImplicitParamDecl::Other);
4598   auto *InitRef = DeclRefExpr::Create(
4599       C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
4600       /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
4601   PrivateVD->setInitStyle(VarDecl::CInit);
4602   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
4603                                               InitRef, /*BasePath=*/nullptr,
4604                                               VK_PRValue, FPOptionsOverride()));
4605   Data.FirstprivateVars.emplace_back(OrigRef);
4606   Data.FirstprivateCopies.emplace_back(PrivateRef);
4607   Data.FirstprivateInits.emplace_back(InitRef);
4608   return OrigVD;
4609 }
4610 
4611 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
4612     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
4613     OMPTargetDataInfo &InputInfo) {
4614   // Emit outlined function for task construct.
4615   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
4616   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4617   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4618   auto I = CS->getCapturedDecl()->param_begin();
4619   auto PartId = std::next(I);
4620   auto TaskT = std::next(I, 4);
4621   OMPTaskDataTy Data;
4622   // The task is not final.
4623   Data.Final.setInt(/*IntVal=*/false);
4624   // Get list of firstprivate variables.
4625   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
4626     auto IRef = C->varlist_begin();
4627     auto IElemInitRef = C->inits().begin();
4628     for (auto *IInit : C->private_copies()) {
4629       Data.FirstprivateVars.push_back(*IRef);
4630       Data.FirstprivateCopies.push_back(IInit);
4631       Data.FirstprivateInits.push_back(*IElemInitRef);
4632       ++IRef;
4633       ++IElemInitRef;
4634     }
4635   }
4636   OMPPrivateScope TargetScope(*this);
4637   VarDecl *BPVD = nullptr;
4638   VarDecl *PVD = nullptr;
4639   VarDecl *SVD = nullptr;
4640   VarDecl *MVD = nullptr;
4641   if (InputInfo.NumberOfTargetItems > 0) {
4642     auto *CD = CapturedDecl::Create(
4643         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
4644     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
4645     QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType(
4646         getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
4647         /*IndexTypeQuals=*/0);
4648     BPVD = createImplicitFirstprivateForType(
4649         getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4650     PVD = createImplicitFirstprivateForType(
4651         getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4652     QualType SizesType = getContext().getConstantArrayType(
4653         getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
4654         ArrSize, nullptr, ArrayType::Normal,
4655         /*IndexTypeQuals=*/0);
4656     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
4657                                             S.getBeginLoc());
4658     TargetScope.addPrivate(
4659         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
4660     TargetScope.addPrivate(PVD,
4661                            [&InputInfo]() { return InputInfo.PointersArray; });
4662     TargetScope.addPrivate(SVD,
4663                            [&InputInfo]() { return InputInfo.SizesArray; });
4664     // If there is no user-defined mapper, the mapper array will be nullptr. In
4665     // this case, we don't need to privatize it.
4666     if (!dyn_cast_or_null<llvm::ConstantPointerNull>(
4667             InputInfo.MappersArray.getPointer())) {
4668       MVD = createImplicitFirstprivateForType(
4669           getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
4670       TargetScope.addPrivate(MVD,
4671                              [&InputInfo]() { return InputInfo.MappersArray; });
4672     }
4673   }
4674   (void)TargetScope.Privatize();
4675   // Build list of dependences.
4676   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
4677     OMPTaskDataTy::DependData &DD =
4678         Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier());
4679     DD.DepExprs.append(C->varlist_begin(), C->varlist_end());
4680   }
4681   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD,
4682                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
4683     // Set proper addresses for generated private copies.
4684     OMPPrivateScope Scope(CGF);
4685     if (!Data.FirstprivateVars.empty()) {
4686       enum { PrivatesParam = 2, CopyFnParam = 3 };
4687       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
4688           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
4689       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
4690           CS->getCapturedDecl()->getParam(PrivatesParam)));
4691       // Map privates.
4692       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
4693       llvm::SmallVector<llvm::Value *, 16> CallArgs;
4694       llvm::SmallVector<llvm::Type *, 4> ParamTypes;
4695       CallArgs.push_back(PrivatesPtr);
4696       ParamTypes.push_back(PrivatesPtr->getType());
4697       for (const Expr *E : Data.FirstprivateVars) {
4698         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4699         Address PrivatePtr =
4700             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
4701                               ".firstpriv.ptr.addr");
4702         PrivatePtrs.emplace_back(VD, PrivatePtr);
4703         CallArgs.push_back(PrivatePtr.getPointer());
4704         ParamTypes.push_back(PrivatePtr.getType());
4705       }
4706       auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(),
4707                                                ParamTypes, /*isVarArg=*/false);
4708       CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4709           CopyFn, CopyFnTy->getPointerTo());
4710       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4711           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
4712       for (const auto &Pair : PrivatePtrs) {
4713         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
4714                             CGF.getContext().getDeclAlign(Pair.first));
4715         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
4716       }
4717     }
4718     // Privatize all private variables except for in_reduction items.
4719     (void)Scope.Privatize();
4720     if (InputInfo.NumberOfTargetItems > 0) {
4721       InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
4722           CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
4723       InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
4724           CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
4725       InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
4726           CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
4727       // If MVD is nullptr, the mapper array is not privatized
4728       if (MVD)
4729         InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
4730             CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
4731     }
4732 
4733     Action.Enter(CGF);
4734     OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
4735     BodyGen(CGF);
4736   };
4737   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
4738       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
4739       Data.NumberOfParts);
4740   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
4741   IntegerLiteral IfCond(getContext(), TrueOrFalse,
4742                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4743                         SourceLocation());
4744 
4745   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
4746                                       SharedsTy, CapturedStruct, &IfCond, Data);
4747 }
4748 
4749 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
4750   // Emit outlined function for task construct.
4751   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
4752   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
4753   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
4754   const Expr *IfCond = nullptr;
4755   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4756     if (C->getNameModifier() == OMPD_unknown ||
4757         C->getNameModifier() == OMPD_task) {
4758       IfCond = C->getCondition();
4759       break;
4760     }
4761   }
4762 
4763   OMPTaskDataTy Data;
4764   // Check if we should emit tied or untied task.
4765   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
4766   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
4767     CGF.EmitStmt(CS->getCapturedStmt());
4768   };
4769   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
4770                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
4771                             const OMPTaskDataTy &Data) {
4772     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
4773                                             SharedsTy, CapturedStruct, IfCond,
4774                                             Data);
4775   };
4776   auto LPCRegion =
4777       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
4778   EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
4779 }
4780 
4781 void CodeGenFunction::EmitOMPTaskyieldDirective(
4782     const OMPTaskyieldDirective &S) {
4783   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
4784 }
4785 
4786 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
4787   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
4788 }
4789 
4790 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
4791   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
4792 }
4793 
4794 void CodeGenFunction::EmitOMPTaskgroupDirective(
4795     const OMPTaskgroupDirective &S) {
4796   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4797     Action.Enter(CGF);
4798     if (const Expr *E = S.getReductionRef()) {
4799       SmallVector<const Expr *, 4> LHSs;
4800       SmallVector<const Expr *, 4> RHSs;
4801       OMPTaskDataTy Data;
4802       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
4803         Data.ReductionVars.append(C->varlist_begin(), C->varlist_end());
4804         Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end());
4805         Data.ReductionCopies.append(C->privates().begin(), C->privates().end());
4806         Data.ReductionOps.append(C->reduction_ops().begin(),
4807                                  C->reduction_ops().end());
4808         LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4809         RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4810       }
4811       llvm::Value *ReductionDesc =
4812           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
4813                                                            LHSs, RHSs, Data);
4814       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4815       CGF.EmitVarDecl(*VD);
4816       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
4817                             /*Volatile=*/false, E->getType());
4818     }
4819     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4820   };
4821   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4822   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
4823 }
4824 
4825 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
4826   llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
4827                                 ? llvm::AtomicOrdering::NotAtomic
4828                                 : llvm::AtomicOrdering::AcquireRelease;
4829   CGM.getOpenMPRuntime().emitFlush(
4830       *this,
4831       [&S]() -> ArrayRef<const Expr *> {
4832         if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
4833           return llvm::makeArrayRef(FlushClause->varlist_begin(),
4834                                     FlushClause->varlist_end());
4835         return llvm::None;
4836       }(),
4837       S.getBeginLoc(), AO);
4838 }
4839 
4840 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) {
4841   const auto *DO = S.getSingleClause<OMPDepobjClause>();
4842   LValue DOLVal = EmitLValue(DO->getDepobj());
4843   if (const auto *DC = S.getSingleClause<OMPDependClause>()) {
4844     OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(),
4845                                            DC->getModifier());
4846     Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end());
4847     Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause(
4848         *this, Dependencies, DC->getBeginLoc());
4849     EmitStoreOfScalar(DepAddr.getPointer(), DOLVal);
4850     return;
4851   }
4852   if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) {
4853     CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc());
4854     return;
4855   }
4856   if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) {
4857     CGM.getOpenMPRuntime().emitUpdateClause(
4858         *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc());
4859     return;
4860   }
4861 }
4862 
4863 void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) {
4864   if (!OMPParentLoopDirectiveForScan)
4865     return;
4866   const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan;
4867   bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>();
4868   SmallVector<const Expr *, 4> Shareds;
4869   SmallVector<const Expr *, 4> Privates;
4870   SmallVector<const Expr *, 4> LHSs;
4871   SmallVector<const Expr *, 4> RHSs;
4872   SmallVector<const Expr *, 4> ReductionOps;
4873   SmallVector<const Expr *, 4> CopyOps;
4874   SmallVector<const Expr *, 4> CopyArrayTemps;
4875   SmallVector<const Expr *, 4> CopyArrayElems;
4876   for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) {
4877     if (C->getModifier() != OMPC_REDUCTION_inscan)
4878       continue;
4879     Shareds.append(C->varlist_begin(), C->varlist_end());
4880     Privates.append(C->privates().begin(), C->privates().end());
4881     LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
4882     RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
4883     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
4884     CopyOps.append(C->copy_ops().begin(), C->copy_ops().end());
4885     CopyArrayTemps.append(C->copy_array_temps().begin(),
4886                           C->copy_array_temps().end());
4887     CopyArrayElems.append(C->copy_array_elems().begin(),
4888                           C->copy_array_elems().end());
4889   }
4890   if (ParentDir.getDirectiveKind() == OMPD_simd ||
4891       (getLangOpts().OpenMPSimd &&
4892        isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) {
4893     // For simd directive and simd-based directives in simd only mode, use the
4894     // following codegen:
4895     // int x = 0;
4896     // #pragma omp simd reduction(inscan, +: x)
4897     // for (..) {
4898     //   <first part>
4899     //   #pragma omp scan inclusive(x)
4900     //   <second part>
4901     //  }
4902     // is transformed to:
4903     // int x = 0;
4904     // for (..) {
4905     //   int x_priv = 0;
4906     //   <first part>
4907     //   x = x_priv + x;
4908     //   x_priv = x;
4909     //   <second part>
4910     // }
4911     // and
4912     // int x = 0;
4913     // #pragma omp simd reduction(inscan, +: x)
4914     // for (..) {
4915     //   <first part>
4916     //   #pragma omp scan exclusive(x)
4917     //   <second part>
4918     // }
4919     // to
4920     // int x = 0;
4921     // for (..) {
4922     //   int x_priv = 0;
4923     //   <second part>
4924     //   int temp = x;
4925     //   x = x_priv + x;
4926     //   x_priv = temp;
4927     //   <first part>
4928     // }
4929     llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce");
4930     EmitBranch(IsInclusive
4931                    ? OMPScanReduce
4932                    : BreakContinueStack.back().ContinueBlock.getBlock());
4933     EmitBlock(OMPScanDispatch);
4934     {
4935       // New scope for correct construction/destruction of temp variables for
4936       // exclusive scan.
4937       LexicalScope Scope(*this, S.getSourceRange());
4938       EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock);
4939       EmitBlock(OMPScanReduce);
4940       if (!IsInclusive) {
4941         // Create temp var and copy LHS value to this temp value.
4942         // TMP = LHS;
4943         for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
4944           const Expr *PrivateExpr = Privates[I];
4945           const Expr *TempExpr = CopyArrayTemps[I];
4946           EmitAutoVarDecl(
4947               *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl()));
4948           LValue DestLVal = EmitLValue(TempExpr);
4949           LValue SrcLVal = EmitLValue(LHSs[I]);
4950           EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
4951                       SrcLVal.getAddress(*this),
4952                       cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
4953                       cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
4954                       CopyOps[I]);
4955         }
4956       }
4957       CGM.getOpenMPRuntime().emitReduction(
4958           *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps,
4959           {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd});
4960       for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
4961         const Expr *PrivateExpr = Privates[I];
4962         LValue DestLVal;
4963         LValue SrcLVal;
4964         if (IsInclusive) {
4965           DestLVal = EmitLValue(RHSs[I]);
4966           SrcLVal = EmitLValue(LHSs[I]);
4967         } else {
4968           const Expr *TempExpr = CopyArrayTemps[I];
4969           DestLVal = EmitLValue(RHSs[I]);
4970           SrcLVal = EmitLValue(TempExpr);
4971         }
4972         EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
4973                     SrcLVal.getAddress(*this),
4974                     cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
4975                     cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
4976                     CopyOps[I]);
4977       }
4978     }
4979     EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock);
4980     OMPScanExitBlock = IsInclusive
4981                            ? BreakContinueStack.back().ContinueBlock.getBlock()
4982                            : OMPScanReduce;
4983     EmitBlock(OMPAfterScanBlock);
4984     return;
4985   }
4986   if (!IsInclusive) {
4987     EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
4988     EmitBlock(OMPScanExitBlock);
4989   }
4990   if (OMPFirstScanLoop) {
4991     // Emit buffer[i] = red; at the end of the input phase.
4992     const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
4993                              .getIterationVariable()
4994                              ->IgnoreParenImpCasts();
4995     LValue IdxLVal = EmitLValue(IVExpr);
4996     llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
4997     IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
4998     for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
4999       const Expr *PrivateExpr = Privates[I];
5000       const Expr *OrigExpr = Shareds[I];
5001       const Expr *CopyArrayElem = CopyArrayElems[I];
5002       OpaqueValueMapping IdxMapping(
5003           *this,
5004           cast<OpaqueValueExpr>(
5005               cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5006           RValue::get(IdxVal));
5007       LValue DestLVal = EmitLValue(CopyArrayElem);
5008       LValue SrcLVal = EmitLValue(OrigExpr);
5009       EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5010                   SrcLVal.getAddress(*this),
5011                   cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5012                   cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5013                   CopyOps[I]);
5014     }
5015   }
5016   EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5017   if (IsInclusive) {
5018     EmitBlock(OMPScanExitBlock);
5019     EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock());
5020   }
5021   EmitBlock(OMPScanDispatch);
5022   if (!OMPFirstScanLoop) {
5023     // Emit red = buffer[i]; at the entrance to the scan phase.
5024     const auto *IVExpr = cast<OMPLoopDirective>(ParentDir)
5025                              .getIterationVariable()
5026                              ->IgnoreParenImpCasts();
5027     LValue IdxLVal = EmitLValue(IVExpr);
5028     llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc());
5029     IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false);
5030     llvm::BasicBlock *ExclusiveExitBB = nullptr;
5031     if (!IsInclusive) {
5032       llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec");
5033       ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit");
5034       llvm::Value *Cmp = Builder.CreateIsNull(IdxVal);
5035       Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB);
5036       EmitBlock(ContBB);
5037       // Use idx - 1 iteration for exclusive scan.
5038       IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1));
5039     }
5040     for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) {
5041       const Expr *PrivateExpr = Privates[I];
5042       const Expr *OrigExpr = Shareds[I];
5043       const Expr *CopyArrayElem = CopyArrayElems[I];
5044       OpaqueValueMapping IdxMapping(
5045           *this,
5046           cast<OpaqueValueExpr>(
5047               cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()),
5048           RValue::get(IdxVal));
5049       LValue SrcLVal = EmitLValue(CopyArrayElem);
5050       LValue DestLVal = EmitLValue(OrigExpr);
5051       EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this),
5052                   SrcLVal.getAddress(*this),
5053                   cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()),
5054                   cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()),
5055                   CopyOps[I]);
5056     }
5057     if (!IsInclusive) {
5058       EmitBlock(ExclusiveExitBB);
5059     }
5060   }
5061   EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock
5062                                                : OMPAfterScanBlock);
5063   EmitBlock(OMPAfterScanBlock);
5064 }
5065 
5066 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
5067                                             const CodeGenLoopTy &CodeGenLoop,
5068                                             Expr *IncExpr) {
5069   // Emit the loop iteration variable.
5070   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
5071   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
5072   EmitVarDecl(*IVDecl);
5073 
5074   // Emit the iterations count variable.
5075   // If it is not a variable, Sema decided to calculate iterations count on each
5076   // iteration (e.g., it is foldable into a constant).
5077   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5078     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5079     // Emit calculation of the iterations count.
5080     EmitIgnoredExpr(S.getCalcLastIteration());
5081   }
5082 
5083   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
5084 
5085   bool HasLastprivateClause = false;
5086   // Check pre-condition.
5087   {
5088     OMPLoopScope PreInitScope(*this, S);
5089     // Skip the entire loop if we don't meet the precondition.
5090     // If the condition constant folds and can be elided, avoid emitting the
5091     // whole loop.
5092     bool CondConstant;
5093     llvm::BasicBlock *ContBlock = nullptr;
5094     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5095       if (!CondConstant)
5096         return;
5097     } else {
5098       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
5099       ContBlock = createBasicBlock("omp.precond.end");
5100       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
5101                   getProfileCount(&S));
5102       EmitBlock(ThenBlock);
5103       incrementProfileCounter(&S);
5104     }
5105 
5106     emitAlignedClause(*this, S);
5107     // Emit 'then' code.
5108     {
5109       // Emit helper vars inits.
5110 
5111       LValue LB = EmitOMPHelperVar(
5112           *this, cast<DeclRefExpr>(
5113                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5114                           ? S.getCombinedLowerBoundVariable()
5115                           : S.getLowerBoundVariable())));
5116       LValue UB = EmitOMPHelperVar(
5117           *this, cast<DeclRefExpr>(
5118                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5119                           ? S.getCombinedUpperBoundVariable()
5120                           : S.getUpperBoundVariable())));
5121       LValue ST =
5122           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
5123       LValue IL =
5124           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
5125 
5126       OMPPrivateScope LoopScope(*this);
5127       if (EmitOMPFirstprivateClause(S, LoopScope)) {
5128         // Emit implicit barrier to synchronize threads and avoid data races
5129         // on initialization of firstprivate variables and post-update of
5130         // lastprivate variables.
5131         CGM.getOpenMPRuntime().emitBarrierCall(
5132             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
5133             /*ForceSimpleCall=*/true);
5134       }
5135       EmitOMPPrivateClause(S, LoopScope);
5136       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5137           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5138           !isOpenMPTeamsDirective(S.getDirectiveKind()))
5139         EmitOMPReductionClauseInit(S, LoopScope);
5140       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
5141       EmitOMPPrivateLoopCounters(S, LoopScope);
5142       (void)LoopScope.Privatize();
5143       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5144         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
5145 
5146       // Detect the distribute schedule kind and chunk.
5147       llvm::Value *Chunk = nullptr;
5148       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
5149       if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
5150         ScheduleKind = C->getDistScheduleKind();
5151         if (const Expr *Ch = C->getChunkSize()) {
5152           Chunk = EmitScalarExpr(Ch);
5153           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
5154                                        S.getIterationVariable()->getType(),
5155                                        S.getBeginLoc());
5156         }
5157       } else {
5158         // Default behaviour for dist_schedule clause.
5159         CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
5160             *this, S, ScheduleKind, Chunk);
5161       }
5162       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
5163       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
5164 
5165       // OpenMP [2.10.8, distribute Construct, Description]
5166       // If dist_schedule is specified, kind must be static. If specified,
5167       // iterations are divided into chunks of size chunk_size, chunks are
5168       // assigned to the teams of the league in a round-robin fashion in the
5169       // order of the team number. When no chunk_size is specified, the
5170       // iteration space is divided into chunks that are approximately equal
5171       // in size, and at most one chunk is distributed to each team of the
5172       // league. The size of the chunks is unspecified in this case.
5173       bool StaticChunked = RT.isStaticChunked(
5174           ScheduleKind, /* Chunked */ Chunk != nullptr) &&
5175           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
5176       if (RT.isStaticNonchunked(ScheduleKind,
5177                                 /* Chunked */ Chunk != nullptr) ||
5178           StaticChunked) {
5179         CGOpenMPRuntime::StaticRTInput StaticInit(
5180             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
5181             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
5182             StaticChunked ? Chunk : nullptr);
5183         RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
5184                                     StaticInit);
5185         JumpDest LoopExit =
5186             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
5187         // UB = min(UB, GlobalUB);
5188         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5189                             ? S.getCombinedEnsureUpperBound()
5190                             : S.getEnsureUpperBound());
5191         // IV = LB;
5192         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5193                             ? S.getCombinedInit()
5194                             : S.getInit());
5195 
5196         const Expr *Cond =
5197             isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
5198                 ? S.getCombinedCond()
5199                 : S.getCond();
5200 
5201         if (StaticChunked)
5202           Cond = S.getCombinedDistCond();
5203 
5204         // For static unchunked schedules generate:
5205         //
5206         //  1. For distribute alone, codegen
5207         //    while (idx <= UB) {
5208         //      BODY;
5209         //      ++idx;
5210         //    }
5211         //
5212         //  2. When combined with 'for' (e.g. as in 'distribute parallel for')
5213         //    while (idx <= UB) {
5214         //      <CodeGen rest of pragma>(LB, UB);
5215         //      idx += ST;
5216         //    }
5217         //
5218         // For static chunk one schedule generate:
5219         //
5220         // while (IV <= GlobalUB) {
5221         //   <CodeGen rest of pragma>(LB, UB);
5222         //   LB += ST;
5223         //   UB += ST;
5224         //   UB = min(UB, GlobalUB);
5225         //   IV = LB;
5226         // }
5227         //
5228         emitCommonSimdLoop(
5229             *this, S,
5230             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5231               if (isOpenMPSimdDirective(S.getDirectiveKind()))
5232                 CGF.EmitOMPSimdInit(S);
5233             },
5234             [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
5235              StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
5236               CGF.EmitOMPInnerLoop(
5237                   S, LoopScope.requiresCleanups(), Cond, IncExpr,
5238                   [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
5239                     CodeGenLoop(CGF, S, LoopExit);
5240                   },
5241                   [&S, StaticChunked](CodeGenFunction &CGF) {
5242                     if (StaticChunked) {
5243                       CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
5244                       CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
5245                       CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
5246                       CGF.EmitIgnoredExpr(S.getCombinedInit());
5247                     }
5248                   });
5249             });
5250         EmitBlock(LoopExit.getBlock());
5251         // Tell the runtime we are done.
5252         RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
5253       } else {
5254         // Emit the outer loop, which requests its work chunk [LB..UB] from
5255         // runtime and runs the inner loop to process it.
5256         const OMPLoopArguments LoopArguments = {
5257             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
5258             IL.getAddress(*this), Chunk};
5259         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
5260                                    CodeGenLoop);
5261       }
5262       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
5263         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
5264           return CGF.Builder.CreateIsNotNull(
5265               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5266         });
5267       }
5268       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
5269           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
5270           !isOpenMPTeamsDirective(S.getDirectiveKind())) {
5271         EmitOMPReductionClauseFinal(S, OMPD_simd);
5272         // Emit post-update of the reduction variables if IsLastIter != 0.
5273         emitPostUpdateForReductionClause(
5274             *this, S, [IL, &S](CodeGenFunction &CGF) {
5275               return CGF.Builder.CreateIsNotNull(
5276                   CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
5277             });
5278       }
5279       // Emit final copy of the lastprivate variables if IsLastIter != 0.
5280       if (HasLastprivateClause) {
5281         EmitOMPLastprivateClauseFinal(
5282             S, /*NoFinals=*/false,
5283             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
5284       }
5285     }
5286 
5287     // We're now done with the loop, so jump to the continuation block.
5288     if (ContBlock) {
5289       EmitBranch(ContBlock);
5290       EmitBlock(ContBlock, true);
5291     }
5292   }
5293 }
5294 
5295 void CodeGenFunction::EmitOMPDistributeDirective(
5296     const OMPDistributeDirective &S) {
5297   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5298     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
5299   };
5300   OMPLexicalScope Scope(*this, S, OMPD_unknown);
5301   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
5302 }
5303 
5304 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
5305                                                    const CapturedStmt *S,
5306                                                    SourceLocation Loc) {
5307   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
5308   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
5309   CGF.CapturedStmtInfo = &CapStmtInfo;
5310   llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
5311   Fn->setDoesNotRecurse();
5312   if (CGM.getCodeGenOpts().OptimizationLevel != 0)
5313     Fn->addFnAttr(llvm::Attribute::AlwaysInline);
5314   return Fn;
5315 }
5316 
5317 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
5318   if (S.hasClausesOfKind<OMPDependClause>()) {
5319     assert(!S.hasAssociatedStmt() &&
5320            "No associated statement must be in ordered depend construct.");
5321     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
5322       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
5323     return;
5324   }
5325   const auto *C = S.getSingleClause<OMPSIMDClause>();
5326   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
5327                                  PrePostActionTy &Action) {
5328     const CapturedStmt *CS = S.getInnermostCapturedStmt();
5329     if (C) {
5330       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
5331       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
5332       llvm::Function *OutlinedFn =
5333           emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
5334       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
5335                                                       OutlinedFn, CapturedVars);
5336     } else {
5337       Action.Enter(CGF);
5338       CGF.EmitStmt(CS->getCapturedStmt());
5339     }
5340   };
5341   OMPLexicalScope Scope(*this, S, OMPD_unknown);
5342   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
5343 }
5344 
5345 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
5346                                          QualType SrcType, QualType DestType,
5347                                          SourceLocation Loc) {
5348   assert(CGF.hasScalarEvaluationKind(DestType) &&
5349          "DestType must have scalar evaluation kind.");
5350   assert(!Val.isAggregate() && "Must be a scalar or complex.");
5351   return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
5352                                                    DestType, Loc)
5353                         : CGF.EmitComplexToScalarConversion(
5354                               Val.getComplexVal(), SrcType, DestType, Loc);
5355 }
5356 
5357 static CodeGenFunction::ComplexPairTy
5358 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
5359                       QualType DestType, SourceLocation Loc) {
5360   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
5361          "DestType must have complex evaluation kind.");
5362   CodeGenFunction::ComplexPairTy ComplexVal;
5363   if (Val.isScalar()) {
5364     // Convert the input element to the element type of the complex.
5365     QualType DestElementType =
5366         DestType->castAs<ComplexType>()->getElementType();
5367     llvm::Value *ScalarVal = CGF.EmitScalarConversion(
5368         Val.getScalarVal(), SrcType, DestElementType, Loc);
5369     ComplexVal = CodeGenFunction::ComplexPairTy(
5370         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
5371   } else {
5372     assert(Val.isComplex() && "Must be a scalar or complex.");
5373     QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
5374     QualType DestElementType =
5375         DestType->castAs<ComplexType>()->getElementType();
5376     ComplexVal.first = CGF.EmitScalarConversion(
5377         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
5378     ComplexVal.second = CGF.EmitScalarConversion(
5379         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
5380   }
5381   return ComplexVal;
5382 }
5383 
5384 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
5385                                   LValue LVal, RValue RVal) {
5386   if (LVal.isGlobalReg())
5387     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
5388   else
5389     CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
5390 }
5391 
5392 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF,
5393                                    llvm::AtomicOrdering AO, LValue LVal,
5394                                    SourceLocation Loc) {
5395   if (LVal.isGlobalReg())
5396     return CGF.EmitLoadOfLValue(LVal, Loc);
5397   return CGF.EmitAtomicLoad(
5398       LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
5399       LVal.isVolatile());
5400 }
5401 
5402 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
5403                                          QualType RValTy, SourceLocation Loc) {
5404   switch (getEvaluationKind(LVal.getType())) {
5405   case TEK_Scalar:
5406     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
5407                                *this, RVal, RValTy, LVal.getType(), Loc)),
5408                            LVal);
5409     break;
5410   case TEK_Complex:
5411     EmitStoreOfComplex(
5412         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
5413         /*isInit=*/false);
5414     break;
5415   case TEK_Aggregate:
5416     llvm_unreachable("Must be a scalar or complex.");
5417   }
5418 }
5419 
5420 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
5421                                   const Expr *X, const Expr *V,
5422                                   SourceLocation Loc) {
5423   // v = x;
5424   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
5425   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
5426   LValue XLValue = CGF.EmitLValue(X);
5427   LValue VLValue = CGF.EmitLValue(V);
5428   RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
5429   // OpenMP, 2.17.7, atomic Construct
5430   // If the read or capture clause is specified and the acquire, acq_rel, or
5431   // seq_cst clause is specified then the strong flush on exit from the atomic
5432   // operation is also an acquire flush.
5433   switch (AO) {
5434   case llvm::AtomicOrdering::Acquire:
5435   case llvm::AtomicOrdering::AcquireRelease:
5436   case llvm::AtomicOrdering::SequentiallyConsistent:
5437     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5438                                          llvm::AtomicOrdering::Acquire);
5439     break;
5440   case llvm::AtomicOrdering::Monotonic:
5441   case llvm::AtomicOrdering::Release:
5442     break;
5443   case llvm::AtomicOrdering::NotAtomic:
5444   case llvm::AtomicOrdering::Unordered:
5445     llvm_unreachable("Unexpected ordering.");
5446   }
5447   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
5448   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
5449 }
5450 
5451 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF,
5452                                    llvm::AtomicOrdering AO, const Expr *X,
5453                                    const Expr *E, SourceLocation Loc) {
5454   // x = expr;
5455   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
5456   emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
5457   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5458   // OpenMP, 2.17.7, atomic Construct
5459   // If the write, update, or capture clause is specified and the release,
5460   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5461   // the atomic operation is also a release flush.
5462   switch (AO) {
5463   case llvm::AtomicOrdering::Release:
5464   case llvm::AtomicOrdering::AcquireRelease:
5465   case llvm::AtomicOrdering::SequentiallyConsistent:
5466     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5467                                          llvm::AtomicOrdering::Release);
5468     break;
5469   case llvm::AtomicOrdering::Acquire:
5470   case llvm::AtomicOrdering::Monotonic:
5471     break;
5472   case llvm::AtomicOrdering::NotAtomic:
5473   case llvm::AtomicOrdering::Unordered:
5474     llvm_unreachable("Unexpected ordering.");
5475   }
5476 }
5477 
5478 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
5479                                                 RValue Update,
5480                                                 BinaryOperatorKind BO,
5481                                                 llvm::AtomicOrdering AO,
5482                                                 bool IsXLHSInRHSPart) {
5483   ASTContext &Context = CGF.getContext();
5484   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
5485   // expression is simple and atomic is allowed for the given type for the
5486   // target platform.
5487   if (BO == BO_Comma || !Update.isScalar() ||
5488       !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
5489       (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
5490        (Update.getScalarVal()->getType() !=
5491         X.getAddress(CGF).getElementType())) ||
5492       !X.getAddress(CGF).getElementType()->isIntegerTy() ||
5493       !Context.getTargetInfo().hasBuiltinAtomic(
5494           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
5495     return std::make_pair(false, RValue::get(nullptr));
5496 
5497   llvm::AtomicRMWInst::BinOp RMWOp;
5498   switch (BO) {
5499   case BO_Add:
5500     RMWOp = llvm::AtomicRMWInst::Add;
5501     break;
5502   case BO_Sub:
5503     if (!IsXLHSInRHSPart)
5504       return std::make_pair(false, RValue::get(nullptr));
5505     RMWOp = llvm::AtomicRMWInst::Sub;
5506     break;
5507   case BO_And:
5508     RMWOp = llvm::AtomicRMWInst::And;
5509     break;
5510   case BO_Or:
5511     RMWOp = llvm::AtomicRMWInst::Or;
5512     break;
5513   case BO_Xor:
5514     RMWOp = llvm::AtomicRMWInst::Xor;
5515     break;
5516   case BO_LT:
5517     RMWOp = X.getType()->hasSignedIntegerRepresentation()
5518                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
5519                                    : llvm::AtomicRMWInst::Max)
5520                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
5521                                    : llvm::AtomicRMWInst::UMax);
5522     break;
5523   case BO_GT:
5524     RMWOp = X.getType()->hasSignedIntegerRepresentation()
5525                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
5526                                    : llvm::AtomicRMWInst::Min)
5527                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
5528                                    : llvm::AtomicRMWInst::UMin);
5529     break;
5530   case BO_Assign:
5531     RMWOp = llvm::AtomicRMWInst::Xchg;
5532     break;
5533   case BO_Mul:
5534   case BO_Div:
5535   case BO_Rem:
5536   case BO_Shl:
5537   case BO_Shr:
5538   case BO_LAnd:
5539   case BO_LOr:
5540     return std::make_pair(false, RValue::get(nullptr));
5541   case BO_PtrMemD:
5542   case BO_PtrMemI:
5543   case BO_LE:
5544   case BO_GE:
5545   case BO_EQ:
5546   case BO_NE:
5547   case BO_Cmp:
5548   case BO_AddAssign:
5549   case BO_SubAssign:
5550   case BO_AndAssign:
5551   case BO_OrAssign:
5552   case BO_XorAssign:
5553   case BO_MulAssign:
5554   case BO_DivAssign:
5555   case BO_RemAssign:
5556   case BO_ShlAssign:
5557   case BO_ShrAssign:
5558   case BO_Comma:
5559     llvm_unreachable("Unsupported atomic update operation");
5560   }
5561   llvm::Value *UpdateVal = Update.getScalarVal();
5562   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
5563     UpdateVal = CGF.Builder.CreateIntCast(
5564         IC, X.getAddress(CGF).getElementType(),
5565         X.getType()->hasSignedIntegerRepresentation());
5566   }
5567   llvm::Value *Res =
5568       CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
5569   return std::make_pair(true, RValue::get(Res));
5570 }
5571 
5572 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
5573     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
5574     llvm::AtomicOrdering AO, SourceLocation Loc,
5575     const llvm::function_ref<RValue(RValue)> CommonGen) {
5576   // Update expressions are allowed to have the following forms:
5577   // x binop= expr; -> xrval + expr;
5578   // x++, ++x -> xrval + 1;
5579   // x--, --x -> xrval - 1;
5580   // x = x binop expr; -> xrval binop expr
5581   // x = expr Op x; - > expr binop xrval;
5582   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
5583   if (!Res.first) {
5584     if (X.isGlobalReg()) {
5585       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
5586       // 'xrval'.
5587       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
5588     } else {
5589       // Perform compare-and-swap procedure.
5590       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
5591     }
5592   }
5593   return Res;
5594 }
5595 
5596 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF,
5597                                     llvm::AtomicOrdering AO, const Expr *X,
5598                                     const Expr *E, const Expr *UE,
5599                                     bool IsXLHSInRHSPart, SourceLocation Loc) {
5600   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
5601          "Update expr in 'atomic update' must be a binary operator.");
5602   const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
5603   // Update expressions are allowed to have the following forms:
5604   // x binop= expr; -> xrval + expr;
5605   // x++, ++x -> xrval + 1;
5606   // x--, --x -> xrval - 1;
5607   // x = x binop expr; -> xrval binop expr
5608   // x = expr Op x; - > expr binop xrval;
5609   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
5610   LValue XLValue = CGF.EmitLValue(X);
5611   RValue ExprRValue = CGF.EmitAnyExpr(E);
5612   const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
5613   const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
5614   const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
5615   const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
5616   auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
5617     CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5618     CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
5619     return CGF.EmitAnyExpr(UE);
5620   };
5621   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
5622       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
5623   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5624   // OpenMP, 2.17.7, atomic Construct
5625   // If the write, update, or capture clause is specified and the release,
5626   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5627   // the atomic operation is also a release flush.
5628   switch (AO) {
5629   case llvm::AtomicOrdering::Release:
5630   case llvm::AtomicOrdering::AcquireRelease:
5631   case llvm::AtomicOrdering::SequentiallyConsistent:
5632     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5633                                          llvm::AtomicOrdering::Release);
5634     break;
5635   case llvm::AtomicOrdering::Acquire:
5636   case llvm::AtomicOrdering::Monotonic:
5637     break;
5638   case llvm::AtomicOrdering::NotAtomic:
5639   case llvm::AtomicOrdering::Unordered:
5640     llvm_unreachable("Unexpected ordering.");
5641   }
5642 }
5643 
5644 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
5645                             QualType SourceType, QualType ResType,
5646                             SourceLocation Loc) {
5647   switch (CGF.getEvaluationKind(ResType)) {
5648   case TEK_Scalar:
5649     return RValue::get(
5650         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
5651   case TEK_Complex: {
5652     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
5653     return RValue::getComplex(Res.first, Res.second);
5654   }
5655   case TEK_Aggregate:
5656     break;
5657   }
5658   llvm_unreachable("Must be a scalar or complex.");
5659 }
5660 
5661 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF,
5662                                      llvm::AtomicOrdering AO,
5663                                      bool IsPostfixUpdate, const Expr *V,
5664                                      const Expr *X, const Expr *E,
5665                                      const Expr *UE, bool IsXLHSInRHSPart,
5666                                      SourceLocation Loc) {
5667   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
5668   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
5669   RValue NewVVal;
5670   LValue VLValue = CGF.EmitLValue(V);
5671   LValue XLValue = CGF.EmitLValue(X);
5672   RValue ExprRValue = CGF.EmitAnyExpr(E);
5673   QualType NewVValType;
5674   if (UE) {
5675     // 'x' is updated with some additional value.
5676     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
5677            "Update expr in 'atomic capture' must be a binary operator.");
5678     const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
5679     // Update expressions are allowed to have the following forms:
5680     // x binop= expr; -> xrval + expr;
5681     // x++, ++x -> xrval + 1;
5682     // x--, --x -> xrval - 1;
5683     // x = x binop expr; -> xrval binop expr
5684     // x = expr Op x; - > expr binop xrval;
5685     const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
5686     const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
5687     const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
5688     NewVValType = XRValExpr->getType();
5689     const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
5690     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
5691                   IsPostfixUpdate](RValue XRValue) {
5692       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5693       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
5694       RValue Res = CGF.EmitAnyExpr(UE);
5695       NewVVal = IsPostfixUpdate ? XRValue : Res;
5696       return Res;
5697     };
5698     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
5699         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
5700     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5701     if (Res.first) {
5702       // 'atomicrmw' instruction was generated.
5703       if (IsPostfixUpdate) {
5704         // Use old value from 'atomicrmw'.
5705         NewVVal = Res.second;
5706       } else {
5707         // 'atomicrmw' does not provide new value, so evaluate it using old
5708         // value of 'x'.
5709         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
5710         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
5711         NewVVal = CGF.EmitAnyExpr(UE);
5712       }
5713     }
5714   } else {
5715     // 'x' is simply rewritten with some 'expr'.
5716     NewVValType = X->getType().getNonReferenceType();
5717     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
5718                                X->getType().getNonReferenceType(), Loc);
5719     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
5720       NewVVal = XRValue;
5721       return ExprRValue;
5722     };
5723     // Try to perform atomicrmw xchg, otherwise simple exchange.
5724     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
5725         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
5726         Loc, Gen);
5727     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
5728     if (Res.first) {
5729       // 'atomicrmw' instruction was generated.
5730       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
5731     }
5732   }
5733   // Emit post-update store to 'v' of old/new 'x' value.
5734   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
5735   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
5736   // OpenMP 5.1 removes the required flush for capture clause.
5737   if (CGF.CGM.getLangOpts().OpenMP < 51) {
5738     // OpenMP, 2.17.7, atomic Construct
5739     // If the write, update, or capture clause is specified and the release,
5740     // acq_rel, or seq_cst clause is specified then the strong flush on entry to
5741     // the atomic operation is also a release flush.
5742     // If the read or capture clause is specified and the acquire, acq_rel, or
5743     // seq_cst clause is specified then the strong flush on exit from the atomic
5744     // operation is also an acquire flush.
5745     switch (AO) {
5746     case llvm::AtomicOrdering::Release:
5747       CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5748                                            llvm::AtomicOrdering::Release);
5749       break;
5750     case llvm::AtomicOrdering::Acquire:
5751       CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
5752                                            llvm::AtomicOrdering::Acquire);
5753       break;
5754     case llvm::AtomicOrdering::AcquireRelease:
5755     case llvm::AtomicOrdering::SequentiallyConsistent:
5756       CGF.CGM.getOpenMPRuntime().emitFlush(
5757           CGF, llvm::None, Loc, llvm::AtomicOrdering::AcquireRelease);
5758       break;
5759     case llvm::AtomicOrdering::Monotonic:
5760       break;
5761     case llvm::AtomicOrdering::NotAtomic:
5762     case llvm::AtomicOrdering::Unordered:
5763       llvm_unreachable("Unexpected ordering.");
5764     }
5765   }
5766 }
5767 
5768 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
5769                               llvm::AtomicOrdering AO, bool IsPostfixUpdate,
5770                               const Expr *X, const Expr *V, const Expr *E,
5771                               const Expr *UE, bool IsXLHSInRHSPart,
5772                               SourceLocation Loc) {
5773   switch (Kind) {
5774   case OMPC_read:
5775     emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
5776     break;
5777   case OMPC_write:
5778     emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
5779     break;
5780   case OMPC_unknown:
5781   case OMPC_update:
5782     emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
5783     break;
5784   case OMPC_capture:
5785     emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
5786                              IsXLHSInRHSPart, Loc);
5787     break;
5788   case OMPC_if:
5789   case OMPC_final:
5790   case OMPC_num_threads:
5791   case OMPC_private:
5792   case OMPC_firstprivate:
5793   case OMPC_lastprivate:
5794   case OMPC_reduction:
5795   case OMPC_task_reduction:
5796   case OMPC_in_reduction:
5797   case OMPC_safelen:
5798   case OMPC_simdlen:
5799   case OMPC_sizes:
5800   case OMPC_full:
5801   case OMPC_partial:
5802   case OMPC_allocator:
5803   case OMPC_allocate:
5804   case OMPC_collapse:
5805   case OMPC_default:
5806   case OMPC_seq_cst:
5807   case OMPC_acq_rel:
5808   case OMPC_acquire:
5809   case OMPC_release:
5810   case OMPC_relaxed:
5811   case OMPC_shared:
5812   case OMPC_linear:
5813   case OMPC_aligned:
5814   case OMPC_copyin:
5815   case OMPC_copyprivate:
5816   case OMPC_flush:
5817   case OMPC_depobj:
5818   case OMPC_proc_bind:
5819   case OMPC_schedule:
5820   case OMPC_ordered:
5821   case OMPC_nowait:
5822   case OMPC_untied:
5823   case OMPC_threadprivate:
5824   case OMPC_depend:
5825   case OMPC_mergeable:
5826   case OMPC_device:
5827   case OMPC_threads:
5828   case OMPC_simd:
5829   case OMPC_map:
5830   case OMPC_num_teams:
5831   case OMPC_thread_limit:
5832   case OMPC_priority:
5833   case OMPC_grainsize:
5834   case OMPC_nogroup:
5835   case OMPC_num_tasks:
5836   case OMPC_hint:
5837   case OMPC_dist_schedule:
5838   case OMPC_defaultmap:
5839   case OMPC_uniform:
5840   case OMPC_to:
5841   case OMPC_from:
5842   case OMPC_use_device_ptr:
5843   case OMPC_use_device_addr:
5844   case OMPC_is_device_ptr:
5845   case OMPC_unified_address:
5846   case OMPC_unified_shared_memory:
5847   case OMPC_reverse_offload:
5848   case OMPC_dynamic_allocators:
5849   case OMPC_atomic_default_mem_order:
5850   case OMPC_device_type:
5851   case OMPC_match:
5852   case OMPC_nontemporal:
5853   case OMPC_order:
5854   case OMPC_destroy:
5855   case OMPC_detach:
5856   case OMPC_inclusive:
5857   case OMPC_exclusive:
5858   case OMPC_uses_allocators:
5859   case OMPC_affinity:
5860   case OMPC_init:
5861   case OMPC_inbranch:
5862   case OMPC_notinbranch:
5863   case OMPC_link:
5864   case OMPC_use:
5865   case OMPC_novariants:
5866   case OMPC_nocontext:
5867   case OMPC_filter:
5868     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
5869   }
5870 }
5871 
5872 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
5873   llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic;
5874   bool MemOrderingSpecified = false;
5875   if (S.getSingleClause<OMPSeqCstClause>()) {
5876     AO = llvm::AtomicOrdering::SequentiallyConsistent;
5877     MemOrderingSpecified = true;
5878   } else if (S.getSingleClause<OMPAcqRelClause>()) {
5879     AO = llvm::AtomicOrdering::AcquireRelease;
5880     MemOrderingSpecified = true;
5881   } else if (S.getSingleClause<OMPAcquireClause>()) {
5882     AO = llvm::AtomicOrdering::Acquire;
5883     MemOrderingSpecified = true;
5884   } else if (S.getSingleClause<OMPReleaseClause>()) {
5885     AO = llvm::AtomicOrdering::Release;
5886     MemOrderingSpecified = true;
5887   } else if (S.getSingleClause<OMPRelaxedClause>()) {
5888     AO = llvm::AtomicOrdering::Monotonic;
5889     MemOrderingSpecified = true;
5890   }
5891   OpenMPClauseKind Kind = OMPC_unknown;
5892   for (const OMPClause *C : S.clauses()) {
5893     // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause,
5894     // if it is first).
5895     if (C->getClauseKind() != OMPC_seq_cst &&
5896         C->getClauseKind() != OMPC_acq_rel &&
5897         C->getClauseKind() != OMPC_acquire &&
5898         C->getClauseKind() != OMPC_release &&
5899         C->getClauseKind() != OMPC_relaxed && C->getClauseKind() != OMPC_hint) {
5900       Kind = C->getClauseKind();
5901       break;
5902     }
5903   }
5904   if (!MemOrderingSpecified) {
5905     llvm::AtomicOrdering DefaultOrder =
5906         CGM.getOpenMPRuntime().getDefaultMemoryOrdering();
5907     if (DefaultOrder == llvm::AtomicOrdering::Monotonic ||
5908         DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent ||
5909         (DefaultOrder == llvm::AtomicOrdering::AcquireRelease &&
5910          Kind == OMPC_capture)) {
5911       AO = DefaultOrder;
5912     } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) {
5913       if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) {
5914         AO = llvm::AtomicOrdering::Release;
5915       } else if (Kind == OMPC_read) {
5916         assert(Kind == OMPC_read && "Unexpected atomic kind.");
5917         AO = llvm::AtomicOrdering::Acquire;
5918       }
5919     }
5920   }
5921 
5922   LexicalScope Scope(*this, S.getSourceRange());
5923   EmitStopPoint(S.getAssociatedStmt());
5924   emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(),
5925                     S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(),
5926                     S.getBeginLoc());
5927 }
5928 
5929 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
5930                                          const OMPExecutableDirective &S,
5931                                          const RegionCodeGenTy &CodeGen) {
5932   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
5933   CodeGenModule &CGM = CGF.CGM;
5934 
5935   // On device emit this construct as inlined code.
5936   if (CGM.getLangOpts().OpenMPIsDevice) {
5937     OMPLexicalScope Scope(CGF, S, OMPD_target);
5938     CGM.getOpenMPRuntime().emitInlinedDirective(
5939         CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5940           CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5941         });
5942     return;
5943   }
5944 
5945   auto LPCRegion =
5946       CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
5947   llvm::Function *Fn = nullptr;
5948   llvm::Constant *FnID = nullptr;
5949 
5950   const Expr *IfCond = nullptr;
5951   // Check for the at most one if clause associated with the target region.
5952   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5953     if (C->getNameModifier() == OMPD_unknown ||
5954         C->getNameModifier() == OMPD_target) {
5955       IfCond = C->getCondition();
5956       break;
5957     }
5958   }
5959 
5960   // Check if we have any device clause associated with the directive.
5961   llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device(
5962       nullptr, OMPC_DEVICE_unknown);
5963   if (auto *C = S.getSingleClause<OMPDeviceClause>())
5964     Device.setPointerAndInt(C->getDevice(), C->getModifier());
5965 
5966   // Check if we have an if clause whose conditional always evaluates to false
5967   // or if we do not have any targets specified. If so the target region is not
5968   // an offload entry point.
5969   bool IsOffloadEntry = true;
5970   if (IfCond) {
5971     bool Val;
5972     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
5973       IsOffloadEntry = false;
5974   }
5975   if (CGM.getLangOpts().OMPTargetTriples.empty())
5976     IsOffloadEntry = false;
5977 
5978   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
5979   StringRef ParentName;
5980   // In case we have Ctors/Dtors we use the complete type variant to produce
5981   // the mangling of the device outlined kernel.
5982   if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
5983     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
5984   else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
5985     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
5986   else
5987     ParentName =
5988         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
5989 
5990   // Emit target region as a standalone region.
5991   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
5992                                                     IsOffloadEntry, CodeGen);
5993   OMPLexicalScope Scope(CGF, S, OMPD_task);
5994   auto &&SizeEmitter =
5995       [IsOffloadEntry](CodeGenFunction &CGF,
5996                        const OMPLoopDirective &D) -> llvm::Value * {
5997     if (IsOffloadEntry) {
5998       OMPLoopScope(CGF, D);
5999       // Emit calculation of the iterations count.
6000       llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
6001       NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
6002                                                 /*isSigned=*/false);
6003       return NumIterations;
6004     }
6005     return nullptr;
6006   };
6007   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
6008                                         SizeEmitter);
6009 }
6010 
6011 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
6012                              PrePostActionTy &Action) {
6013   Action.Enter(CGF);
6014   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6015   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6016   CGF.EmitOMPPrivateClause(S, PrivateScope);
6017   (void)PrivateScope.Privatize();
6018   if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6019     CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
6020 
6021   CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
6022   CGF.EnsureInsertPoint();
6023 }
6024 
6025 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
6026                                                   StringRef ParentName,
6027                                                   const OMPTargetDirective &S) {
6028   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6029     emitTargetRegion(CGF, S, Action);
6030   };
6031   llvm::Function *Fn;
6032   llvm::Constant *Addr;
6033   // Emit target region as a standalone region.
6034   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6035       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6036   assert(Fn && Addr && "Target device function emission failed.");
6037 }
6038 
6039 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
6040   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6041     emitTargetRegion(CGF, S, Action);
6042   };
6043   emitCommonOMPTargetDirective(*this, S, CodeGen);
6044 }
6045 
6046 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
6047                                         const OMPExecutableDirective &S,
6048                                         OpenMPDirectiveKind InnermostKind,
6049                                         const RegionCodeGenTy &CodeGen) {
6050   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
6051   llvm::Function *OutlinedFn =
6052       CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
6053           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
6054 
6055   const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
6056   const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
6057   if (NT || TL) {
6058     const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
6059     const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
6060 
6061     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
6062                                                   S.getBeginLoc());
6063   }
6064 
6065   OMPTeamsScope Scope(CGF, S);
6066   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
6067   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
6068   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
6069                                            CapturedVars);
6070 }
6071 
6072 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
6073   // Emit teams region as a standalone region.
6074   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6075     Action.Enter(CGF);
6076     OMPPrivateScope PrivateScope(CGF);
6077     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6078     CGF.EmitOMPPrivateClause(S, PrivateScope);
6079     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6080     (void)PrivateScope.Privatize();
6081     CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
6082     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6083   };
6084   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
6085   emitPostUpdateForReductionClause(*this, S,
6086                                    [](CodeGenFunction &) { return nullptr; });
6087 }
6088 
6089 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
6090                                   const OMPTargetTeamsDirective &S) {
6091   auto *CS = S.getCapturedStmt(OMPD_teams);
6092   Action.Enter(CGF);
6093   // Emit teams region as a standalone region.
6094   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
6095     Action.Enter(CGF);
6096     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6097     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6098     CGF.EmitOMPPrivateClause(S, PrivateScope);
6099     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6100     (void)PrivateScope.Privatize();
6101     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6102       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
6103     CGF.EmitStmt(CS->getCapturedStmt());
6104     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6105   };
6106   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
6107   emitPostUpdateForReductionClause(CGF, S,
6108                                    [](CodeGenFunction &) { return nullptr; });
6109 }
6110 
6111 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6112     CodeGenModule &CGM, StringRef ParentName,
6113     const OMPTargetTeamsDirective &S) {
6114   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6115     emitTargetTeamsRegion(CGF, Action, S);
6116   };
6117   llvm::Function *Fn;
6118   llvm::Constant *Addr;
6119   // Emit target region as a standalone region.
6120   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6121       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6122   assert(Fn && Addr && "Target device function emission failed.");
6123 }
6124 
6125 void CodeGenFunction::EmitOMPTargetTeamsDirective(
6126     const OMPTargetTeamsDirective &S) {
6127   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6128     emitTargetTeamsRegion(CGF, Action, S);
6129   };
6130   emitCommonOMPTargetDirective(*this, S, CodeGen);
6131 }
6132 
6133 static void
6134 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
6135                                 const OMPTargetTeamsDistributeDirective &S) {
6136   Action.Enter(CGF);
6137   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6138     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6139   };
6140 
6141   // Emit teams region as a standalone region.
6142   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6143                                             PrePostActionTy &Action) {
6144     Action.Enter(CGF);
6145     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6146     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6147     (void)PrivateScope.Privatize();
6148     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6149                                                     CodeGenDistribute);
6150     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6151   };
6152   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
6153   emitPostUpdateForReductionClause(CGF, S,
6154                                    [](CodeGenFunction &) { return nullptr; });
6155 }
6156 
6157 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
6158     CodeGenModule &CGM, StringRef ParentName,
6159     const OMPTargetTeamsDistributeDirective &S) {
6160   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6161     emitTargetTeamsDistributeRegion(CGF, Action, S);
6162   };
6163   llvm::Function *Fn;
6164   llvm::Constant *Addr;
6165   // Emit target region as a standalone region.
6166   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6167       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6168   assert(Fn && Addr && "Target device function emission failed.");
6169 }
6170 
6171 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
6172     const OMPTargetTeamsDistributeDirective &S) {
6173   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6174     emitTargetTeamsDistributeRegion(CGF, Action, S);
6175   };
6176   emitCommonOMPTargetDirective(*this, S, CodeGen);
6177 }
6178 
6179 static void emitTargetTeamsDistributeSimdRegion(
6180     CodeGenFunction &CGF, PrePostActionTy &Action,
6181     const OMPTargetTeamsDistributeSimdDirective &S) {
6182   Action.Enter(CGF);
6183   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6184     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6185   };
6186 
6187   // Emit teams region as a standalone region.
6188   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6189                                             PrePostActionTy &Action) {
6190     Action.Enter(CGF);
6191     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6192     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6193     (void)PrivateScope.Privatize();
6194     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6195                                                     CodeGenDistribute);
6196     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6197   };
6198   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
6199   emitPostUpdateForReductionClause(CGF, S,
6200                                    [](CodeGenFunction &) { return nullptr; });
6201 }
6202 
6203 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
6204     CodeGenModule &CGM, StringRef ParentName,
6205     const OMPTargetTeamsDistributeSimdDirective &S) {
6206   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6207     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
6208   };
6209   llvm::Function *Fn;
6210   llvm::Constant *Addr;
6211   // Emit target region as a standalone region.
6212   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6213       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6214   assert(Fn && Addr && "Target device function emission failed.");
6215 }
6216 
6217 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
6218     const OMPTargetTeamsDistributeSimdDirective &S) {
6219   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6220     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
6221   };
6222   emitCommonOMPTargetDirective(*this, S, CodeGen);
6223 }
6224 
6225 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
6226     const OMPTeamsDistributeDirective &S) {
6227 
6228   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6229     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6230   };
6231 
6232   // Emit teams region as a standalone region.
6233   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6234                                             PrePostActionTy &Action) {
6235     Action.Enter(CGF);
6236     OMPPrivateScope PrivateScope(CGF);
6237     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6238     (void)PrivateScope.Privatize();
6239     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6240                                                     CodeGenDistribute);
6241     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6242   };
6243   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
6244   emitPostUpdateForReductionClause(*this, S,
6245                                    [](CodeGenFunction &) { return nullptr; });
6246 }
6247 
6248 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
6249     const OMPTeamsDistributeSimdDirective &S) {
6250   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6251     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
6252   };
6253 
6254   // Emit teams region as a standalone region.
6255   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6256                                             PrePostActionTy &Action) {
6257     Action.Enter(CGF);
6258     OMPPrivateScope PrivateScope(CGF);
6259     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6260     (void)PrivateScope.Privatize();
6261     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
6262                                                     CodeGenDistribute);
6263     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6264   };
6265   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
6266   emitPostUpdateForReductionClause(*this, S,
6267                                    [](CodeGenFunction &) { return nullptr; });
6268 }
6269 
6270 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
6271     const OMPTeamsDistributeParallelForDirective &S) {
6272   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6273     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6274                               S.getDistInc());
6275   };
6276 
6277   // Emit teams region as a standalone region.
6278   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6279                                             PrePostActionTy &Action) {
6280     Action.Enter(CGF);
6281     OMPPrivateScope PrivateScope(CGF);
6282     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6283     (void)PrivateScope.Privatize();
6284     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
6285                                                     CodeGenDistribute);
6286     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6287   };
6288   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
6289   emitPostUpdateForReductionClause(*this, S,
6290                                    [](CodeGenFunction &) { return nullptr; });
6291 }
6292 
6293 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
6294     const OMPTeamsDistributeParallelForSimdDirective &S) {
6295   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6296     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6297                               S.getDistInc());
6298   };
6299 
6300   // Emit teams region as a standalone region.
6301   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6302                                             PrePostActionTy &Action) {
6303     Action.Enter(CGF);
6304     OMPPrivateScope PrivateScope(CGF);
6305     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6306     (void)PrivateScope.Privatize();
6307     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6308         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6309     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6310   };
6311   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
6312                               CodeGen);
6313   emitPostUpdateForReductionClause(*this, S,
6314                                    [](CodeGenFunction &) { return nullptr; });
6315 }
6316 
6317 static void emitTargetTeamsDistributeParallelForRegion(
6318     CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
6319     PrePostActionTy &Action) {
6320   Action.Enter(CGF);
6321   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6322     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6323                               S.getDistInc());
6324   };
6325 
6326   // Emit teams region as a standalone region.
6327   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6328                                                  PrePostActionTy &Action) {
6329     Action.Enter(CGF);
6330     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6331     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6332     (void)PrivateScope.Privatize();
6333     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6334         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6335     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6336   };
6337 
6338   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
6339                               CodeGenTeams);
6340   emitPostUpdateForReductionClause(CGF, S,
6341                                    [](CodeGenFunction &) { return nullptr; });
6342 }
6343 
6344 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
6345     CodeGenModule &CGM, StringRef ParentName,
6346     const OMPTargetTeamsDistributeParallelForDirective &S) {
6347   // Emit SPMD target teams distribute parallel for region as a standalone
6348   // region.
6349   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6350     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
6351   };
6352   llvm::Function *Fn;
6353   llvm::Constant *Addr;
6354   // Emit target region as a standalone region.
6355   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6356       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6357   assert(Fn && Addr && "Target device function emission failed.");
6358 }
6359 
6360 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
6361     const OMPTargetTeamsDistributeParallelForDirective &S) {
6362   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6363     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
6364   };
6365   emitCommonOMPTargetDirective(*this, S, CodeGen);
6366 }
6367 
6368 static void emitTargetTeamsDistributeParallelForSimdRegion(
6369     CodeGenFunction &CGF,
6370     const OMPTargetTeamsDistributeParallelForSimdDirective &S,
6371     PrePostActionTy &Action) {
6372   Action.Enter(CGF);
6373   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6374     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
6375                               S.getDistInc());
6376   };
6377 
6378   // Emit teams region as a standalone region.
6379   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
6380                                                  PrePostActionTy &Action) {
6381     Action.Enter(CGF);
6382     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6383     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6384     (void)PrivateScope.Privatize();
6385     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
6386         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
6387     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
6388   };
6389 
6390   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
6391                               CodeGenTeams);
6392   emitPostUpdateForReductionClause(CGF, S,
6393                                    [](CodeGenFunction &) { return nullptr; });
6394 }
6395 
6396 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
6397     CodeGenModule &CGM, StringRef ParentName,
6398     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
6399   // Emit SPMD target teams distribute parallel for simd region as a standalone
6400   // region.
6401   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6402     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
6403   };
6404   llvm::Function *Fn;
6405   llvm::Constant *Addr;
6406   // Emit target region as a standalone region.
6407   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6408       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6409   assert(Fn && Addr && "Target device function emission failed.");
6410 }
6411 
6412 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
6413     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
6414   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6415     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
6416   };
6417   emitCommonOMPTargetDirective(*this, S, CodeGen);
6418 }
6419 
6420 void CodeGenFunction::EmitOMPCancellationPointDirective(
6421     const OMPCancellationPointDirective &S) {
6422   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
6423                                                    S.getCancelRegion());
6424 }
6425 
6426 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
6427   const Expr *IfCond = nullptr;
6428   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
6429     if (C->getNameModifier() == OMPD_unknown ||
6430         C->getNameModifier() == OMPD_cancel) {
6431       IfCond = C->getCondition();
6432       break;
6433     }
6434   }
6435   if (CGM.getLangOpts().OpenMPIRBuilder) {
6436     llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
6437     // TODO: This check is necessary as we only generate `omp parallel` through
6438     // the OpenMPIRBuilder for now.
6439     if (S.getCancelRegion() == OMPD_parallel ||
6440         S.getCancelRegion() == OMPD_sections ||
6441         S.getCancelRegion() == OMPD_section) {
6442       llvm::Value *IfCondition = nullptr;
6443       if (IfCond)
6444         IfCondition = EmitScalarExpr(IfCond,
6445                                      /*IgnoreResultAssign=*/true);
6446       return Builder.restoreIP(
6447           OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion()));
6448     }
6449   }
6450 
6451   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
6452                                         S.getCancelRegion());
6453 }
6454 
6455 CodeGenFunction::JumpDest
6456 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
6457   if (Kind == OMPD_parallel || Kind == OMPD_task ||
6458       Kind == OMPD_target_parallel || Kind == OMPD_taskloop ||
6459       Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop)
6460     return ReturnBlock;
6461   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
6462          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
6463          Kind == OMPD_distribute_parallel_for ||
6464          Kind == OMPD_target_parallel_for ||
6465          Kind == OMPD_teams_distribute_parallel_for ||
6466          Kind == OMPD_target_teams_distribute_parallel_for);
6467   return OMPCancelStack.getExitBlock();
6468 }
6469 
6470 void CodeGenFunction::EmitOMPUseDevicePtrClause(
6471     const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope,
6472     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
6473   auto OrigVarIt = C.varlist_begin();
6474   auto InitIt = C.inits().begin();
6475   for (const Expr *PvtVarIt : C.private_copies()) {
6476     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
6477     const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
6478     const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
6479 
6480     // In order to identify the right initializer we need to match the
6481     // declaration used by the mapping logic. In some cases we may get
6482     // OMPCapturedExprDecl that refers to the original declaration.
6483     const ValueDecl *MatchingVD = OrigVD;
6484     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
6485       // OMPCapturedExprDecl are used to privative fields of the current
6486       // structure.
6487       const auto *ME = cast<MemberExpr>(OED->getInit());
6488       assert(isa<CXXThisExpr>(ME->getBase()) &&
6489              "Base should be the current struct!");
6490       MatchingVD = ME->getMemberDecl();
6491     }
6492 
6493     // If we don't have information about the current list item, move on to
6494     // the next one.
6495     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
6496     if (InitAddrIt == CaptureDeviceAddrMap.end())
6497       continue;
6498 
6499     bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
6500                                                          InitAddrIt, InitVD,
6501                                                          PvtVD]() {
6502       // Initialize the temporary initialization variable with the address we
6503       // get from the runtime library. We have to cast the source address
6504       // because it is always a void *. References are materialized in the
6505       // privatization scope, so the initialization here disregards the fact
6506       // the original variable is a reference.
6507       QualType AddrQTy =
6508           getContext().getPointerType(OrigVD->getType().getNonReferenceType());
6509       llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
6510       Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
6511       setAddrOfLocalVar(InitVD, InitAddr);
6512 
6513       // Emit private declaration, it will be initialized by the value we
6514       // declaration we just added to the local declarations map.
6515       EmitDecl(*PvtVD);
6516 
6517       // The initialization variables reached its purpose in the emission
6518       // of the previous declaration, so we don't need it anymore.
6519       LocalDeclMap.erase(InitVD);
6520 
6521       // Return the address of the private variable.
6522       return GetAddrOfLocalVar(PvtVD);
6523     });
6524     assert(IsRegistered && "firstprivate var already registered as private");
6525     // Silence the warning about unused variable.
6526     (void)IsRegistered;
6527 
6528     ++OrigVarIt;
6529     ++InitIt;
6530   }
6531 }
6532 
6533 static const VarDecl *getBaseDecl(const Expr *Ref) {
6534   const Expr *Base = Ref->IgnoreParenImpCasts();
6535   while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base))
6536     Base = OASE->getBase()->IgnoreParenImpCasts();
6537   while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base))
6538     Base = ASE->getBase()->IgnoreParenImpCasts();
6539   return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl());
6540 }
6541 
6542 void CodeGenFunction::EmitOMPUseDeviceAddrClause(
6543     const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope,
6544     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
6545   llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed;
6546   for (const Expr *Ref : C.varlists()) {
6547     const VarDecl *OrigVD = getBaseDecl(Ref);
6548     if (!Processed.insert(OrigVD).second)
6549       continue;
6550     // In order to identify the right initializer we need to match the
6551     // declaration used by the mapping logic. In some cases we may get
6552     // OMPCapturedExprDecl that refers to the original declaration.
6553     const ValueDecl *MatchingVD = OrigVD;
6554     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
6555       // OMPCapturedExprDecl are used to privative fields of the current
6556       // structure.
6557       const auto *ME = cast<MemberExpr>(OED->getInit());
6558       assert(isa<CXXThisExpr>(ME->getBase()) &&
6559              "Base should be the current struct!");
6560       MatchingVD = ME->getMemberDecl();
6561     }
6562 
6563     // If we don't have information about the current list item, move on to
6564     // the next one.
6565     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
6566     if (InitAddrIt == CaptureDeviceAddrMap.end())
6567       continue;
6568 
6569     Address PrivAddr = InitAddrIt->getSecond();
6570     // For declrefs and variable length array need to load the pointer for
6571     // correct mapping, since the pointer to the data was passed to the runtime.
6572     if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) ||
6573         MatchingVD->getType()->isArrayType())
6574       PrivAddr =
6575           EmitLoadOfPointer(PrivAddr, getContext()
6576                                           .getPointerType(OrigVD->getType())
6577                                           ->castAs<PointerType>());
6578     llvm::Type *RealTy =
6579         ConvertTypeForMem(OrigVD->getType().getNonReferenceType())
6580             ->getPointerTo();
6581     PrivAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy);
6582 
6583     (void)PrivateScope.addPrivate(OrigVD, [PrivAddr]() { return PrivAddr; });
6584   }
6585 }
6586 
6587 // Generate the instructions for '#pragma omp target data' directive.
6588 void CodeGenFunction::EmitOMPTargetDataDirective(
6589     const OMPTargetDataDirective &S) {
6590   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true,
6591                                        /*SeparateBeginEndCalls=*/true);
6592 
6593   // Create a pre/post action to signal the privatization of the device pointer.
6594   // This action can be replaced by the OpenMP runtime code generation to
6595   // deactivate privatization.
6596   bool PrivatizeDevicePointers = false;
6597   class DevicePointerPrivActionTy : public PrePostActionTy {
6598     bool &PrivatizeDevicePointers;
6599 
6600   public:
6601     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
6602         : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
6603     void Enter(CodeGenFunction &CGF) override {
6604       PrivatizeDevicePointers = true;
6605     }
6606   };
6607   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
6608 
6609   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
6610                        CodeGenFunction &CGF, PrePostActionTy &Action) {
6611     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6612       CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
6613     };
6614 
6615     // Codegen that selects whether to generate the privatization code or not.
6616     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
6617                           &InnermostCodeGen](CodeGenFunction &CGF,
6618                                              PrePostActionTy &Action) {
6619       RegionCodeGenTy RCG(InnermostCodeGen);
6620       PrivatizeDevicePointers = false;
6621 
6622       // Call the pre-action to change the status of PrivatizeDevicePointers if
6623       // needed.
6624       Action.Enter(CGF);
6625 
6626       if (PrivatizeDevicePointers) {
6627         OMPPrivateScope PrivateScope(CGF);
6628         // Emit all instances of the use_device_ptr clause.
6629         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
6630           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
6631                                         Info.CaptureDeviceAddrMap);
6632         for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>())
6633           CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope,
6634                                          Info.CaptureDeviceAddrMap);
6635         (void)PrivateScope.Privatize();
6636         RCG(CGF);
6637       } else {
6638         OMPLexicalScope Scope(CGF, S, OMPD_unknown);
6639         RCG(CGF);
6640       }
6641     };
6642 
6643     // Forward the provided action to the privatization codegen.
6644     RegionCodeGenTy PrivRCG(PrivCodeGen);
6645     PrivRCG.setAction(Action);
6646 
6647     // Notwithstanding the body of the region is emitted as inlined directive,
6648     // we don't use an inline scope as changes in the references inside the
6649     // region are expected to be visible outside, so we do not privative them.
6650     OMPLexicalScope Scope(CGF, S);
6651     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
6652                                                     PrivRCG);
6653   };
6654 
6655   RegionCodeGenTy RCG(CodeGen);
6656 
6657   // If we don't have target devices, don't bother emitting the data mapping
6658   // code.
6659   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
6660     RCG(*this);
6661     return;
6662   }
6663 
6664   // Check if we have any if clause associated with the directive.
6665   const Expr *IfCond = nullptr;
6666   if (const auto *C = S.getSingleClause<OMPIfClause>())
6667     IfCond = C->getCondition();
6668 
6669   // Check if we have any device clause associated with the directive.
6670   const Expr *Device = nullptr;
6671   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
6672     Device = C->getDevice();
6673 
6674   // Set the action to signal privatization of device pointers.
6675   RCG.setAction(PrivAction);
6676 
6677   // Emit region code.
6678   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
6679                                              Info);
6680 }
6681 
6682 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
6683     const OMPTargetEnterDataDirective &S) {
6684   // If we don't have target devices, don't bother emitting the data mapping
6685   // code.
6686   if (CGM.getLangOpts().OMPTargetTriples.empty())
6687     return;
6688 
6689   // Check if we have any if clause associated with the directive.
6690   const Expr *IfCond = nullptr;
6691   if (const auto *C = S.getSingleClause<OMPIfClause>())
6692     IfCond = C->getCondition();
6693 
6694   // Check if we have any device clause associated with the directive.
6695   const Expr *Device = nullptr;
6696   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
6697     Device = C->getDevice();
6698 
6699   OMPLexicalScope Scope(*this, S, OMPD_task);
6700   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
6701 }
6702 
6703 void CodeGenFunction::EmitOMPTargetExitDataDirective(
6704     const OMPTargetExitDataDirective &S) {
6705   // If we don't have target devices, don't bother emitting the data mapping
6706   // code.
6707   if (CGM.getLangOpts().OMPTargetTriples.empty())
6708     return;
6709 
6710   // Check if we have any if clause associated with the directive.
6711   const Expr *IfCond = nullptr;
6712   if (const auto *C = S.getSingleClause<OMPIfClause>())
6713     IfCond = C->getCondition();
6714 
6715   // Check if we have any device clause associated with the directive.
6716   const Expr *Device = nullptr;
6717   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
6718     Device = C->getDevice();
6719 
6720   OMPLexicalScope Scope(*this, S, OMPD_task);
6721   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
6722 }
6723 
6724 static void emitTargetParallelRegion(CodeGenFunction &CGF,
6725                                      const OMPTargetParallelDirective &S,
6726                                      PrePostActionTy &Action) {
6727   // Get the captured statement associated with the 'parallel' region.
6728   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
6729   Action.Enter(CGF);
6730   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
6731     Action.Enter(CGF);
6732     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
6733     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
6734     CGF.EmitOMPPrivateClause(S, PrivateScope);
6735     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
6736     (void)PrivateScope.Privatize();
6737     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
6738       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
6739     // TODO: Add support for clauses.
6740     CGF.EmitStmt(CS->getCapturedStmt());
6741     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
6742   };
6743   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
6744                                  emitEmptyBoundParameters);
6745   emitPostUpdateForReductionClause(CGF, S,
6746                                    [](CodeGenFunction &) { return nullptr; });
6747 }
6748 
6749 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6750     CodeGenModule &CGM, StringRef ParentName,
6751     const OMPTargetParallelDirective &S) {
6752   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6753     emitTargetParallelRegion(CGF, S, Action);
6754   };
6755   llvm::Function *Fn;
6756   llvm::Constant *Addr;
6757   // Emit target region as a standalone region.
6758   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6759       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6760   assert(Fn && Addr && "Target device function emission failed.");
6761 }
6762 
6763 void CodeGenFunction::EmitOMPTargetParallelDirective(
6764     const OMPTargetParallelDirective &S) {
6765   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6766     emitTargetParallelRegion(CGF, S, Action);
6767   };
6768   emitCommonOMPTargetDirective(*this, S, CodeGen);
6769 }
6770 
6771 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
6772                                         const OMPTargetParallelForDirective &S,
6773                                         PrePostActionTy &Action) {
6774   Action.Enter(CGF);
6775   // Emit directive as a combined directive that consists of two implicit
6776   // directives: 'parallel' with 'for' directive.
6777   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6778     Action.Enter(CGF);
6779     CodeGenFunction::OMPCancelStackRAII CancelRegion(
6780         CGF, OMPD_target_parallel_for, S.hasCancel());
6781     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
6782                                emitDispatchForLoopBounds);
6783   };
6784   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
6785                                  emitEmptyBoundParameters);
6786 }
6787 
6788 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
6789     CodeGenModule &CGM, StringRef ParentName,
6790     const OMPTargetParallelForDirective &S) {
6791   // Emit SPMD target parallel for region as a standalone region.
6792   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6793     emitTargetParallelForRegion(CGF, S, Action);
6794   };
6795   llvm::Function *Fn;
6796   llvm::Constant *Addr;
6797   // Emit target region as a standalone region.
6798   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6799       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6800   assert(Fn && Addr && "Target device function emission failed.");
6801 }
6802 
6803 void CodeGenFunction::EmitOMPTargetParallelForDirective(
6804     const OMPTargetParallelForDirective &S) {
6805   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6806     emitTargetParallelForRegion(CGF, S, Action);
6807   };
6808   emitCommonOMPTargetDirective(*this, S, CodeGen);
6809 }
6810 
6811 static void
6812 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
6813                                 const OMPTargetParallelForSimdDirective &S,
6814                                 PrePostActionTy &Action) {
6815   Action.Enter(CGF);
6816   // Emit directive as a combined directive that consists of two implicit
6817   // directives: 'parallel' with 'for' directive.
6818   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6819     Action.Enter(CGF);
6820     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
6821                                emitDispatchForLoopBounds);
6822   };
6823   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
6824                                  emitEmptyBoundParameters);
6825 }
6826 
6827 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
6828     CodeGenModule &CGM, StringRef ParentName,
6829     const OMPTargetParallelForSimdDirective &S) {
6830   // Emit SPMD target parallel for region as a standalone region.
6831   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6832     emitTargetParallelForSimdRegion(CGF, S, Action);
6833   };
6834   llvm::Function *Fn;
6835   llvm::Constant *Addr;
6836   // Emit target region as a standalone region.
6837   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
6838       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
6839   assert(Fn && Addr && "Target device function emission failed.");
6840 }
6841 
6842 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
6843     const OMPTargetParallelForSimdDirective &S) {
6844   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
6845     emitTargetParallelForSimdRegion(CGF, S, Action);
6846   };
6847   emitCommonOMPTargetDirective(*this, S, CodeGen);
6848 }
6849 
6850 /// Emit a helper variable and return corresponding lvalue.
6851 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
6852                      const ImplicitParamDecl *PVD,
6853                      CodeGenFunction::OMPPrivateScope &Privates) {
6854   const auto *VDecl = cast<VarDecl>(Helper->getDecl());
6855   Privates.addPrivate(VDecl,
6856                       [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
6857 }
6858 
6859 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
6860   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
6861   // Emit outlined function for task construct.
6862   const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
6863   Address CapturedStruct = Address::invalid();
6864   {
6865     OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
6866     CapturedStruct = GenerateCapturedStmtArgument(*CS);
6867   }
6868   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
6869   const Expr *IfCond = nullptr;
6870   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
6871     if (C->getNameModifier() == OMPD_unknown ||
6872         C->getNameModifier() == OMPD_taskloop) {
6873       IfCond = C->getCondition();
6874       break;
6875     }
6876   }
6877 
6878   OMPTaskDataTy Data;
6879   // Check if taskloop must be emitted without taskgroup.
6880   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
6881   // TODO: Check if we should emit tied or untied task.
6882   Data.Tied = true;
6883   // Set scheduling for taskloop
6884   if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
6885     // grainsize clause
6886     Data.Schedule.setInt(/*IntVal=*/false);
6887     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
6888   } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
6889     // num_tasks clause
6890     Data.Schedule.setInt(/*IntVal=*/true);
6891     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
6892   }
6893 
6894   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
6895     // if (PreCond) {
6896     //   for (IV in 0..LastIteration) BODY;
6897     //   <Final counter/linear vars updates>;
6898     // }
6899     //
6900 
6901     // Emit: if (PreCond) - begin.
6902     // If the condition constant folds and can be elided, avoid emitting the
6903     // whole loop.
6904     bool CondConstant;
6905     llvm::BasicBlock *ContBlock = nullptr;
6906     OMPLoopScope PreInitScope(CGF, S);
6907     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
6908       if (!CondConstant)
6909         return;
6910     } else {
6911       llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
6912       ContBlock = CGF.createBasicBlock("taskloop.if.end");
6913       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
6914                   CGF.getProfileCount(&S));
6915       CGF.EmitBlock(ThenBlock);
6916       CGF.incrementProfileCounter(&S);
6917     }
6918 
6919     (void)CGF.EmitOMPLinearClauseInit(S);
6920 
6921     OMPPrivateScope LoopScope(CGF);
6922     // Emit helper vars inits.
6923     enum { LowerBound = 5, UpperBound, Stride, LastIter };
6924     auto *I = CS->getCapturedDecl()->param_begin();
6925     auto *LBP = std::next(I, LowerBound);
6926     auto *UBP = std::next(I, UpperBound);
6927     auto *STP = std::next(I, Stride);
6928     auto *LIP = std::next(I, LastIter);
6929     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
6930              LoopScope);
6931     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
6932              LoopScope);
6933     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
6934     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
6935              LoopScope);
6936     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
6937     CGF.EmitOMPLinearClause(S, LoopScope);
6938     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
6939     (void)LoopScope.Privatize();
6940     // Emit the loop iteration variable.
6941     const Expr *IVExpr = S.getIterationVariable();
6942     const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
6943     CGF.EmitVarDecl(*IVDecl);
6944     CGF.EmitIgnoredExpr(S.getInit());
6945 
6946     // Emit the iterations count variable.
6947     // If it is not a variable, Sema decided to calculate iterations count on
6948     // each iteration (e.g., it is foldable into a constant).
6949     if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
6950       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
6951       // Emit calculation of the iterations count.
6952       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
6953     }
6954 
6955     {
6956       OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
6957       emitCommonSimdLoop(
6958           CGF, S,
6959           [&S](CodeGenFunction &CGF, PrePostActionTy &) {
6960             if (isOpenMPSimdDirective(S.getDirectiveKind()))
6961               CGF.EmitOMPSimdInit(S);
6962           },
6963           [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
6964             CGF.EmitOMPInnerLoop(
6965                 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
6966                 [&S](CodeGenFunction &CGF) {
6967                   emitOMPLoopBodyWithStopPoint(CGF, S,
6968                                                CodeGenFunction::JumpDest());
6969                 },
6970                 [](CodeGenFunction &) {});
6971           });
6972     }
6973     // Emit: if (PreCond) - end.
6974     if (ContBlock) {
6975       CGF.EmitBranch(ContBlock);
6976       CGF.EmitBlock(ContBlock, true);
6977     }
6978     // Emit final copy of the lastprivate variables if IsLastIter != 0.
6979     if (HasLastprivateClause) {
6980       CGF.EmitOMPLastprivateClauseFinal(
6981           S, isOpenMPSimdDirective(S.getDirectiveKind()),
6982           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
6983               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
6984               (*LIP)->getType(), S.getBeginLoc())));
6985     }
6986     CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
6987       return CGF.Builder.CreateIsNotNull(
6988           CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
6989                                (*LIP)->getType(), S.getBeginLoc()));
6990     });
6991   };
6992   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
6993                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
6994                             const OMPTaskDataTy &Data) {
6995     auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
6996                       &Data](CodeGenFunction &CGF, PrePostActionTy &) {
6997       OMPLoopScope PreInitScope(CGF, S);
6998       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
6999                                                   OutlinedFn, SharedsTy,
7000                                                   CapturedStruct, IfCond, Data);
7001     };
7002     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
7003                                                     CodeGen);
7004   };
7005   if (Data.Nogroup) {
7006     EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
7007   } else {
7008     CGM.getOpenMPRuntime().emitTaskgroupRegion(
7009         *this,
7010         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
7011                                         PrePostActionTy &Action) {
7012           Action.Enter(CGF);
7013           CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
7014                                         Data);
7015         },
7016         S.getBeginLoc());
7017   }
7018 }
7019 
7020 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
7021   auto LPCRegion =
7022       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7023   EmitOMPTaskLoopBasedDirective(S);
7024 }
7025 
7026 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
7027     const OMPTaskLoopSimdDirective &S) {
7028   auto LPCRegion =
7029       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7030   OMPLexicalScope Scope(*this, S);
7031   EmitOMPTaskLoopBasedDirective(S);
7032 }
7033 
7034 void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
7035     const OMPMasterTaskLoopDirective &S) {
7036   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7037     Action.Enter(CGF);
7038     EmitOMPTaskLoopBasedDirective(S);
7039   };
7040   auto LPCRegion =
7041       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7042   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
7043   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7044 }
7045 
7046 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
7047     const OMPMasterTaskLoopSimdDirective &S) {
7048   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7049     Action.Enter(CGF);
7050     EmitOMPTaskLoopBasedDirective(S);
7051   };
7052   auto LPCRegion =
7053       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7054   OMPLexicalScope Scope(*this, S);
7055   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
7056 }
7057 
7058 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
7059     const OMPParallelMasterTaskLoopDirective &S) {
7060   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7061     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7062                                   PrePostActionTy &Action) {
7063       Action.Enter(CGF);
7064       CGF.EmitOMPTaskLoopBasedDirective(S);
7065     };
7066     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7067     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7068                                             S.getBeginLoc());
7069   };
7070   auto LPCRegion =
7071       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7072   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
7073                                  emitEmptyBoundParameters);
7074 }
7075 
7076 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
7077     const OMPParallelMasterTaskLoopSimdDirective &S) {
7078   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
7079     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
7080                                   PrePostActionTy &Action) {
7081       Action.Enter(CGF);
7082       CGF.EmitOMPTaskLoopBasedDirective(S);
7083     };
7084     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
7085     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
7086                                             S.getBeginLoc());
7087   };
7088   auto LPCRegion =
7089       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
7090   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
7091                                  emitEmptyBoundParameters);
7092 }
7093 
7094 // Generate the instructions for '#pragma omp target update' directive.
7095 void CodeGenFunction::EmitOMPTargetUpdateDirective(
7096     const OMPTargetUpdateDirective &S) {
7097   // If we don't have target devices, don't bother emitting the data mapping
7098   // code.
7099   if (CGM.getLangOpts().OMPTargetTriples.empty())
7100     return;
7101 
7102   // Check if we have any if clause associated with the directive.
7103   const Expr *IfCond = nullptr;
7104   if (const auto *C = S.getSingleClause<OMPIfClause>())
7105     IfCond = C->getCondition();
7106 
7107   // Check if we have any device clause associated with the directive.
7108   const Expr *Device = nullptr;
7109   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
7110     Device = C->getDevice();
7111 
7112   OMPLexicalScope Scope(*this, S, OMPD_task);
7113   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
7114 }
7115 
7116 void CodeGenFunction::EmitSimpleOMPExecutableDirective(
7117     const OMPExecutableDirective &D) {
7118   if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) {
7119     EmitOMPScanDirective(*SD);
7120     return;
7121   }
7122   if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
7123     return;
7124   auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
7125     OMPPrivateScope GlobalsScope(CGF);
7126     if (isOpenMPTaskingDirective(D.getDirectiveKind())) {
7127       // Capture global firstprivates to avoid crash.
7128       for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
7129         for (const Expr *Ref : C->varlists()) {
7130           const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts());
7131           if (!DRE)
7132             continue;
7133           const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7134           if (!VD || VD->hasLocalStorage())
7135             continue;
7136           if (!CGF.LocalDeclMap.count(VD)) {
7137             LValue GlobLVal = CGF.EmitLValue(Ref);
7138             GlobalsScope.addPrivate(
7139                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
7140           }
7141         }
7142       }
7143     }
7144     if (isOpenMPSimdDirective(D.getDirectiveKind())) {
7145       (void)GlobalsScope.Privatize();
7146       ParentLoopDirectiveForScanRegion ScanRegion(CGF, D);
7147       emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
7148     } else {
7149       if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
7150         for (const Expr *E : LD->counters()) {
7151           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
7152           if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
7153             LValue GlobLVal = CGF.EmitLValue(E);
7154             GlobalsScope.addPrivate(
7155                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
7156           }
7157           if (isa<OMPCapturedExprDecl>(VD)) {
7158             // Emit only those that were not explicitly referenced in clauses.
7159             if (!CGF.LocalDeclMap.count(VD))
7160               CGF.EmitVarDecl(*VD);
7161           }
7162         }
7163         for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
7164           if (!C->getNumForLoops())
7165             continue;
7166           for (unsigned I = LD->getLoopsNumber(),
7167                         E = C->getLoopNumIterations().size();
7168                I < E; ++I) {
7169             if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
7170                     cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
7171               // Emit only those that were not explicitly referenced in clauses.
7172               if (!CGF.LocalDeclMap.count(VD))
7173                 CGF.EmitVarDecl(*VD);
7174             }
7175           }
7176         }
7177       }
7178       (void)GlobalsScope.Privatize();
7179       CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
7180     }
7181   };
7182   if (D.getDirectiveKind() == OMPD_atomic ||
7183       D.getDirectiveKind() == OMPD_critical ||
7184       D.getDirectiveKind() == OMPD_section ||
7185       D.getDirectiveKind() == OMPD_master ||
7186       D.getDirectiveKind() == OMPD_masked) {
7187     EmitStmt(D.getAssociatedStmt());
7188   } else {
7189     auto LPCRegion =
7190         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
7191     OMPSimdLexicalScope Scope(*this, D);
7192     CGM.getOpenMPRuntime().emitInlinedDirective(
7193         *this,
7194         isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
7195                                                     : D.getDirectiveKind(),
7196         CodeGen);
7197   }
7198   // Check for outer lastprivate conditional update.
7199   checkForLastprivateConditionalUpdate(*this, D);
7200 }
7201