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