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