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