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