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   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3147   emitMaster(*this, S);
3148 }
3149 
3150 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
3151   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3152     Action.Enter(CGF);
3153     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3154   };
3155   const Expr *Hint = nullptr;
3156   if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
3157     Hint = HintClause->getHint();
3158   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3159   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
3160                                             S.getDirectiveName().getAsString(),
3161                                             CodeGen, S.getBeginLoc(), Hint);
3162 }
3163 
3164 void CodeGenFunction::EmitOMPParallelForDirective(
3165     const OMPParallelForDirective &S) {
3166   // Emit directive as a combined directive that consists of two implicit
3167   // directives: 'parallel' with 'for' directive.
3168   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3169     Action.Enter(CGF);
3170     OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
3171     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3172                                emitDispatchForLoopBounds);
3173   };
3174   {
3175     auto LPCRegion =
3176         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3177     emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
3178                                    emitEmptyBoundParameters);
3179   }
3180   // Check for outer lastprivate conditional update.
3181   checkForLastprivateConditionalUpdate(*this, S);
3182 }
3183 
3184 void CodeGenFunction::EmitOMPParallelForSimdDirective(
3185     const OMPParallelForSimdDirective &S) {
3186   // Emit directive as a combined directive that consists of two implicit
3187   // directives: 'parallel' with 'for' directive.
3188   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3189     Action.Enter(CGF);
3190     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
3191                                emitDispatchForLoopBounds);
3192   };
3193   {
3194     auto LPCRegion =
3195         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3196     emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
3197                                    emitEmptyBoundParameters);
3198   }
3199   // Check for outer lastprivate conditional update.
3200   checkForLastprivateConditionalUpdate(*this, S);
3201 }
3202 
3203 void CodeGenFunction::EmitOMPParallelMasterDirective(
3204     const OMPParallelMasterDirective &S) {
3205   // Emit directive as a combined directive that consists of two implicit
3206   // directives: 'parallel' with 'master' directive.
3207   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3208     Action.Enter(CGF);
3209     OMPPrivateScope PrivateScope(CGF);
3210     bool Copyins = CGF.EmitOMPCopyinClause(S);
3211     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
3212     if (Copyins) {
3213       // Emit implicit barrier to synchronize threads and avoid data races on
3214       // propagation master's thread values of threadprivate variables to local
3215       // instances of that variables of all other implicit threads.
3216       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
3217           CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3218           /*ForceSimpleCall=*/true);
3219     }
3220     CGF.EmitOMPPrivateClause(S, PrivateScope);
3221     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
3222     (void)PrivateScope.Privatize();
3223     emitMaster(CGF, S);
3224     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
3225   };
3226   {
3227     auto LPCRegion =
3228         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3229     emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen,
3230                                    emitEmptyBoundParameters);
3231     emitPostUpdateForReductionClause(*this, S,
3232                                      [](CodeGenFunction &) { return nullptr; });
3233   }
3234   // Check for outer lastprivate conditional update.
3235   checkForLastprivateConditionalUpdate(*this, S);
3236 }
3237 
3238 void CodeGenFunction::EmitOMPParallelSectionsDirective(
3239     const OMPParallelSectionsDirective &S) {
3240   // Emit directive as a combined directive that consists of two implicit
3241   // directives: 'parallel' with 'sections' directive.
3242   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3243     Action.Enter(CGF);
3244     CGF.EmitSections(S);
3245   };
3246   {
3247     auto LPCRegion =
3248         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3249     emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
3250                                    emitEmptyBoundParameters);
3251   }
3252   // Check for outer lastprivate conditional update.
3253   checkForLastprivateConditionalUpdate(*this, S);
3254 }
3255 
3256 void CodeGenFunction::EmitOMPTaskBasedDirective(
3257     const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
3258     const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
3259     OMPTaskDataTy &Data) {
3260   // Emit outlined function for task construct.
3261   const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
3262   auto I = CS->getCapturedDecl()->param_begin();
3263   auto PartId = std::next(I);
3264   auto TaskT = std::next(I, 4);
3265   // Check if the task is final
3266   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
3267     // If the condition constant folds and can be elided, try to avoid emitting
3268     // the condition and the dead arm of the if/else.
3269     const Expr *Cond = Clause->getCondition();
3270     bool CondConstant;
3271     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
3272       Data.Final.setInt(CondConstant);
3273     else
3274       Data.Final.setPointer(EvaluateExprAsBool(Cond));
3275   } else {
3276     // By default the task is not final.
3277     Data.Final.setInt(/*IntVal=*/false);
3278   }
3279   // Check if the task has 'priority' clause.
3280   if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
3281     const Expr *Prio = Clause->getPriority();
3282     Data.Priority.setInt(/*IntVal=*/true);
3283     Data.Priority.setPointer(EmitScalarConversion(
3284         EmitScalarExpr(Prio), Prio->getType(),
3285         getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
3286         Prio->getExprLoc()));
3287   }
3288   // The first function argument for tasks is a thread id, the second one is a
3289   // part id (0 for tied tasks, >=0 for untied task).
3290   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
3291   // Get list of private variables.
3292   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
3293     auto IRef = C->varlist_begin();
3294     for (const Expr *IInit : C->private_copies()) {
3295       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3296       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3297         Data.PrivateVars.push_back(*IRef);
3298         Data.PrivateCopies.push_back(IInit);
3299       }
3300       ++IRef;
3301     }
3302   }
3303   EmittedAsPrivate.clear();
3304   // Get list of firstprivate variables.
3305   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3306     auto IRef = C->varlist_begin();
3307     auto IElemInitRef = C->inits().begin();
3308     for (const Expr *IInit : C->private_copies()) {
3309       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3310       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3311         Data.FirstprivateVars.push_back(*IRef);
3312         Data.FirstprivateCopies.push_back(IInit);
3313         Data.FirstprivateInits.push_back(*IElemInitRef);
3314       }
3315       ++IRef;
3316       ++IElemInitRef;
3317     }
3318   }
3319   // Get list of lastprivate variables (for taskloops).
3320   llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
3321   for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
3322     auto IRef = C->varlist_begin();
3323     auto ID = C->destination_exprs().begin();
3324     for (const Expr *IInit : C->private_copies()) {
3325       const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
3326       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
3327         Data.LastprivateVars.push_back(*IRef);
3328         Data.LastprivateCopies.push_back(IInit);
3329       }
3330       LastprivateDstsOrigs.insert(
3331           {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
3332            cast<DeclRefExpr>(*IRef)});
3333       ++IRef;
3334       ++ID;
3335     }
3336   }
3337   SmallVector<const Expr *, 4> LHSs;
3338   SmallVector<const Expr *, 4> RHSs;
3339   for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
3340     auto IPriv = C->privates().begin();
3341     auto IRed = C->reduction_ops().begin();
3342     auto ILHS = C->lhs_exprs().begin();
3343     auto IRHS = C->rhs_exprs().begin();
3344     for (const Expr *Ref : C->varlists()) {
3345       Data.ReductionVars.emplace_back(Ref);
3346       Data.ReductionCopies.emplace_back(*IPriv);
3347       Data.ReductionOps.emplace_back(*IRed);
3348       LHSs.emplace_back(*ILHS);
3349       RHSs.emplace_back(*IRHS);
3350       std::advance(IPriv, 1);
3351       std::advance(IRed, 1);
3352       std::advance(ILHS, 1);
3353       std::advance(IRHS, 1);
3354     }
3355   }
3356   Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
3357       *this, S.getBeginLoc(), LHSs, RHSs, Data);
3358   // Build list of dependences.
3359   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3360     for (const Expr *IRef : C->varlists())
3361       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3362   auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
3363                     CapturedRegion](CodeGenFunction &CGF,
3364                                     PrePostActionTy &Action) {
3365     // Set proper addresses for generated private copies.
3366     OMPPrivateScope Scope(CGF);
3367     if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
3368         !Data.LastprivateVars.empty()) {
3369       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3370           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3371       enum { PrivatesParam = 2, CopyFnParam = 3 };
3372       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3373           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3374       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3375           CS->getCapturedDecl()->getParam(PrivatesParam)));
3376       // Map privates.
3377       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3378       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3379       CallArgs.push_back(PrivatesPtr);
3380       for (const Expr *E : Data.PrivateVars) {
3381         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3382         Address PrivatePtr = CGF.CreateMemTemp(
3383             CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
3384         PrivatePtrs.emplace_back(VD, PrivatePtr);
3385         CallArgs.push_back(PrivatePtr.getPointer());
3386       }
3387       for (const Expr *E : Data.FirstprivateVars) {
3388         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3389         Address PrivatePtr =
3390             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3391                               ".firstpriv.ptr.addr");
3392         PrivatePtrs.emplace_back(VD, PrivatePtr);
3393         CallArgs.push_back(PrivatePtr.getPointer());
3394       }
3395       for (const Expr *E : Data.LastprivateVars) {
3396         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3397         Address PrivatePtr =
3398             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3399                               ".lastpriv.ptr.addr");
3400         PrivatePtrs.emplace_back(VD, PrivatePtr);
3401         CallArgs.push_back(PrivatePtr.getPointer());
3402       }
3403       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3404           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3405       for (const auto &Pair : LastprivateDstsOrigs) {
3406         const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
3407         DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD),
3408                         /*RefersToEnclosingVariableOrCapture=*/
3409                             CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
3410                         Pair.second->getType(), VK_LValue,
3411                         Pair.second->getExprLoc());
3412         Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
3413           return CGF.EmitLValue(&DRE).getAddress(CGF);
3414         });
3415       }
3416       for (const auto &Pair : PrivatePtrs) {
3417         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3418                             CGF.getContext().getDeclAlign(Pair.first));
3419         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3420       }
3421     }
3422     if (Data.Reductions) {
3423       OMPLexicalScope LexScope(CGF, S, CapturedRegion);
3424       ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
3425                              Data.ReductionOps);
3426       llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
3427           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
3428       for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
3429         RedCG.emitSharedLValue(CGF, Cnt);
3430         RedCG.emitAggregateType(CGF, Cnt);
3431         // FIXME: This must removed once the runtime library is fixed.
3432         // Emit required threadprivate variables for
3433         // initializer/combiner/finalizer.
3434         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3435                                                            RedCG, Cnt);
3436         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3437             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3438         Replacement =
3439             Address(CGF.EmitScalarConversion(
3440                         Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3441                         CGF.getContext().getPointerType(
3442                             Data.ReductionCopies[Cnt]->getType()),
3443                         Data.ReductionCopies[Cnt]->getExprLoc()),
3444                     Replacement.getAlignment());
3445         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3446         Scope.addPrivate(RedCG.getBaseDecl(Cnt),
3447                          [Replacement]() { return Replacement; });
3448       }
3449     }
3450     // Privatize all private variables except for in_reduction items.
3451     (void)Scope.Privatize();
3452     SmallVector<const Expr *, 4> InRedVars;
3453     SmallVector<const Expr *, 4> InRedPrivs;
3454     SmallVector<const Expr *, 4> InRedOps;
3455     SmallVector<const Expr *, 4> TaskgroupDescriptors;
3456     for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
3457       auto IPriv = C->privates().begin();
3458       auto IRed = C->reduction_ops().begin();
3459       auto ITD = C->taskgroup_descriptors().begin();
3460       for (const Expr *Ref : C->varlists()) {
3461         InRedVars.emplace_back(Ref);
3462         InRedPrivs.emplace_back(*IPriv);
3463         InRedOps.emplace_back(*IRed);
3464         TaskgroupDescriptors.emplace_back(*ITD);
3465         std::advance(IPriv, 1);
3466         std::advance(IRed, 1);
3467         std::advance(ITD, 1);
3468       }
3469     }
3470     // Privatize in_reduction items here, because taskgroup descriptors must be
3471     // privatized earlier.
3472     OMPPrivateScope InRedScope(CGF);
3473     if (!InRedVars.empty()) {
3474       ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
3475       for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
3476         RedCG.emitSharedLValue(CGF, Cnt);
3477         RedCG.emitAggregateType(CGF, Cnt);
3478         // The taskgroup descriptor variable is always implicit firstprivate and
3479         // privatized already during processing of the firstprivates.
3480         // FIXME: This must removed once the runtime library is fixed.
3481         // Emit required threadprivate variables for
3482         // initializer/combiner/finalizer.
3483         CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
3484                                                            RedCG, Cnt);
3485         llvm::Value *ReductionsPtr =
3486             CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
3487                                  TaskgroupDescriptors[Cnt]->getExprLoc());
3488         Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
3489             CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
3490         Replacement = Address(
3491             CGF.EmitScalarConversion(
3492                 Replacement.getPointer(), CGF.getContext().VoidPtrTy,
3493                 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
3494                 InRedPrivs[Cnt]->getExprLoc()),
3495             Replacement.getAlignment());
3496         Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
3497         InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
3498                               [Replacement]() { return Replacement; });
3499       }
3500     }
3501     (void)InRedScope.Privatize();
3502 
3503     Action.Enter(CGF);
3504     BodyGen(CGF);
3505   };
3506   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3507       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
3508       Data.NumberOfParts);
3509   OMPLexicalScope Scope(*this, S, llvm::None,
3510                         !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3511                             !isOpenMPSimdDirective(S.getDirectiveKind()));
3512   TaskGen(*this, OutlinedFn, Data);
3513 }
3514 
3515 static ImplicitParamDecl *
3516 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
3517                                   QualType Ty, CapturedDecl *CD,
3518                                   SourceLocation Loc) {
3519   auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3520                                            ImplicitParamDecl::Other);
3521   auto *OrigRef = DeclRefExpr::Create(
3522       C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
3523       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3524   auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
3525                                               ImplicitParamDecl::Other);
3526   auto *PrivateRef = DeclRefExpr::Create(
3527       C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
3528       /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
3529   QualType ElemType = C.getBaseElementType(Ty);
3530   auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
3531                                            ImplicitParamDecl::Other);
3532   auto *InitRef = DeclRefExpr::Create(
3533       C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
3534       /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
3535   PrivateVD->setInitStyle(VarDecl::CInit);
3536   PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
3537                                               InitRef, /*BasePath=*/nullptr,
3538                                               VK_RValue));
3539   Data.FirstprivateVars.emplace_back(OrigRef);
3540   Data.FirstprivateCopies.emplace_back(PrivateRef);
3541   Data.FirstprivateInits.emplace_back(InitRef);
3542   return OrigVD;
3543 }
3544 
3545 void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
3546     const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
3547     OMPTargetDataInfo &InputInfo) {
3548   // Emit outlined function for task construct.
3549   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3550   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3551   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3552   auto I = CS->getCapturedDecl()->param_begin();
3553   auto PartId = std::next(I);
3554   auto TaskT = std::next(I, 4);
3555   OMPTaskDataTy Data;
3556   // The task is not final.
3557   Data.Final.setInt(/*IntVal=*/false);
3558   // Get list of firstprivate variables.
3559   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
3560     auto IRef = C->varlist_begin();
3561     auto IElemInitRef = C->inits().begin();
3562     for (auto *IInit : C->private_copies()) {
3563       Data.FirstprivateVars.push_back(*IRef);
3564       Data.FirstprivateCopies.push_back(IInit);
3565       Data.FirstprivateInits.push_back(*IElemInitRef);
3566       ++IRef;
3567       ++IElemInitRef;
3568     }
3569   }
3570   OMPPrivateScope TargetScope(*this);
3571   VarDecl *BPVD = nullptr;
3572   VarDecl *PVD = nullptr;
3573   VarDecl *SVD = nullptr;
3574   if (InputInfo.NumberOfTargetItems > 0) {
3575     auto *CD = CapturedDecl::Create(
3576         getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
3577     llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
3578     QualType BaseAndPointersType = getContext().getConstantArrayType(
3579         getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal,
3580         /*IndexTypeQuals=*/0);
3581     BPVD = createImplicitFirstprivateForType(
3582         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3583     PVD = createImplicitFirstprivateForType(
3584         getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
3585     QualType SizesType = getContext().getConstantArrayType(
3586         getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1),
3587         ArrSize, nullptr, ArrayType::Normal,
3588         /*IndexTypeQuals=*/0);
3589     SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
3590                                             S.getBeginLoc());
3591     TargetScope.addPrivate(
3592         BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
3593     TargetScope.addPrivate(PVD,
3594                            [&InputInfo]() { return InputInfo.PointersArray; });
3595     TargetScope.addPrivate(SVD,
3596                            [&InputInfo]() { return InputInfo.SizesArray; });
3597   }
3598   (void)TargetScope.Privatize();
3599   // Build list of dependences.
3600   for (const auto *C : S.getClausesOfKind<OMPDependClause>())
3601     for (const Expr *IRef : C->varlists())
3602       Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
3603   auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
3604                     &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
3605     // Set proper addresses for generated private copies.
3606     OMPPrivateScope Scope(CGF);
3607     if (!Data.FirstprivateVars.empty()) {
3608       llvm::FunctionType *CopyFnTy = llvm::FunctionType::get(
3609           CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true);
3610       enum { PrivatesParam = 2, CopyFnParam = 3 };
3611       llvm::Value *CopyFn = CGF.Builder.CreateLoad(
3612           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
3613       llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
3614           CS->getCapturedDecl()->getParam(PrivatesParam)));
3615       // Map privates.
3616       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
3617       llvm::SmallVector<llvm::Value *, 16> CallArgs;
3618       CallArgs.push_back(PrivatesPtr);
3619       for (const Expr *E : Data.FirstprivateVars) {
3620         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3621         Address PrivatePtr =
3622             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
3623                               ".firstpriv.ptr.addr");
3624         PrivatePtrs.emplace_back(VD, PrivatePtr);
3625         CallArgs.push_back(PrivatePtr.getPointer());
3626       }
3627       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3628           CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs);
3629       for (const auto &Pair : PrivatePtrs) {
3630         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
3631                             CGF.getContext().getDeclAlign(Pair.first));
3632         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
3633       }
3634     }
3635     // Privatize all private variables except for in_reduction items.
3636     (void)Scope.Privatize();
3637     if (InputInfo.NumberOfTargetItems > 0) {
3638       InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
3639           CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0);
3640       InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
3641           CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
3642       InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
3643           CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
3644     }
3645 
3646     Action.Enter(CGF);
3647     OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
3648     BodyGen(CGF);
3649   };
3650   llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
3651       S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
3652       Data.NumberOfParts);
3653   llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
3654   IntegerLiteral IfCond(getContext(), TrueOrFalse,
3655                         getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3656                         SourceLocation());
3657 
3658   CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
3659                                       SharedsTy, CapturedStruct, &IfCond, Data);
3660 }
3661 
3662 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
3663   // Emit outlined function for task construct.
3664   const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
3665   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
3666   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
3667   const Expr *IfCond = nullptr;
3668   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
3669     if (C->getNameModifier() == OMPD_unknown ||
3670         C->getNameModifier() == OMPD_task) {
3671       IfCond = C->getCondition();
3672       break;
3673     }
3674   }
3675 
3676   OMPTaskDataTy Data;
3677   // Check if we should emit tied or untied task.
3678   Data.Tied = !S.getSingleClause<OMPUntiedClause>();
3679   auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
3680     CGF.EmitStmt(CS->getCapturedStmt());
3681   };
3682   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
3683                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
3684                             const OMPTaskDataTy &Data) {
3685     CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
3686                                             SharedsTy, CapturedStruct, IfCond,
3687                                             Data);
3688   };
3689   auto LPCRegion =
3690       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
3691   EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
3692 }
3693 
3694 void CodeGenFunction::EmitOMPTaskyieldDirective(
3695     const OMPTaskyieldDirective &S) {
3696   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
3697 }
3698 
3699 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
3700   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
3701 }
3702 
3703 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
3704   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
3705 }
3706 
3707 void CodeGenFunction::EmitOMPTaskgroupDirective(
3708     const OMPTaskgroupDirective &S) {
3709   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
3710     Action.Enter(CGF);
3711     if (const Expr *E = S.getReductionRef()) {
3712       SmallVector<const Expr *, 4> LHSs;
3713       SmallVector<const Expr *, 4> RHSs;
3714       OMPTaskDataTy Data;
3715       for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
3716         auto IPriv = C->privates().begin();
3717         auto IRed = C->reduction_ops().begin();
3718         auto ILHS = C->lhs_exprs().begin();
3719         auto IRHS = C->rhs_exprs().begin();
3720         for (const Expr *Ref : C->varlists()) {
3721           Data.ReductionVars.emplace_back(Ref);
3722           Data.ReductionCopies.emplace_back(*IPriv);
3723           Data.ReductionOps.emplace_back(*IRed);
3724           LHSs.emplace_back(*ILHS);
3725           RHSs.emplace_back(*IRHS);
3726           std::advance(IPriv, 1);
3727           std::advance(IRed, 1);
3728           std::advance(ILHS, 1);
3729           std::advance(IRHS, 1);
3730         }
3731       }
3732       llvm::Value *ReductionDesc =
3733           CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
3734                                                            LHSs, RHSs, Data);
3735       const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3736       CGF.EmitVarDecl(*VD);
3737       CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
3738                             /*Volatile=*/false, E->getType());
3739     }
3740     CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
3741   };
3742   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3743   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
3744 }
3745 
3746 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
3747   llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>()
3748                                 ? llvm::AtomicOrdering::NotAtomic
3749                                 : llvm::AtomicOrdering::AcquireRelease;
3750   CGM.getOpenMPRuntime().emitFlush(
3751       *this,
3752       [&S]() -> ArrayRef<const Expr *> {
3753         if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
3754           return llvm::makeArrayRef(FlushClause->varlist_begin(),
3755                                     FlushClause->varlist_end());
3756         return llvm::None;
3757       }(),
3758       S.getBeginLoc(), AO);
3759 }
3760 
3761 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
3762                                             const CodeGenLoopTy &CodeGenLoop,
3763                                             Expr *IncExpr) {
3764   // Emit the loop iteration variable.
3765   const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
3766   const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
3767   EmitVarDecl(*IVDecl);
3768 
3769   // Emit the iterations count variable.
3770   // If it is not a variable, Sema decided to calculate iterations count on each
3771   // iteration (e.g., it is foldable into a constant).
3772   if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
3773     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
3774     // Emit calculation of the iterations count.
3775     EmitIgnoredExpr(S.getCalcLastIteration());
3776   }
3777 
3778   CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
3779 
3780   bool HasLastprivateClause = false;
3781   // Check pre-condition.
3782   {
3783     OMPLoopScope PreInitScope(*this, S);
3784     // Skip the entire loop if we don't meet the precondition.
3785     // If the condition constant folds and can be elided, avoid emitting the
3786     // whole loop.
3787     bool CondConstant;
3788     llvm::BasicBlock *ContBlock = nullptr;
3789     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
3790       if (!CondConstant)
3791         return;
3792     } else {
3793       llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
3794       ContBlock = createBasicBlock("omp.precond.end");
3795       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
3796                   getProfileCount(&S));
3797       EmitBlock(ThenBlock);
3798       incrementProfileCounter(&S);
3799     }
3800 
3801     emitAlignedClause(*this, S);
3802     // Emit 'then' code.
3803     {
3804       // Emit helper vars inits.
3805 
3806       LValue LB = EmitOMPHelperVar(
3807           *this, cast<DeclRefExpr>(
3808                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3809                           ? S.getCombinedLowerBoundVariable()
3810                           : S.getLowerBoundVariable())));
3811       LValue UB = EmitOMPHelperVar(
3812           *this, cast<DeclRefExpr>(
3813                      (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3814                           ? S.getCombinedUpperBoundVariable()
3815                           : S.getUpperBoundVariable())));
3816       LValue ST =
3817           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
3818       LValue IL =
3819           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
3820 
3821       OMPPrivateScope LoopScope(*this);
3822       if (EmitOMPFirstprivateClause(S, LoopScope)) {
3823         // Emit implicit barrier to synchronize threads and avoid data races
3824         // on initialization of firstprivate variables and post-update of
3825         // lastprivate variables.
3826         CGM.getOpenMPRuntime().emitBarrierCall(
3827             *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
3828             /*ForceSimpleCall=*/true);
3829       }
3830       EmitOMPPrivateClause(S, LoopScope);
3831       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3832           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3833           !isOpenMPTeamsDirective(S.getDirectiveKind()))
3834         EmitOMPReductionClauseInit(S, LoopScope);
3835       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
3836       EmitOMPPrivateLoopCounters(S, LoopScope);
3837       (void)LoopScope.Privatize();
3838       if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
3839         CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S);
3840 
3841       // Detect the distribute schedule kind and chunk.
3842       llvm::Value *Chunk = nullptr;
3843       OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
3844       if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
3845         ScheduleKind = C->getDistScheduleKind();
3846         if (const Expr *Ch = C->getChunkSize()) {
3847           Chunk = EmitScalarExpr(Ch);
3848           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
3849                                        S.getIterationVariable()->getType(),
3850                                        S.getBeginLoc());
3851         }
3852       } else {
3853         // Default behaviour for dist_schedule clause.
3854         CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
3855             *this, S, ScheduleKind, Chunk);
3856       }
3857       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
3858       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
3859 
3860       // OpenMP [2.10.8, distribute Construct, Description]
3861       // If dist_schedule is specified, kind must be static. If specified,
3862       // iterations are divided into chunks of size chunk_size, chunks are
3863       // assigned to the teams of the league in a round-robin fashion in the
3864       // order of the team number. When no chunk_size is specified, the
3865       // iteration space is divided into chunks that are approximately equal
3866       // in size, and at most one chunk is distributed to each team of the
3867       // league. The size of the chunks is unspecified in this case.
3868       bool StaticChunked = RT.isStaticChunked(
3869           ScheduleKind, /* Chunked */ Chunk != nullptr) &&
3870           isOpenMPLoopBoundSharingDirective(S.getDirectiveKind());
3871       if (RT.isStaticNonchunked(ScheduleKind,
3872                                 /* Chunked */ Chunk != nullptr) ||
3873           StaticChunked) {
3874         CGOpenMPRuntime::StaticRTInput StaticInit(
3875             IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this),
3876             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3877             StaticChunked ? Chunk : nullptr);
3878         RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
3879                                     StaticInit);
3880         JumpDest LoopExit =
3881             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
3882         // UB = min(UB, GlobalUB);
3883         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3884                             ? S.getCombinedEnsureUpperBound()
3885                             : S.getEnsureUpperBound());
3886         // IV = LB;
3887         EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3888                             ? S.getCombinedInit()
3889                             : S.getInit());
3890 
3891         const Expr *Cond =
3892             isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
3893                 ? S.getCombinedCond()
3894                 : S.getCond();
3895 
3896         if (StaticChunked)
3897           Cond = S.getCombinedDistCond();
3898 
3899         // For static unchunked schedules generate:
3900         //
3901         //  1. For distribute alone, codegen
3902         //    while (idx <= UB) {
3903         //      BODY;
3904         //      ++idx;
3905         //    }
3906         //
3907         //  2. When combined with 'for' (e.g. as in 'distribute parallel for')
3908         //    while (idx <= UB) {
3909         //      <CodeGen rest of pragma>(LB, UB);
3910         //      idx += ST;
3911         //    }
3912         //
3913         // For static chunk one schedule generate:
3914         //
3915         // while (IV <= GlobalUB) {
3916         //   <CodeGen rest of pragma>(LB, UB);
3917         //   LB += ST;
3918         //   UB += ST;
3919         //   UB = min(UB, GlobalUB);
3920         //   IV = LB;
3921         // }
3922         //
3923         emitCommonSimdLoop(
3924             *this, S,
3925             [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3926               if (isOpenMPSimdDirective(S.getDirectiveKind()))
3927                 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true);
3928             },
3929             [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop,
3930              StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) {
3931               CGF.EmitOMPInnerLoop(
3932                   S, LoopScope.requiresCleanups(), Cond, IncExpr,
3933                   [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
3934                     CodeGenLoop(CGF, S, LoopExit);
3935                   },
3936                   [&S, StaticChunked](CodeGenFunction &CGF) {
3937                     if (StaticChunked) {
3938                       CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound());
3939                       CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound());
3940                       CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound());
3941                       CGF.EmitIgnoredExpr(S.getCombinedInit());
3942                     }
3943                   });
3944             });
3945         EmitBlock(LoopExit.getBlock());
3946         // Tell the runtime we are done.
3947         RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind());
3948       } else {
3949         // Emit the outer loop, which requests its work chunk [LB..UB] from
3950         // runtime and runs the inner loop to process it.
3951         const OMPLoopArguments LoopArguments = {
3952             LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this),
3953             IL.getAddress(*this), Chunk};
3954         EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
3955                                    CodeGenLoop);
3956       }
3957       if (isOpenMPSimdDirective(S.getDirectiveKind())) {
3958         EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
3959           return CGF.Builder.CreateIsNotNull(
3960               CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3961         });
3962       }
3963       if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
3964           !isOpenMPParallelDirective(S.getDirectiveKind()) &&
3965           !isOpenMPTeamsDirective(S.getDirectiveKind())) {
3966         EmitOMPReductionClauseFinal(S, OMPD_simd);
3967         // Emit post-update of the reduction variables if IsLastIter != 0.
3968         emitPostUpdateForReductionClause(
3969             *this, S, [IL, &S](CodeGenFunction &CGF) {
3970               return CGF.Builder.CreateIsNotNull(
3971                   CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
3972             });
3973       }
3974       // Emit final copy of the lastprivate variables if IsLastIter != 0.
3975       if (HasLastprivateClause) {
3976         EmitOMPLastprivateClauseFinal(
3977             S, /*NoFinals=*/false,
3978             Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
3979       }
3980     }
3981 
3982     // We're now done with the loop, so jump to the continuation block.
3983     if (ContBlock) {
3984       EmitBranch(ContBlock);
3985       EmitBlock(ContBlock, true);
3986     }
3987   }
3988 }
3989 
3990 void CodeGenFunction::EmitOMPDistributeDirective(
3991     const OMPDistributeDirective &S) {
3992   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
3993     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
3994   };
3995   OMPLexicalScope Scope(*this, S, OMPD_unknown);
3996   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
3997 }
3998 
3999 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
4000                                                    const CapturedStmt *S,
4001                                                    SourceLocation Loc) {
4002   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4003   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
4004   CGF.CapturedStmtInfo = &CapStmtInfo;
4005   llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc);
4006   Fn->setDoesNotRecurse();
4007   return Fn;
4008 }
4009 
4010 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
4011   if (S.hasClausesOfKind<OMPDependClause>()) {
4012     assert(!S.getAssociatedStmt() &&
4013            "No associated statement must be in ordered depend construct.");
4014     for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
4015       CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
4016     return;
4017   }
4018   const auto *C = S.getSingleClause<OMPSIMDClause>();
4019   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
4020                                  PrePostActionTy &Action) {
4021     const CapturedStmt *CS = S.getInnermostCapturedStmt();
4022     if (C) {
4023       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4024       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
4025       llvm::Function *OutlinedFn =
4026           emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc());
4027       CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
4028                                                       OutlinedFn, CapturedVars);
4029     } else {
4030       Action.Enter(CGF);
4031       CGF.EmitStmt(CS->getCapturedStmt());
4032     }
4033   };
4034   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4035   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
4036 }
4037 
4038 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
4039                                          QualType SrcType, QualType DestType,
4040                                          SourceLocation Loc) {
4041   assert(CGF.hasScalarEvaluationKind(DestType) &&
4042          "DestType must have scalar evaluation kind.");
4043   assert(!Val.isAggregate() && "Must be a scalar or complex.");
4044   return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
4045                                                    DestType, Loc)
4046                         : CGF.EmitComplexToScalarConversion(
4047                               Val.getComplexVal(), SrcType, DestType, Loc);
4048 }
4049 
4050 static CodeGenFunction::ComplexPairTy
4051 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
4052                       QualType DestType, SourceLocation Loc) {
4053   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
4054          "DestType must have complex evaluation kind.");
4055   CodeGenFunction::ComplexPairTy ComplexVal;
4056   if (Val.isScalar()) {
4057     // Convert the input element to the element type of the complex.
4058     QualType DestElementType =
4059         DestType->castAs<ComplexType>()->getElementType();
4060     llvm::Value *ScalarVal = CGF.EmitScalarConversion(
4061         Val.getScalarVal(), SrcType, DestElementType, Loc);
4062     ComplexVal = CodeGenFunction::ComplexPairTy(
4063         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
4064   } else {
4065     assert(Val.isComplex() && "Must be a scalar or complex.");
4066     QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
4067     QualType DestElementType =
4068         DestType->castAs<ComplexType>()->getElementType();
4069     ComplexVal.first = CGF.EmitScalarConversion(
4070         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
4071     ComplexVal.second = CGF.EmitScalarConversion(
4072         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
4073   }
4074   return ComplexVal;
4075 }
4076 
4077 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
4078                                   LValue LVal, RValue RVal) {
4079   if (LVal.isGlobalReg())
4080     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
4081   else
4082     CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false);
4083 }
4084 
4085 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF,
4086                                    llvm::AtomicOrdering AO, LValue LVal,
4087                                    SourceLocation Loc) {
4088   if (LVal.isGlobalReg())
4089     return CGF.EmitLoadOfLValue(LVal, Loc);
4090   return CGF.EmitAtomicLoad(
4091       LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO),
4092       LVal.isVolatile());
4093 }
4094 
4095 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
4096                                          QualType RValTy, SourceLocation Loc) {
4097   switch (getEvaluationKind(LVal.getType())) {
4098   case TEK_Scalar:
4099     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
4100                                *this, RVal, RValTy, LVal.getType(), Loc)),
4101                            LVal);
4102     break;
4103   case TEK_Complex:
4104     EmitStoreOfComplex(
4105         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
4106         /*isInit=*/false);
4107     break;
4108   case TEK_Aggregate:
4109     llvm_unreachable("Must be a scalar or complex.");
4110   }
4111 }
4112 
4113 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO,
4114                                   const Expr *X, const Expr *V,
4115                                   SourceLocation Loc) {
4116   // v = x;
4117   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
4118   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
4119   LValue XLValue = CGF.EmitLValue(X);
4120   LValue VLValue = CGF.EmitLValue(V);
4121   RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc);
4122   // OpenMP, 2.17.7, atomic Construct
4123   // If the read or capture clause is specified and the acquire, acq_rel, or
4124   // seq_cst clause is specified then the strong flush on exit from the atomic
4125   // operation is also an acquire flush.
4126   switch (AO) {
4127   case llvm::AtomicOrdering::Acquire:
4128   case llvm::AtomicOrdering::AcquireRelease:
4129   case llvm::AtomicOrdering::SequentiallyConsistent:
4130     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4131                                          llvm::AtomicOrdering::Acquire);
4132     break;
4133   case llvm::AtomicOrdering::Monotonic:
4134   case llvm::AtomicOrdering::Release:
4135     break;
4136   case llvm::AtomicOrdering::NotAtomic:
4137   case llvm::AtomicOrdering::Unordered:
4138     llvm_unreachable("Unexpected ordering.");
4139   }
4140   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
4141   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
4142 }
4143 
4144 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF,
4145                                    llvm::AtomicOrdering AO, const Expr *X,
4146                                    const Expr *E, SourceLocation Loc) {
4147   // x = expr;
4148   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
4149   emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
4150   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4151   // OpenMP, 2.17.7, atomic Construct
4152   // If the write, update, or capture clause is specified and the release,
4153   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
4154   // the atomic operation is also a release flush.
4155   switch (AO) {
4156   case llvm::AtomicOrdering::Release:
4157   case llvm::AtomicOrdering::AcquireRelease:
4158   case llvm::AtomicOrdering::SequentiallyConsistent:
4159     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4160                                          llvm::AtomicOrdering::Release);
4161     break;
4162   case llvm::AtomicOrdering::Acquire:
4163   case llvm::AtomicOrdering::Monotonic:
4164     break;
4165   case llvm::AtomicOrdering::NotAtomic:
4166   case llvm::AtomicOrdering::Unordered:
4167     llvm_unreachable("Unexpected ordering.");
4168   }
4169 }
4170 
4171 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
4172                                                 RValue Update,
4173                                                 BinaryOperatorKind BO,
4174                                                 llvm::AtomicOrdering AO,
4175                                                 bool IsXLHSInRHSPart) {
4176   ASTContext &Context = CGF.getContext();
4177   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
4178   // expression is simple and atomic is allowed for the given type for the
4179   // target platform.
4180   if (BO == BO_Comma || !Update.isScalar() ||
4181       !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
4182       (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
4183        (Update.getScalarVal()->getType() !=
4184         X.getAddress(CGF).getElementType())) ||
4185       !X.getAddress(CGF).getElementType()->isIntegerTy() ||
4186       !Context.getTargetInfo().hasBuiltinAtomic(
4187           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
4188     return std::make_pair(false, RValue::get(nullptr));
4189 
4190   llvm::AtomicRMWInst::BinOp RMWOp;
4191   switch (BO) {
4192   case BO_Add:
4193     RMWOp = llvm::AtomicRMWInst::Add;
4194     break;
4195   case BO_Sub:
4196     if (!IsXLHSInRHSPart)
4197       return std::make_pair(false, RValue::get(nullptr));
4198     RMWOp = llvm::AtomicRMWInst::Sub;
4199     break;
4200   case BO_And:
4201     RMWOp = llvm::AtomicRMWInst::And;
4202     break;
4203   case BO_Or:
4204     RMWOp = llvm::AtomicRMWInst::Or;
4205     break;
4206   case BO_Xor:
4207     RMWOp = llvm::AtomicRMWInst::Xor;
4208     break;
4209   case BO_LT:
4210     RMWOp = X.getType()->hasSignedIntegerRepresentation()
4211                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
4212                                    : llvm::AtomicRMWInst::Max)
4213                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
4214                                    : llvm::AtomicRMWInst::UMax);
4215     break;
4216   case BO_GT:
4217     RMWOp = X.getType()->hasSignedIntegerRepresentation()
4218                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
4219                                    : llvm::AtomicRMWInst::Min)
4220                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
4221                                    : llvm::AtomicRMWInst::UMin);
4222     break;
4223   case BO_Assign:
4224     RMWOp = llvm::AtomicRMWInst::Xchg;
4225     break;
4226   case BO_Mul:
4227   case BO_Div:
4228   case BO_Rem:
4229   case BO_Shl:
4230   case BO_Shr:
4231   case BO_LAnd:
4232   case BO_LOr:
4233     return std::make_pair(false, RValue::get(nullptr));
4234   case BO_PtrMemD:
4235   case BO_PtrMemI:
4236   case BO_LE:
4237   case BO_GE:
4238   case BO_EQ:
4239   case BO_NE:
4240   case BO_Cmp:
4241   case BO_AddAssign:
4242   case BO_SubAssign:
4243   case BO_AndAssign:
4244   case BO_OrAssign:
4245   case BO_XorAssign:
4246   case BO_MulAssign:
4247   case BO_DivAssign:
4248   case BO_RemAssign:
4249   case BO_ShlAssign:
4250   case BO_ShrAssign:
4251   case BO_Comma:
4252     llvm_unreachable("Unsupported atomic update operation");
4253   }
4254   llvm::Value *UpdateVal = Update.getScalarVal();
4255   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
4256     UpdateVal = CGF.Builder.CreateIntCast(
4257         IC, X.getAddress(CGF).getElementType(),
4258         X.getType()->hasSignedIntegerRepresentation());
4259   }
4260   llvm::Value *Res =
4261       CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO);
4262   return std::make_pair(true, RValue::get(Res));
4263 }
4264 
4265 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
4266     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
4267     llvm::AtomicOrdering AO, SourceLocation Loc,
4268     const llvm::function_ref<RValue(RValue)> CommonGen) {
4269   // Update expressions are allowed to have the following forms:
4270   // x binop= expr; -> xrval + expr;
4271   // x++, ++x -> xrval + 1;
4272   // x--, --x -> xrval - 1;
4273   // x = x binop expr; -> xrval binop expr
4274   // x = expr Op x; - > expr binop xrval;
4275   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
4276   if (!Res.first) {
4277     if (X.isGlobalReg()) {
4278       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
4279       // 'xrval'.
4280       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
4281     } else {
4282       // Perform compare-and-swap procedure.
4283       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
4284     }
4285   }
4286   return Res;
4287 }
4288 
4289 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF,
4290                                     llvm::AtomicOrdering AO, const Expr *X,
4291                                     const Expr *E, const Expr *UE,
4292                                     bool IsXLHSInRHSPart, SourceLocation Loc) {
4293   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4294          "Update expr in 'atomic update' must be a binary operator.");
4295   const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
4296   // Update expressions are allowed to have the following forms:
4297   // x binop= expr; -> xrval + expr;
4298   // x++, ++x -> xrval + 1;
4299   // x--, --x -> xrval - 1;
4300   // x = x binop expr; -> xrval binop expr
4301   // x = expr Op x; - > expr binop xrval;
4302   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
4303   LValue XLValue = CGF.EmitLValue(X);
4304   RValue ExprRValue = CGF.EmitAnyExpr(E);
4305   const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4306   const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4307   const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4308   const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4309   auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
4310     CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4311     CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4312     return CGF.EmitAnyExpr(UE);
4313   };
4314   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
4315       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4316   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4317   // OpenMP, 2.17.7, atomic Construct
4318   // If the write, update, or capture clause is specified and the release,
4319   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
4320   // the atomic operation is also a release flush.
4321   switch (AO) {
4322   case llvm::AtomicOrdering::Release:
4323   case llvm::AtomicOrdering::AcquireRelease:
4324   case llvm::AtomicOrdering::SequentiallyConsistent:
4325     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4326                                          llvm::AtomicOrdering::Release);
4327     break;
4328   case llvm::AtomicOrdering::Acquire:
4329   case llvm::AtomicOrdering::Monotonic:
4330     break;
4331   case llvm::AtomicOrdering::NotAtomic:
4332   case llvm::AtomicOrdering::Unordered:
4333     llvm_unreachable("Unexpected ordering.");
4334   }
4335 }
4336 
4337 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
4338                             QualType SourceType, QualType ResType,
4339                             SourceLocation Loc) {
4340   switch (CGF.getEvaluationKind(ResType)) {
4341   case TEK_Scalar:
4342     return RValue::get(
4343         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
4344   case TEK_Complex: {
4345     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
4346     return RValue::getComplex(Res.first, Res.second);
4347   }
4348   case TEK_Aggregate:
4349     break;
4350   }
4351   llvm_unreachable("Must be a scalar or complex.");
4352 }
4353 
4354 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF,
4355                                      llvm::AtomicOrdering AO,
4356                                      bool IsPostfixUpdate, const Expr *V,
4357                                      const Expr *X, const Expr *E,
4358                                      const Expr *UE, bool IsXLHSInRHSPart,
4359                                      SourceLocation Loc) {
4360   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
4361   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
4362   RValue NewVVal;
4363   LValue VLValue = CGF.EmitLValue(V);
4364   LValue XLValue = CGF.EmitLValue(X);
4365   RValue ExprRValue = CGF.EmitAnyExpr(E);
4366   QualType NewVValType;
4367   if (UE) {
4368     // 'x' is updated with some additional value.
4369     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
4370            "Update expr in 'atomic capture' must be a binary operator.");
4371     const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
4372     // Update expressions are allowed to have the following forms:
4373     // x binop= expr; -> xrval + expr;
4374     // x++, ++x -> xrval + 1;
4375     // x--, --x -> xrval - 1;
4376     // x = x binop expr; -> xrval binop expr
4377     // x = expr Op x; - > expr binop xrval;
4378     const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
4379     const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
4380     const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
4381     NewVValType = XRValExpr->getType();
4382     const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
4383     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
4384                   IsPostfixUpdate](RValue XRValue) {
4385       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4386       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
4387       RValue Res = CGF.EmitAnyExpr(UE);
4388       NewVVal = IsPostfixUpdate ? XRValue : Res;
4389       return Res;
4390     };
4391     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4392         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
4393     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4394     if (Res.first) {
4395       // 'atomicrmw' instruction was generated.
4396       if (IsPostfixUpdate) {
4397         // Use old value from 'atomicrmw'.
4398         NewVVal = Res.second;
4399       } else {
4400         // 'atomicrmw' does not provide new value, so evaluate it using old
4401         // value of 'x'.
4402         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
4403         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
4404         NewVVal = CGF.EmitAnyExpr(UE);
4405       }
4406     }
4407   } else {
4408     // 'x' is simply rewritten with some 'expr'.
4409     NewVValType = X->getType().getNonReferenceType();
4410     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
4411                                X->getType().getNonReferenceType(), Loc);
4412     auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
4413       NewVVal = XRValue;
4414       return ExprRValue;
4415     };
4416     // Try to perform atomicrmw xchg, otherwise simple exchange.
4417     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
4418         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
4419         Loc, Gen);
4420     CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X);
4421     if (Res.first) {
4422       // 'atomicrmw' instruction was generated.
4423       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
4424     }
4425   }
4426   // Emit post-update store to 'v' of old/new 'x' value.
4427   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
4428   CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V);
4429   // OpenMP, 2.17.7, atomic Construct
4430   // If the write, update, or capture clause is specified and the release,
4431   // acq_rel, or seq_cst clause is specified then the strong flush on entry to
4432   // the atomic operation is also a release flush.
4433   // If the read or capture clause is specified and the acquire, acq_rel, or
4434   // seq_cst clause is specified then the strong flush on exit from the atomic
4435   // operation is also an acquire flush.
4436   switch (AO) {
4437   case llvm::AtomicOrdering::Release:
4438     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4439                                          llvm::AtomicOrdering::Release);
4440     break;
4441   case llvm::AtomicOrdering::Acquire:
4442     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4443                                          llvm::AtomicOrdering::Acquire);
4444     break;
4445   case llvm::AtomicOrdering::AcquireRelease:
4446   case llvm::AtomicOrdering::SequentiallyConsistent:
4447     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc,
4448                                          llvm::AtomicOrdering::AcquireRelease);
4449     break;
4450   case llvm::AtomicOrdering::Monotonic:
4451     break;
4452   case llvm::AtomicOrdering::NotAtomic:
4453   case llvm::AtomicOrdering::Unordered:
4454     llvm_unreachable("Unexpected ordering.");
4455   }
4456 }
4457 
4458 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
4459                               llvm::AtomicOrdering AO, bool IsPostfixUpdate,
4460                               const Expr *X, const Expr *V, const Expr *E,
4461                               const Expr *UE, bool IsXLHSInRHSPart,
4462                               SourceLocation Loc) {
4463   switch (Kind) {
4464   case OMPC_read:
4465     emitOMPAtomicReadExpr(CGF, AO, X, V, Loc);
4466     break;
4467   case OMPC_write:
4468     emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc);
4469     break;
4470   case OMPC_unknown:
4471   case OMPC_update:
4472     emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc);
4473     break;
4474   case OMPC_capture:
4475     emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE,
4476                              IsXLHSInRHSPart, Loc);
4477     break;
4478   case OMPC_if:
4479   case OMPC_final:
4480   case OMPC_num_threads:
4481   case OMPC_private:
4482   case OMPC_firstprivate:
4483   case OMPC_lastprivate:
4484   case OMPC_reduction:
4485   case OMPC_task_reduction:
4486   case OMPC_in_reduction:
4487   case OMPC_safelen:
4488   case OMPC_simdlen:
4489   case OMPC_allocator:
4490   case OMPC_allocate:
4491   case OMPC_collapse:
4492   case OMPC_default:
4493   case OMPC_seq_cst:
4494   case OMPC_acq_rel:
4495   case OMPC_acquire:
4496   case OMPC_release:
4497   case OMPC_shared:
4498   case OMPC_linear:
4499   case OMPC_aligned:
4500   case OMPC_copyin:
4501   case OMPC_copyprivate:
4502   case OMPC_flush:
4503   case OMPC_proc_bind:
4504   case OMPC_schedule:
4505   case OMPC_ordered:
4506   case OMPC_nowait:
4507   case OMPC_untied:
4508   case OMPC_threadprivate:
4509   case OMPC_depend:
4510   case OMPC_mergeable:
4511   case OMPC_device:
4512   case OMPC_threads:
4513   case OMPC_simd:
4514   case OMPC_map:
4515   case OMPC_num_teams:
4516   case OMPC_thread_limit:
4517   case OMPC_priority:
4518   case OMPC_grainsize:
4519   case OMPC_nogroup:
4520   case OMPC_num_tasks:
4521   case OMPC_hint:
4522   case OMPC_dist_schedule:
4523   case OMPC_defaultmap:
4524   case OMPC_uniform:
4525   case OMPC_to:
4526   case OMPC_from:
4527   case OMPC_use_device_ptr:
4528   case OMPC_is_device_ptr:
4529   case OMPC_unified_address:
4530   case OMPC_unified_shared_memory:
4531   case OMPC_reverse_offload:
4532   case OMPC_dynamic_allocators:
4533   case OMPC_atomic_default_mem_order:
4534   case OMPC_device_type:
4535   case OMPC_match:
4536   case OMPC_nontemporal:
4537   case OMPC_order:
4538     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
4539   }
4540 }
4541 
4542 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
4543   llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic;
4544   if (S.getSingleClause<OMPSeqCstClause>())
4545     AO = llvm::AtomicOrdering::SequentiallyConsistent;
4546   else if (S.getSingleClause<OMPAcqRelClause>())
4547     AO = llvm::AtomicOrdering::AcquireRelease;
4548   else if (S.getSingleClause<OMPAcquireClause>())
4549     AO = llvm::AtomicOrdering::Acquire;
4550   else if (S.getSingleClause<OMPReleaseClause>())
4551     AO = llvm::AtomicOrdering::Release;
4552   OpenMPClauseKind Kind = OMPC_unknown;
4553   for (const OMPClause *C : S.clauses()) {
4554     // Find first clause (skip seq_cst|acq_rel|aqcuire|release clause, if it is
4555     // first).
4556     if (C->getClauseKind() != OMPC_seq_cst &&
4557         C->getClauseKind() != OMPC_acq_rel &&
4558         C->getClauseKind() != OMPC_acquire &&
4559         C->getClauseKind() != OMPC_release) {
4560       Kind = C->getClauseKind();
4561       break;
4562     }
4563   }
4564 
4565   const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
4566   if (const auto *FE = dyn_cast<FullExpr>(CS))
4567     enterFullExpression(FE);
4568   // Processing for statements under 'atomic capture'.
4569   if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
4570     for (const Stmt *C : Compound->body()) {
4571       if (const auto *FE = dyn_cast<FullExpr>(C))
4572         enterFullExpression(FE);
4573     }
4574   }
4575 
4576   auto &&CodeGen = [&S, Kind, AO, CS](CodeGenFunction &CGF,
4577                                             PrePostActionTy &) {
4578     CGF.EmitStopPoint(CS);
4579     emitOMPAtomicExpr(CGF, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(),
4580                       S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(),
4581                       S.getBeginLoc());
4582   };
4583   OMPLexicalScope Scope(*this, S, OMPD_unknown);
4584   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
4585 }
4586 
4587 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
4588                                          const OMPExecutableDirective &S,
4589                                          const RegionCodeGenTy &CodeGen) {
4590   assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
4591   CodeGenModule &CGM = CGF.CGM;
4592 
4593   // On device emit this construct as inlined code.
4594   if (CGM.getLangOpts().OpenMPIsDevice) {
4595     OMPLexicalScope Scope(CGF, S, OMPD_target);
4596     CGM.getOpenMPRuntime().emitInlinedDirective(
4597         CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4598           CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
4599         });
4600     return;
4601   }
4602 
4603   auto LPCRegion =
4604       CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S);
4605   llvm::Function *Fn = nullptr;
4606   llvm::Constant *FnID = nullptr;
4607 
4608   const Expr *IfCond = nullptr;
4609   // Check for the at most one if clause associated with the target region.
4610   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
4611     if (C->getNameModifier() == OMPD_unknown ||
4612         C->getNameModifier() == OMPD_target) {
4613       IfCond = C->getCondition();
4614       break;
4615     }
4616   }
4617 
4618   // Check if we have any device clause associated with the directive.
4619   const Expr *Device = nullptr;
4620   if (auto *C = S.getSingleClause<OMPDeviceClause>())
4621     Device = C->getDevice();
4622 
4623   // Check if we have an if clause whose conditional always evaluates to false
4624   // or if we do not have any targets specified. If so the target region is not
4625   // an offload entry point.
4626   bool IsOffloadEntry = true;
4627   if (IfCond) {
4628     bool Val;
4629     if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
4630       IsOffloadEntry = false;
4631   }
4632   if (CGM.getLangOpts().OMPTargetTriples.empty())
4633     IsOffloadEntry = false;
4634 
4635   assert(CGF.CurFuncDecl && "No parent declaration for target region!");
4636   StringRef ParentName;
4637   // In case we have Ctors/Dtors we use the complete type variant to produce
4638   // the mangling of the device outlined kernel.
4639   if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
4640     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
4641   else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
4642     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
4643   else
4644     ParentName =
4645         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
4646 
4647   // Emit target region as a standalone region.
4648   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
4649                                                     IsOffloadEntry, CodeGen);
4650   OMPLexicalScope Scope(CGF, S, OMPD_task);
4651   auto &&SizeEmitter =
4652       [IsOffloadEntry](CodeGenFunction &CGF,
4653                        const OMPLoopDirective &D) -> llvm::Value * {
4654     if (IsOffloadEntry) {
4655       OMPLoopScope(CGF, D);
4656       // Emit calculation of the iterations count.
4657       llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations());
4658       NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty,
4659                                                 /*isSigned=*/false);
4660       return NumIterations;
4661     }
4662     return nullptr;
4663   };
4664   CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
4665                                         SizeEmitter);
4666 }
4667 
4668 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
4669                              PrePostActionTy &Action) {
4670   Action.Enter(CGF);
4671   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4672   (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4673   CGF.EmitOMPPrivateClause(S, PrivateScope);
4674   (void)PrivateScope.Privatize();
4675   if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4676     CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4677 
4678   CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
4679 }
4680 
4681 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
4682                                                   StringRef ParentName,
4683                                                   const OMPTargetDirective &S) {
4684   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4685     emitTargetRegion(CGF, S, Action);
4686   };
4687   llvm::Function *Fn;
4688   llvm::Constant *Addr;
4689   // Emit target region as a standalone region.
4690   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4691       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4692   assert(Fn && Addr && "Target device function emission failed.");
4693 }
4694 
4695 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
4696   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4697     emitTargetRegion(CGF, S, Action);
4698   };
4699   emitCommonOMPTargetDirective(*this, S, CodeGen);
4700 }
4701 
4702 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
4703                                         const OMPExecutableDirective &S,
4704                                         OpenMPDirectiveKind InnermostKind,
4705                                         const RegionCodeGenTy &CodeGen) {
4706   const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
4707   llvm::Function *OutlinedFn =
4708       CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
4709           S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
4710 
4711   const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
4712   const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
4713   if (NT || TL) {
4714     const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
4715     const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
4716 
4717     CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
4718                                                   S.getBeginLoc());
4719   }
4720 
4721   OMPTeamsScope Scope(CGF, S);
4722   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
4723   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
4724   CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
4725                                            CapturedVars);
4726 }
4727 
4728 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
4729   // Emit teams region as a standalone region.
4730   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4731     Action.Enter(CGF);
4732     OMPPrivateScope PrivateScope(CGF);
4733     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4734     CGF.EmitOMPPrivateClause(S, PrivateScope);
4735     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4736     (void)PrivateScope.Privatize();
4737     CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
4738     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4739   };
4740   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4741   emitPostUpdateForReductionClause(*this, S,
4742                                    [](CodeGenFunction &) { return nullptr; });
4743 }
4744 
4745 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4746                                   const OMPTargetTeamsDirective &S) {
4747   auto *CS = S.getCapturedStmt(OMPD_teams);
4748   Action.Enter(CGF);
4749   // Emit teams region as a standalone region.
4750   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
4751     Action.Enter(CGF);
4752     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4753     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
4754     CGF.EmitOMPPrivateClause(S, PrivateScope);
4755     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4756     (void)PrivateScope.Privatize();
4757     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
4758       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
4759     CGF.EmitStmt(CS->getCapturedStmt());
4760     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4761   };
4762   emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
4763   emitPostUpdateForReductionClause(CGF, S,
4764                                    [](CodeGenFunction &) { return nullptr; });
4765 }
4766 
4767 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
4768     CodeGenModule &CGM, StringRef ParentName,
4769     const OMPTargetTeamsDirective &S) {
4770   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4771     emitTargetTeamsRegion(CGF, Action, S);
4772   };
4773   llvm::Function *Fn;
4774   llvm::Constant *Addr;
4775   // Emit target region as a standalone region.
4776   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4777       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4778   assert(Fn && Addr && "Target device function emission failed.");
4779 }
4780 
4781 void CodeGenFunction::EmitOMPTargetTeamsDirective(
4782     const OMPTargetTeamsDirective &S) {
4783   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4784     emitTargetTeamsRegion(CGF, Action, S);
4785   };
4786   emitCommonOMPTargetDirective(*this, S, CodeGen);
4787 }
4788 
4789 static void
4790 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
4791                                 const OMPTargetTeamsDistributeDirective &S) {
4792   Action.Enter(CGF);
4793   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4794     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4795   };
4796 
4797   // Emit teams region as a standalone region.
4798   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4799                                             PrePostActionTy &Action) {
4800     Action.Enter(CGF);
4801     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4802     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4803     (void)PrivateScope.Privatize();
4804     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4805                                                     CodeGenDistribute);
4806     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4807   };
4808   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
4809   emitPostUpdateForReductionClause(CGF, S,
4810                                    [](CodeGenFunction &) { return nullptr; });
4811 }
4812 
4813 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
4814     CodeGenModule &CGM, StringRef ParentName,
4815     const OMPTargetTeamsDistributeDirective &S) {
4816   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4817     emitTargetTeamsDistributeRegion(CGF, Action, S);
4818   };
4819   llvm::Function *Fn;
4820   llvm::Constant *Addr;
4821   // Emit target region as a standalone region.
4822   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4823       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4824   assert(Fn && Addr && "Target device function emission failed.");
4825 }
4826 
4827 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
4828     const OMPTargetTeamsDistributeDirective &S) {
4829   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4830     emitTargetTeamsDistributeRegion(CGF, Action, S);
4831   };
4832   emitCommonOMPTargetDirective(*this, S, CodeGen);
4833 }
4834 
4835 static void emitTargetTeamsDistributeSimdRegion(
4836     CodeGenFunction &CGF, PrePostActionTy &Action,
4837     const OMPTargetTeamsDistributeSimdDirective &S) {
4838   Action.Enter(CGF);
4839   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4840     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4841   };
4842 
4843   // Emit teams region as a standalone region.
4844   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4845                                             PrePostActionTy &Action) {
4846     Action.Enter(CGF);
4847     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4848     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4849     (void)PrivateScope.Privatize();
4850     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4851                                                     CodeGenDistribute);
4852     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4853   };
4854   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
4855   emitPostUpdateForReductionClause(CGF, S,
4856                                    [](CodeGenFunction &) { return nullptr; });
4857 }
4858 
4859 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
4860     CodeGenModule &CGM, StringRef ParentName,
4861     const OMPTargetTeamsDistributeSimdDirective &S) {
4862   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4863     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4864   };
4865   llvm::Function *Fn;
4866   llvm::Constant *Addr;
4867   // Emit target region as a standalone region.
4868   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
4869       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
4870   assert(Fn && Addr && "Target device function emission failed.");
4871 }
4872 
4873 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
4874     const OMPTargetTeamsDistributeSimdDirective &S) {
4875   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
4876     emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
4877   };
4878   emitCommonOMPTargetDirective(*this, S, CodeGen);
4879 }
4880 
4881 void CodeGenFunction::EmitOMPTeamsDistributeDirective(
4882     const OMPTeamsDistributeDirective &S) {
4883 
4884   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4885     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4886   };
4887 
4888   // Emit teams region as a standalone region.
4889   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4890                                             PrePostActionTy &Action) {
4891     Action.Enter(CGF);
4892     OMPPrivateScope PrivateScope(CGF);
4893     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4894     (void)PrivateScope.Privatize();
4895     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4896                                                     CodeGenDistribute);
4897     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4898   };
4899   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
4900   emitPostUpdateForReductionClause(*this, S,
4901                                    [](CodeGenFunction &) { return nullptr; });
4902 }
4903 
4904 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
4905     const OMPTeamsDistributeSimdDirective &S) {
4906   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4907     CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
4908   };
4909 
4910   // Emit teams region as a standalone region.
4911   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4912                                             PrePostActionTy &Action) {
4913     Action.Enter(CGF);
4914     OMPPrivateScope PrivateScope(CGF);
4915     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4916     (void)PrivateScope.Privatize();
4917     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
4918                                                     CodeGenDistribute);
4919     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4920   };
4921   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
4922   emitPostUpdateForReductionClause(*this, S,
4923                                    [](CodeGenFunction &) { return nullptr; });
4924 }
4925 
4926 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
4927     const OMPTeamsDistributeParallelForDirective &S) {
4928   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4929     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4930                               S.getDistInc());
4931   };
4932 
4933   // Emit teams region as a standalone region.
4934   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4935                                             PrePostActionTy &Action) {
4936     Action.Enter(CGF);
4937     OMPPrivateScope PrivateScope(CGF);
4938     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4939     (void)PrivateScope.Privatize();
4940     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
4941                                                     CodeGenDistribute);
4942     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4943   };
4944   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
4945   emitPostUpdateForReductionClause(*this, S,
4946                                    [](CodeGenFunction &) { return nullptr; });
4947 }
4948 
4949 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
4950     const OMPTeamsDistributeParallelForSimdDirective &S) {
4951   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4952     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4953                               S.getDistInc());
4954   };
4955 
4956   // Emit teams region as a standalone region.
4957   auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4958                                             PrePostActionTy &Action) {
4959     Action.Enter(CGF);
4960     OMPPrivateScope PrivateScope(CGF);
4961     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4962     (void)PrivateScope.Privatize();
4963     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4964         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4965     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4966   };
4967   emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd,
4968                               CodeGen);
4969   emitPostUpdateForReductionClause(*this, S,
4970                                    [](CodeGenFunction &) { return nullptr; });
4971 }
4972 
4973 static void emitTargetTeamsDistributeParallelForRegion(
4974     CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
4975     PrePostActionTy &Action) {
4976   Action.Enter(CGF);
4977   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
4978     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
4979                               S.getDistInc());
4980   };
4981 
4982   // Emit teams region as a standalone region.
4983   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
4984                                                  PrePostActionTy &Action) {
4985     Action.Enter(CGF);
4986     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4987     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
4988     (void)PrivateScope.Privatize();
4989     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
4990         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
4991     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
4992   };
4993 
4994   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
4995                               CodeGenTeams);
4996   emitPostUpdateForReductionClause(CGF, S,
4997                                    [](CodeGenFunction &) { return nullptr; });
4998 }
4999 
5000 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
5001     CodeGenModule &CGM, StringRef ParentName,
5002     const OMPTargetTeamsDistributeParallelForDirective &S) {
5003   // Emit SPMD target teams distribute parallel for region as a standalone
5004   // region.
5005   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5006     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
5007   };
5008   llvm::Function *Fn;
5009   llvm::Constant *Addr;
5010   // Emit target region as a standalone region.
5011   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5012       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5013   assert(Fn && Addr && "Target device function emission failed.");
5014 }
5015 
5016 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
5017     const OMPTargetTeamsDistributeParallelForDirective &S) {
5018   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5019     emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
5020   };
5021   emitCommonOMPTargetDirective(*this, S, CodeGen);
5022 }
5023 
5024 static void emitTargetTeamsDistributeParallelForSimdRegion(
5025     CodeGenFunction &CGF,
5026     const OMPTargetTeamsDistributeParallelForSimdDirective &S,
5027     PrePostActionTy &Action) {
5028   Action.Enter(CGF);
5029   auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5030     CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
5031                               S.getDistInc());
5032   };
5033 
5034   // Emit teams region as a standalone region.
5035   auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
5036                                                  PrePostActionTy &Action) {
5037     Action.Enter(CGF);
5038     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5039     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5040     (void)PrivateScope.Privatize();
5041     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
5042         CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
5043     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
5044   };
5045 
5046   emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
5047                               CodeGenTeams);
5048   emitPostUpdateForReductionClause(CGF, S,
5049                                    [](CodeGenFunction &) { return nullptr; });
5050 }
5051 
5052 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
5053     CodeGenModule &CGM, StringRef ParentName,
5054     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
5055   // Emit SPMD target teams distribute parallel for simd region as a standalone
5056   // region.
5057   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5058     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
5059   };
5060   llvm::Function *Fn;
5061   llvm::Constant *Addr;
5062   // Emit target region as a standalone region.
5063   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5064       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5065   assert(Fn && Addr && "Target device function emission failed.");
5066 }
5067 
5068 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
5069     const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
5070   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5071     emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
5072   };
5073   emitCommonOMPTargetDirective(*this, S, CodeGen);
5074 }
5075 
5076 void CodeGenFunction::EmitOMPCancellationPointDirective(
5077     const OMPCancellationPointDirective &S) {
5078   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
5079                                                    S.getCancelRegion());
5080 }
5081 
5082 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
5083   const Expr *IfCond = nullptr;
5084   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5085     if (C->getNameModifier() == OMPD_unknown ||
5086         C->getNameModifier() == OMPD_cancel) {
5087       IfCond = C->getCondition();
5088       break;
5089     }
5090   }
5091   if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) {
5092     // TODO: This check is necessary as we only generate `omp parallel` through
5093     // the OpenMPIRBuilder for now.
5094     if (S.getCancelRegion() == OMPD_parallel) {
5095       llvm::Value *IfCondition = nullptr;
5096       if (IfCond)
5097         IfCondition = EmitScalarExpr(IfCond,
5098                                      /*IgnoreResultAssign=*/true);
5099       return Builder.restoreIP(
5100           OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion()));
5101     }
5102   }
5103 
5104   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
5105                                         S.getCancelRegion());
5106 }
5107 
5108 CodeGenFunction::JumpDest
5109 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
5110   if (Kind == OMPD_parallel || Kind == OMPD_task ||
5111       Kind == OMPD_target_parallel)
5112     return ReturnBlock;
5113   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
5114          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
5115          Kind == OMPD_distribute_parallel_for ||
5116          Kind == OMPD_target_parallel_for ||
5117          Kind == OMPD_teams_distribute_parallel_for ||
5118          Kind == OMPD_target_teams_distribute_parallel_for);
5119   return OMPCancelStack.getExitBlock();
5120 }
5121 
5122 void CodeGenFunction::EmitOMPUseDevicePtrClause(
5123     const OMPClause &NC, OMPPrivateScope &PrivateScope,
5124     const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
5125   const auto &C = cast<OMPUseDevicePtrClause>(NC);
5126   auto OrigVarIt = C.varlist_begin();
5127   auto InitIt = C.inits().begin();
5128   for (const Expr *PvtVarIt : C.private_copies()) {
5129     const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
5130     const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
5131     const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
5132 
5133     // In order to identify the right initializer we need to match the
5134     // declaration used by the mapping logic. In some cases we may get
5135     // OMPCapturedExprDecl that refers to the original declaration.
5136     const ValueDecl *MatchingVD = OrigVD;
5137     if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
5138       // OMPCapturedExprDecl are used to privative fields of the current
5139       // structure.
5140       const auto *ME = cast<MemberExpr>(OED->getInit());
5141       assert(isa<CXXThisExpr>(ME->getBase()) &&
5142              "Base should be the current struct!");
5143       MatchingVD = ME->getMemberDecl();
5144     }
5145 
5146     // If we don't have information about the current list item, move on to
5147     // the next one.
5148     auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
5149     if (InitAddrIt == CaptureDeviceAddrMap.end())
5150       continue;
5151 
5152     bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
5153                                                          InitAddrIt, InitVD,
5154                                                          PvtVD]() {
5155       // Initialize the temporary initialization variable with the address we
5156       // get from the runtime library. We have to cast the source address
5157       // because it is always a void *. References are materialized in the
5158       // privatization scope, so the initialization here disregards the fact
5159       // the original variable is a reference.
5160       QualType AddrQTy =
5161           getContext().getPointerType(OrigVD->getType().getNonReferenceType());
5162       llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
5163       Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
5164       setAddrOfLocalVar(InitVD, InitAddr);
5165 
5166       // Emit private declaration, it will be initialized by the value we
5167       // declaration we just added to the local declarations map.
5168       EmitDecl(*PvtVD);
5169 
5170       // The initialization variables reached its purpose in the emission
5171       // of the previous declaration, so we don't need it anymore.
5172       LocalDeclMap.erase(InitVD);
5173 
5174       // Return the address of the private variable.
5175       return GetAddrOfLocalVar(PvtVD);
5176     });
5177     assert(IsRegistered && "firstprivate var already registered as private");
5178     // Silence the warning about unused variable.
5179     (void)IsRegistered;
5180 
5181     ++OrigVarIt;
5182     ++InitIt;
5183   }
5184 }
5185 
5186 // Generate the instructions for '#pragma omp target data' directive.
5187 void CodeGenFunction::EmitOMPTargetDataDirective(
5188     const OMPTargetDataDirective &S) {
5189   CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
5190 
5191   // Create a pre/post action to signal the privatization of the device pointer.
5192   // This action can be replaced by the OpenMP runtime code generation to
5193   // deactivate privatization.
5194   bool PrivatizeDevicePointers = false;
5195   class DevicePointerPrivActionTy : public PrePostActionTy {
5196     bool &PrivatizeDevicePointers;
5197 
5198   public:
5199     explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
5200         : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
5201     void Enter(CodeGenFunction &CGF) override {
5202       PrivatizeDevicePointers = true;
5203     }
5204   };
5205   DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
5206 
5207   auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
5208                        CodeGenFunction &CGF, PrePostActionTy &Action) {
5209     auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5210       CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
5211     };
5212 
5213     // Codegen that selects whether to generate the privatization code or not.
5214     auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
5215                           &InnermostCodeGen](CodeGenFunction &CGF,
5216                                              PrePostActionTy &Action) {
5217       RegionCodeGenTy RCG(InnermostCodeGen);
5218       PrivatizeDevicePointers = false;
5219 
5220       // Call the pre-action to change the status of PrivatizeDevicePointers if
5221       // needed.
5222       Action.Enter(CGF);
5223 
5224       if (PrivatizeDevicePointers) {
5225         OMPPrivateScope PrivateScope(CGF);
5226         // Emit all instances of the use_device_ptr clause.
5227         for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
5228           CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
5229                                         Info.CaptureDeviceAddrMap);
5230         (void)PrivateScope.Privatize();
5231         RCG(CGF);
5232       } else {
5233         RCG(CGF);
5234       }
5235     };
5236 
5237     // Forward the provided action to the privatization codegen.
5238     RegionCodeGenTy PrivRCG(PrivCodeGen);
5239     PrivRCG.setAction(Action);
5240 
5241     // Notwithstanding the body of the region is emitted as inlined directive,
5242     // we don't use an inline scope as changes in the references inside the
5243     // region are expected to be visible outside, so we do not privative them.
5244     OMPLexicalScope Scope(CGF, S);
5245     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
5246                                                     PrivRCG);
5247   };
5248 
5249   RegionCodeGenTy RCG(CodeGen);
5250 
5251   // If we don't have target devices, don't bother emitting the data mapping
5252   // code.
5253   if (CGM.getLangOpts().OMPTargetTriples.empty()) {
5254     RCG(*this);
5255     return;
5256   }
5257 
5258   // Check if we have any if clause associated with the directive.
5259   const Expr *IfCond = nullptr;
5260   if (const auto *C = S.getSingleClause<OMPIfClause>())
5261     IfCond = C->getCondition();
5262 
5263   // Check if we have any device clause associated with the directive.
5264   const Expr *Device = nullptr;
5265   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5266     Device = C->getDevice();
5267 
5268   // Set the action to signal privatization of device pointers.
5269   RCG.setAction(PrivAction);
5270 
5271   // Emit region code.
5272   CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
5273                                              Info);
5274 }
5275 
5276 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
5277     const OMPTargetEnterDataDirective &S) {
5278   // If we don't have target devices, don't bother emitting the data mapping
5279   // code.
5280   if (CGM.getLangOpts().OMPTargetTriples.empty())
5281     return;
5282 
5283   // Check if we have any if clause associated with the directive.
5284   const Expr *IfCond = nullptr;
5285   if (const auto *C = S.getSingleClause<OMPIfClause>())
5286     IfCond = C->getCondition();
5287 
5288   // Check if we have any device clause associated with the directive.
5289   const Expr *Device = nullptr;
5290   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5291     Device = C->getDevice();
5292 
5293   OMPLexicalScope Scope(*this, S, OMPD_task);
5294   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5295 }
5296 
5297 void CodeGenFunction::EmitOMPTargetExitDataDirective(
5298     const OMPTargetExitDataDirective &S) {
5299   // If we don't have target devices, don't bother emitting the data mapping
5300   // code.
5301   if (CGM.getLangOpts().OMPTargetTriples.empty())
5302     return;
5303 
5304   // Check if we have any if clause associated with the directive.
5305   const Expr *IfCond = nullptr;
5306   if (const auto *C = S.getSingleClause<OMPIfClause>())
5307     IfCond = C->getCondition();
5308 
5309   // Check if we have any device clause associated with the directive.
5310   const Expr *Device = nullptr;
5311   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5312     Device = C->getDevice();
5313 
5314   OMPLexicalScope Scope(*this, S, OMPD_task);
5315   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5316 }
5317 
5318 static void emitTargetParallelRegion(CodeGenFunction &CGF,
5319                                      const OMPTargetParallelDirective &S,
5320                                      PrePostActionTy &Action) {
5321   // Get the captured statement associated with the 'parallel' region.
5322   const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
5323   Action.Enter(CGF);
5324   auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
5325     Action.Enter(CGF);
5326     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5327     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
5328     CGF.EmitOMPPrivateClause(S, PrivateScope);
5329     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
5330     (void)PrivateScope.Privatize();
5331     if (isOpenMPTargetExecutionDirective(S.getDirectiveKind()))
5332       CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S);
5333     // TODO: Add support for clauses.
5334     CGF.EmitStmt(CS->getCapturedStmt());
5335     CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
5336   };
5337   emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
5338                                  emitEmptyBoundParameters);
5339   emitPostUpdateForReductionClause(CGF, S,
5340                                    [](CodeGenFunction &) { return nullptr; });
5341 }
5342 
5343 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
5344     CodeGenModule &CGM, StringRef ParentName,
5345     const OMPTargetParallelDirective &S) {
5346   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5347     emitTargetParallelRegion(CGF, S, Action);
5348   };
5349   llvm::Function *Fn;
5350   llvm::Constant *Addr;
5351   // Emit target region as a standalone region.
5352   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5353       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5354   assert(Fn && Addr && "Target device function emission failed.");
5355 }
5356 
5357 void CodeGenFunction::EmitOMPTargetParallelDirective(
5358     const OMPTargetParallelDirective &S) {
5359   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5360     emitTargetParallelRegion(CGF, S, Action);
5361   };
5362   emitCommonOMPTargetDirective(*this, S, CodeGen);
5363 }
5364 
5365 static void emitTargetParallelForRegion(CodeGenFunction &CGF,
5366                                         const OMPTargetParallelForDirective &S,
5367                                         PrePostActionTy &Action) {
5368   Action.Enter(CGF);
5369   // Emit directive as a combined directive that consists of two implicit
5370   // directives: 'parallel' with 'for' directive.
5371   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5372     Action.Enter(CGF);
5373     CodeGenFunction::OMPCancelStackRAII CancelRegion(
5374         CGF, OMPD_target_parallel_for, S.hasCancel());
5375     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5376                                emitDispatchForLoopBounds);
5377   };
5378   emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
5379                                  emitEmptyBoundParameters);
5380 }
5381 
5382 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
5383     CodeGenModule &CGM, StringRef ParentName,
5384     const OMPTargetParallelForDirective &S) {
5385   // Emit SPMD target parallel for region as a standalone region.
5386   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5387     emitTargetParallelForRegion(CGF, S, Action);
5388   };
5389   llvm::Function *Fn;
5390   llvm::Constant *Addr;
5391   // Emit target region as a standalone region.
5392   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5393       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5394   assert(Fn && Addr && "Target device function emission failed.");
5395 }
5396 
5397 void CodeGenFunction::EmitOMPTargetParallelForDirective(
5398     const OMPTargetParallelForDirective &S) {
5399   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5400     emitTargetParallelForRegion(CGF, S, Action);
5401   };
5402   emitCommonOMPTargetDirective(*this, S, CodeGen);
5403 }
5404 
5405 static void
5406 emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
5407                                 const OMPTargetParallelForSimdDirective &S,
5408                                 PrePostActionTy &Action) {
5409   Action.Enter(CGF);
5410   // Emit directive as a combined directive that consists of two implicit
5411   // directives: 'parallel' with 'for' directive.
5412   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5413     Action.Enter(CGF);
5414     CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
5415                                emitDispatchForLoopBounds);
5416   };
5417   emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
5418                                  emitEmptyBoundParameters);
5419 }
5420 
5421 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
5422     CodeGenModule &CGM, StringRef ParentName,
5423     const OMPTargetParallelForSimdDirective &S) {
5424   // Emit SPMD target parallel for region as a standalone region.
5425   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5426     emitTargetParallelForSimdRegion(CGF, S, Action);
5427   };
5428   llvm::Function *Fn;
5429   llvm::Constant *Addr;
5430   // Emit target region as a standalone region.
5431   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
5432       S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
5433   assert(Fn && Addr && "Target device function emission failed.");
5434 }
5435 
5436 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
5437     const OMPTargetParallelForSimdDirective &S) {
5438   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5439     emitTargetParallelForSimdRegion(CGF, S, Action);
5440   };
5441   emitCommonOMPTargetDirective(*this, S, CodeGen);
5442 }
5443 
5444 /// Emit a helper variable and return corresponding lvalue.
5445 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
5446                      const ImplicitParamDecl *PVD,
5447                      CodeGenFunction::OMPPrivateScope &Privates) {
5448   const auto *VDecl = cast<VarDecl>(Helper->getDecl());
5449   Privates.addPrivate(VDecl,
5450                       [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
5451 }
5452 
5453 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
5454   assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
5455   // Emit outlined function for task construct.
5456   const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
5457   Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
5458   QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
5459   const Expr *IfCond = nullptr;
5460   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
5461     if (C->getNameModifier() == OMPD_unknown ||
5462         C->getNameModifier() == OMPD_taskloop) {
5463       IfCond = C->getCondition();
5464       break;
5465     }
5466   }
5467 
5468   OMPTaskDataTy Data;
5469   // Check if taskloop must be emitted without taskgroup.
5470   Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
5471   // TODO: Check if we should emit tied or untied task.
5472   Data.Tied = true;
5473   // Set scheduling for taskloop
5474   if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
5475     // grainsize clause
5476     Data.Schedule.setInt(/*IntVal=*/false);
5477     Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
5478   } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
5479     // num_tasks clause
5480     Data.Schedule.setInt(/*IntVal=*/true);
5481     Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
5482   }
5483 
5484   auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
5485     // if (PreCond) {
5486     //   for (IV in 0..LastIteration) BODY;
5487     //   <Final counter/linear vars updates>;
5488     // }
5489     //
5490 
5491     // Emit: if (PreCond) - begin.
5492     // If the condition constant folds and can be elided, avoid emitting the
5493     // whole loop.
5494     bool CondConstant;
5495     llvm::BasicBlock *ContBlock = nullptr;
5496     OMPLoopScope PreInitScope(CGF, S);
5497     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
5498       if (!CondConstant)
5499         return;
5500     } else {
5501       llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
5502       ContBlock = CGF.createBasicBlock("taskloop.if.end");
5503       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
5504                   CGF.getProfileCount(&S));
5505       CGF.EmitBlock(ThenBlock);
5506       CGF.incrementProfileCounter(&S);
5507     }
5508 
5509     (void)CGF.EmitOMPLinearClauseInit(S);
5510 
5511     OMPPrivateScope LoopScope(CGF);
5512     // Emit helper vars inits.
5513     enum { LowerBound = 5, UpperBound, Stride, LastIter };
5514     auto *I = CS->getCapturedDecl()->param_begin();
5515     auto *LBP = std::next(I, LowerBound);
5516     auto *UBP = std::next(I, UpperBound);
5517     auto *STP = std::next(I, Stride);
5518     auto *LIP = std::next(I, LastIter);
5519     mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
5520              LoopScope);
5521     mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
5522              LoopScope);
5523     mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
5524     mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
5525              LoopScope);
5526     CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
5527     CGF.EmitOMPLinearClause(S, LoopScope);
5528     bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
5529     (void)LoopScope.Privatize();
5530     // Emit the loop iteration variable.
5531     const Expr *IVExpr = S.getIterationVariable();
5532     const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
5533     CGF.EmitVarDecl(*IVDecl);
5534     CGF.EmitIgnoredExpr(S.getInit());
5535 
5536     // Emit the iterations count variable.
5537     // If it is not a variable, Sema decided to calculate iterations count on
5538     // each iteration (e.g., it is foldable into a constant).
5539     if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
5540       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
5541       // Emit calculation of the iterations count.
5542       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
5543     }
5544 
5545     {
5546       OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false);
5547       emitCommonSimdLoop(
5548           CGF, S,
5549           [&S](CodeGenFunction &CGF, PrePostActionTy &) {
5550             if (isOpenMPSimdDirective(S.getDirectiveKind()))
5551               CGF.EmitOMPSimdInit(S);
5552           },
5553           [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) {
5554             CGF.EmitOMPInnerLoop(
5555                 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
5556                 [&S](CodeGenFunction &CGF) {
5557                   CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
5558                   CGF.EmitStopPoint(&S);
5559                 },
5560                 [](CodeGenFunction &) {});
5561           });
5562     }
5563     // Emit: if (PreCond) - end.
5564     if (ContBlock) {
5565       CGF.EmitBranch(ContBlock);
5566       CGF.EmitBlock(ContBlock, true);
5567     }
5568     // Emit final copy of the lastprivate variables if IsLastIter != 0.
5569     if (HasLastprivateClause) {
5570       CGF.EmitOMPLastprivateClauseFinal(
5571           S, isOpenMPSimdDirective(S.getDirectiveKind()),
5572           CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
5573               CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5574               (*LIP)->getType(), S.getBeginLoc())));
5575     }
5576     CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) {
5577       return CGF.Builder.CreateIsNotNull(
5578           CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
5579                                (*LIP)->getType(), S.getBeginLoc()));
5580     });
5581   };
5582   auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
5583                     IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn,
5584                             const OMPTaskDataTy &Data) {
5585     auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
5586                       &Data](CodeGenFunction &CGF, PrePostActionTy &) {
5587       OMPLoopScope PreInitScope(CGF, S);
5588       CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
5589                                                   OutlinedFn, SharedsTy,
5590                                                   CapturedStruct, IfCond, Data);
5591     };
5592     CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
5593                                                     CodeGen);
5594   };
5595   if (Data.Nogroup) {
5596     EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
5597   } else {
5598     CGM.getOpenMPRuntime().emitTaskgroupRegion(
5599         *this,
5600         [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
5601                                         PrePostActionTy &Action) {
5602           Action.Enter(CGF);
5603           CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
5604                                         Data);
5605         },
5606         S.getBeginLoc());
5607   }
5608 }
5609 
5610 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
5611   auto LPCRegion =
5612       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5613   EmitOMPTaskLoopBasedDirective(S);
5614 }
5615 
5616 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
5617     const OMPTaskLoopSimdDirective &S) {
5618   auto LPCRegion =
5619       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5620   OMPLexicalScope Scope(*this, S);
5621   EmitOMPTaskLoopBasedDirective(S);
5622 }
5623 
5624 void CodeGenFunction::EmitOMPMasterTaskLoopDirective(
5625     const OMPMasterTaskLoopDirective &S) {
5626   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5627     Action.Enter(CGF);
5628     EmitOMPTaskLoopBasedDirective(S);
5629   };
5630   auto LPCRegion =
5631       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5632   OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false);
5633   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5634 }
5635 
5636 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective(
5637     const OMPMasterTaskLoopSimdDirective &S) {
5638   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5639     Action.Enter(CGF);
5640     EmitOMPTaskLoopBasedDirective(S);
5641   };
5642   auto LPCRegion =
5643       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5644   OMPLexicalScope Scope(*this, S);
5645   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
5646 }
5647 
5648 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective(
5649     const OMPParallelMasterTaskLoopDirective &S) {
5650   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5651     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5652                                   PrePostActionTy &Action) {
5653       Action.Enter(CGF);
5654       CGF.EmitOMPTaskLoopBasedDirective(S);
5655     };
5656     OMPLexicalScope Scope(CGF, S, llvm::None, /*EmitPreInitStmt=*/false);
5657     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5658                                             S.getBeginLoc());
5659   };
5660   auto LPCRegion =
5661       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5662   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen,
5663                                  emitEmptyBoundParameters);
5664 }
5665 
5666 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective(
5667     const OMPParallelMasterTaskLoopSimdDirective &S) {
5668   auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) {
5669     auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF,
5670                                   PrePostActionTy &Action) {
5671       Action.Enter(CGF);
5672       CGF.EmitOMPTaskLoopBasedDirective(S);
5673     };
5674     OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false);
5675     CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen,
5676                                             S.getBeginLoc());
5677   };
5678   auto LPCRegion =
5679       CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
5680   emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen,
5681                                  emitEmptyBoundParameters);
5682 }
5683 
5684 // Generate the instructions for '#pragma omp target update' directive.
5685 void CodeGenFunction::EmitOMPTargetUpdateDirective(
5686     const OMPTargetUpdateDirective &S) {
5687   // If we don't have target devices, don't bother emitting the data mapping
5688   // code.
5689   if (CGM.getLangOpts().OMPTargetTriples.empty())
5690     return;
5691 
5692   // Check if we have any if clause associated with the directive.
5693   const Expr *IfCond = nullptr;
5694   if (const auto *C = S.getSingleClause<OMPIfClause>())
5695     IfCond = C->getCondition();
5696 
5697   // Check if we have any device clause associated with the directive.
5698   const Expr *Device = nullptr;
5699   if (const auto *C = S.getSingleClause<OMPDeviceClause>())
5700     Device = C->getDevice();
5701 
5702   OMPLexicalScope Scope(*this, S, OMPD_task);
5703   CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
5704 }
5705 
5706 void CodeGenFunction::EmitSimpleOMPExecutableDirective(
5707     const OMPExecutableDirective &D) {
5708   if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
5709     return;
5710   auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
5711     if (isOpenMPSimdDirective(D.getDirectiveKind())) {
5712       emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
5713     } else {
5714       OMPPrivateScope LoopGlobals(CGF);
5715       if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
5716         for (const Expr *E : LD->counters()) {
5717           const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
5718           if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
5719             LValue GlobLVal = CGF.EmitLValue(E);
5720             LoopGlobals.addPrivate(
5721                 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); });
5722           }
5723           if (isa<OMPCapturedExprDecl>(VD)) {
5724             // Emit only those that were not explicitly referenced in clauses.
5725             if (!CGF.LocalDeclMap.count(VD))
5726               CGF.EmitVarDecl(*VD);
5727           }
5728         }
5729         for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
5730           if (!C->getNumForLoops())
5731             continue;
5732           for (unsigned I = LD->getCollapsedNumber(),
5733                         E = C->getLoopNumIterations().size();
5734                I < E; ++I) {
5735             if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
5736                     cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
5737               // Emit only those that were not explicitly referenced in clauses.
5738               if (!CGF.LocalDeclMap.count(VD))
5739                 CGF.EmitVarDecl(*VD);
5740             }
5741           }
5742         }
5743       }
5744       LoopGlobals.Privatize();
5745       CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
5746     }
5747   };
5748   {
5749     auto LPCRegion =
5750         CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D);
5751     OMPSimdLexicalScope Scope(*this, D);
5752     CGM.getOpenMPRuntime().emitInlinedDirective(
5753         *this,
5754         isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
5755                                                     : D.getDirectiveKind(),
5756         CodeGen);
5757   }
5758   // Check for outer lastprivate conditional update.
5759   checkForLastprivateConditionalUpdate(*this, D);
5760 }
5761