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