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