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