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