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