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 using namespace clang;
22 using namespace CodeGen;
23 
24 namespace {
25 /// Lexical scope for OpenMP executable constructs, that handles correct codegen
26 /// for captured expressions.
27 class OMPLexicalScope {
28   CodeGenFunction::LexicalScope Scope;
29   void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
30     for (const auto *C : S.clauses()) {
31       if (auto *CPI = OMPClauseWithPreInit::get(C)) {
32         if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
33           for (const auto *I : PreInit->decls())
34             CGF.EmitVarDecl(cast<VarDecl>(*I));
35         }
36       }
37     }
38   }
39 
40 public:
41   OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
42       : Scope(CGF, S.getSourceRange()) {
43     emitPreInitStmt(CGF, S);
44   }
45 };
46 } // namespace
47 
48 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
49   auto &C = getContext();
50   llvm::Value *Size = nullptr;
51   auto SizeInChars = C.getTypeSizeInChars(Ty);
52   if (SizeInChars.isZero()) {
53     // getTypeSizeInChars() returns 0 for a VLA.
54     while (auto *VAT = C.getAsVariableArrayType(Ty)) {
55       llvm::Value *ArraySize;
56       std::tie(ArraySize, Ty) = getVLASize(VAT);
57       Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
58     }
59     SizeInChars = C.getTypeSizeInChars(Ty);
60     if (SizeInChars.isZero())
61       return llvm::ConstantInt::get(SizeTy, /*V=*/0);
62     Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
63   } else
64     Size = CGM.getSize(SizeInChars);
65   return Size;
66 }
67 
68 void CodeGenFunction::GenerateOpenMPCapturedVars(
69     const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
70   const RecordDecl *RD = S.getCapturedRecordDecl();
71   auto CurField = RD->field_begin();
72   auto CurCap = S.captures().begin();
73   for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
74                                                  E = S.capture_init_end();
75        I != E; ++I, ++CurField, ++CurCap) {
76     if (CurField->hasCapturedVLAType()) {
77       auto VAT = CurField->getCapturedVLAType();
78       auto *Val = VLASizeMap[VAT->getSizeExpr()];
79       CapturedVars.push_back(Val);
80     } else if (CurCap->capturesThis())
81       CapturedVars.push_back(CXXThisValue);
82     else if (CurCap->capturesVariableByCopy())
83       CapturedVars.push_back(
84           EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal());
85     else {
86       assert(CurCap->capturesVariable() && "Expected capture by reference.");
87       CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
88     }
89   }
90 }
91 
92 static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
93                                     StringRef Name, LValue AddrLV,
94                                     bool isReferenceType = false) {
95   ASTContext &Ctx = CGF.getContext();
96 
97   auto *CastedPtr = CGF.EmitScalarConversion(
98       AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
99       Ctx.getPointerType(DstType), SourceLocation());
100   auto TmpAddr =
101       CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
102           .getAddress();
103 
104   // If we are dealing with references we need to return the address of the
105   // reference instead of the reference of the value.
106   if (isReferenceType) {
107     QualType RefType = Ctx.getLValueReferenceType(DstType);
108     auto *RefVal = TmpAddr.getPointer();
109     TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
110     auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
111     CGF.EmitScalarInit(RefVal, TmpLVal);
112   }
113 
114   return TmpAddr;
115 }
116 
117 llvm::Function *
118 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
119   assert(
120       CapturedStmtInfo &&
121       "CapturedStmtInfo should be set when generating the captured function");
122   const CapturedDecl *CD = S.getCapturedDecl();
123   const RecordDecl *RD = S.getCapturedRecordDecl();
124   assert(CD->hasBody() && "missing CapturedDecl body");
125 
126   // Build the argument list.
127   ASTContext &Ctx = CGM.getContext();
128   FunctionArgList Args;
129   Args.append(CD->param_begin(),
130               std::next(CD->param_begin(), CD->getContextParamPosition()));
131   auto I = S.captures().begin();
132   for (auto *FD : RD->fields()) {
133     QualType ArgType = FD->getType();
134     IdentifierInfo *II = nullptr;
135     VarDecl *CapVar = nullptr;
136 
137     // If this is a capture by copy and the type is not a pointer, the outlined
138     // function argument type should be uintptr and the value properly casted to
139     // uintptr. This is necessary given that the runtime library is only able to
140     // deal with pointers. We can pass in the same way the VLA type sizes to the
141     // outlined function.
142     if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
143         I->capturesVariableArrayType())
144       ArgType = Ctx.getUIntPtrType();
145 
146     if (I->capturesVariable() || I->capturesVariableByCopy()) {
147       CapVar = I->getCapturedVar();
148       II = CapVar->getIdentifier();
149     } else if (I->capturesThis())
150       II = &getContext().Idents.get("this");
151     else {
152       assert(I->capturesVariableArrayType());
153       II = &getContext().Idents.get("vla");
154     }
155     if (ArgType->isVariablyModifiedType())
156       ArgType = getContext().getVariableArrayDecayedType(ArgType);
157     Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr,
158                                              FD->getLocation(), II, ArgType));
159     ++I;
160   }
161   Args.append(
162       std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
163       CD->param_end());
164 
165   // Create the function declaration.
166   FunctionType::ExtInfo ExtInfo;
167   const CGFunctionInfo &FuncInfo =
168       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
169                                                     /*IsVariadic=*/false);
170   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
171 
172   llvm::Function *F = llvm::Function::Create(
173       FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
174       CapturedStmtInfo->getHelperName(), &CGM.getModule());
175   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
176   if (CD->isNothrow())
177     F->addFnAttr(llvm::Attribute::NoUnwind);
178 
179   // Generate the function.
180   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
181                 CD->getBody()->getLocStart());
182   unsigned Cnt = CD->getContextParamPosition();
183   I = S.captures().begin();
184   for (auto *FD : RD->fields()) {
185     // If we are capturing a pointer by copy we don't need to do anything, just
186     // use the value that we get from the arguments.
187     if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
188       setAddrOfLocalVar(I->getCapturedVar(), GetAddrOfLocalVar(Args[Cnt]));
189       ++Cnt;
190       ++I;
191       continue;
192     }
193 
194     LValue ArgLVal =
195         MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
196                        AlignmentSource::Decl);
197     if (FD->hasCapturedVLAType()) {
198       LValue CastedArgLVal =
199           MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
200                                               Args[Cnt]->getName(), ArgLVal),
201                          FD->getType(), AlignmentSource::Decl);
202       auto *ExprArg =
203           EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
204       auto VAT = FD->getCapturedVLAType();
205       VLASizeMap[VAT->getSizeExpr()] = ExprArg;
206     } else if (I->capturesVariable()) {
207       auto *Var = I->getCapturedVar();
208       QualType VarTy = Var->getType();
209       Address ArgAddr = ArgLVal.getAddress();
210       if (!VarTy->isReferenceType()) {
211         ArgAddr = EmitLoadOfReference(
212             ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
213       }
214       setAddrOfLocalVar(
215           Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
216     } else if (I->capturesVariableByCopy()) {
217       assert(!FD->getType()->isAnyPointerType() &&
218              "Not expecting a captured pointer.");
219       auto *Var = I->getCapturedVar();
220       QualType VarTy = Var->getType();
221       setAddrOfLocalVar(I->getCapturedVar(),
222                         castValueFromUintptr(*this, FD->getType(),
223                                              Args[Cnt]->getName(), ArgLVal,
224                                              VarTy->isReferenceType()));
225     } else {
226       // If 'this' is captured, load it into CXXThisValue.
227       assert(I->capturesThis());
228       CXXThisValue =
229           EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
230     }
231     ++Cnt;
232     ++I;
233   }
234 
235   PGO.assignRegionCounters(GlobalDecl(CD), F);
236   CapturedStmtInfo->EmitBody(*this, CD->getBody());
237   FinishFunction(CD->getBodyRBrace());
238 
239   return F;
240 }
241 
242 //===----------------------------------------------------------------------===//
243 //                              OpenMP Directive Emission
244 //===----------------------------------------------------------------------===//
245 void CodeGenFunction::EmitOMPAggregateAssign(
246     Address DestAddr, Address SrcAddr, QualType OriginalType,
247     const llvm::function_ref<void(Address, Address)> &CopyGen) {
248   // Perform element-by-element initialization.
249   QualType ElementTy;
250 
251   // Drill down to the base element type on both arrays.
252   auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
253   auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
254   SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
255 
256   auto SrcBegin = SrcAddr.getPointer();
257   auto DestBegin = DestAddr.getPointer();
258   // Cast from pointer to array type to pointer to single element.
259   auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
260   // The basic structure here is a while-do loop.
261   auto BodyBB = createBasicBlock("omp.arraycpy.body");
262   auto DoneBB = createBasicBlock("omp.arraycpy.done");
263   auto IsEmpty =
264       Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
265   Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
266 
267   // Enter the loop body, making that address the current address.
268   auto EntryBB = Builder.GetInsertBlock();
269   EmitBlock(BodyBB);
270 
271   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
272 
273   llvm::PHINode *SrcElementPHI =
274     Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
275   SrcElementPHI->addIncoming(SrcBegin, EntryBB);
276   Address SrcElementCurrent =
277       Address(SrcElementPHI,
278               SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
279 
280   llvm::PHINode *DestElementPHI =
281     Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
282   DestElementPHI->addIncoming(DestBegin, EntryBB);
283   Address DestElementCurrent =
284     Address(DestElementPHI,
285             DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
286 
287   // Emit copy.
288   CopyGen(DestElementCurrent, SrcElementCurrent);
289 
290   // Shift the address forward by one element.
291   auto DestElementNext = Builder.CreateConstGEP1_32(
292       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
293   auto SrcElementNext = Builder.CreateConstGEP1_32(
294       SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
295   // Check whether we've reached the end.
296   auto Done =
297       Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
298   Builder.CreateCondBr(Done, DoneBB, BodyBB);
299   DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
300   SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
301 
302   // Done.
303   EmitBlock(DoneBB, /*IsFinished=*/true);
304 }
305 
306 /// \brief Emit initialization of arrays of complex types.
307 /// \param DestAddr Address of the array.
308 /// \param Type Type of array.
309 /// \param Init Initial expression of array.
310 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
311                                  QualType Type, const Expr *Init) {
312   // Perform element-by-element initialization.
313   QualType ElementTy;
314 
315   // Drill down to the base element type on both arrays.
316   auto ArrayTy = Type->getAsArrayTypeUnsafe();
317   auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
318   DestAddr =
319       CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
320 
321   auto DestBegin = DestAddr.getPointer();
322   // Cast from pointer to array type to pointer to single element.
323   auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
324   // The basic structure here is a while-do loop.
325   auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
326   auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
327   auto IsEmpty =
328       CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
329   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
330 
331   // Enter the loop body, making that address the current address.
332   auto EntryBB = CGF.Builder.GetInsertBlock();
333   CGF.EmitBlock(BodyBB);
334 
335   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
336 
337   llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
338       DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
339   DestElementPHI->addIncoming(DestBegin, EntryBB);
340   Address DestElementCurrent =
341       Address(DestElementPHI,
342               DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
343 
344   // Emit copy.
345   {
346     CodeGenFunction::RunCleanupsScope InitScope(CGF);
347     CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
348                          /*IsInitializer=*/false);
349   }
350 
351   // Shift the address forward by one element.
352   auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
353       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
354   // Check whether we've reached the end.
355   auto Done =
356       CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
357   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
358   DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
359 
360   // Done.
361   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
362 }
363 
364 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
365                                   Address SrcAddr, const VarDecl *DestVD,
366                                   const VarDecl *SrcVD, const Expr *Copy) {
367   if (OriginalType->isArrayType()) {
368     auto *BO = dyn_cast<BinaryOperator>(Copy);
369     if (BO && BO->getOpcode() == BO_Assign) {
370       // Perform simple memcpy for simple copying.
371       EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
372     } else {
373       // For arrays with complex element types perform element by element
374       // copying.
375       EmitOMPAggregateAssign(
376           DestAddr, SrcAddr, OriginalType,
377           [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
378             // Working with the single array element, so have to remap
379             // destination and source variables to corresponding array
380             // elements.
381             CodeGenFunction::OMPPrivateScope Remap(*this);
382             Remap.addPrivate(DestVD, [DestElement]() -> Address {
383               return DestElement;
384             });
385             Remap.addPrivate(
386                 SrcVD, [SrcElement]() -> Address { return SrcElement; });
387             (void)Remap.Privatize();
388             EmitIgnoredExpr(Copy);
389           });
390     }
391   } else {
392     // Remap pseudo source variable to private copy.
393     CodeGenFunction::OMPPrivateScope Remap(*this);
394     Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
395     Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
396     (void)Remap.Privatize();
397     // Emit copying of the whole variable.
398     EmitIgnoredExpr(Copy);
399   }
400 }
401 
402 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
403                                                 OMPPrivateScope &PrivateScope) {
404   if (!HaveInsertPoint())
405     return false;
406   bool FirstprivateIsLastprivate = false;
407   llvm::DenseSet<const VarDecl *> Lastprivates;
408   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
409     for (const auto *D : C->varlists())
410       Lastprivates.insert(
411           cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
412   }
413   llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
414   for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
415     auto IRef = C->varlist_begin();
416     auto InitsRef = C->inits().begin();
417     for (auto IInit : C->private_copies()) {
418       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
419       FirstprivateIsLastprivate =
420           FirstprivateIsLastprivate ||
421           (Lastprivates.count(OrigVD->getCanonicalDecl()) > 0);
422       if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
423         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
424         auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
425         bool IsRegistered;
426         DeclRefExpr DRE(
427             const_cast<VarDecl *>(OrigVD),
428             /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
429                 OrigVD) != nullptr,
430             (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
431         Address OriginalAddr = EmitLValue(&DRE).getAddress();
432         QualType Type = OrigVD->getType();
433         if (Type->isArrayType()) {
434           // Emit VarDecl with copy init for arrays.
435           // Get the address of the original variable captured in current
436           // captured region.
437           IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
438             auto Emission = EmitAutoVarAlloca(*VD);
439             auto *Init = VD->getInit();
440             if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
441               // Perform simple memcpy.
442               EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
443                                   Type);
444             } else {
445               EmitOMPAggregateAssign(
446                   Emission.getAllocatedAddress(), OriginalAddr, Type,
447                   [this, VDInit, Init](Address DestElement,
448                                        Address SrcElement) {
449                     // Clean up any temporaries needed by the initialization.
450                     RunCleanupsScope InitScope(*this);
451                     // Emit initialization for single element.
452                     setAddrOfLocalVar(VDInit, SrcElement);
453                     EmitAnyExprToMem(Init, DestElement,
454                                      Init->getType().getQualifiers(),
455                                      /*IsInitializer*/ false);
456                     LocalDeclMap.erase(VDInit);
457                   });
458             }
459             EmitAutoVarCleanups(Emission);
460             return Emission.getAllocatedAddress();
461           });
462         } else {
463           IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
464             // Emit private VarDecl with copy init.
465             // Remap temp VDInit variable to the address of the original
466             // variable
467             // (for proper handling of captured global variables).
468             setAddrOfLocalVar(VDInit, OriginalAddr);
469             EmitDecl(*VD);
470             LocalDeclMap.erase(VDInit);
471             return GetAddrOfLocalVar(VD);
472           });
473         }
474         assert(IsRegistered &&
475                "firstprivate var already registered as private");
476         // Silence the warning about unused variable.
477         (void)IsRegistered;
478       }
479       ++IRef;
480       ++InitsRef;
481     }
482   }
483   return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
484 }
485 
486 void CodeGenFunction::EmitOMPPrivateClause(
487     const OMPExecutableDirective &D,
488     CodeGenFunction::OMPPrivateScope &PrivateScope) {
489   if (!HaveInsertPoint())
490     return;
491   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
492   for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
493     auto IRef = C->varlist_begin();
494     for (auto IInit : C->private_copies()) {
495       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
496       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
497         auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
498         bool IsRegistered =
499             PrivateScope.addPrivate(OrigVD, [&]() -> Address {
500               // Emit private VarDecl with copy init.
501               EmitDecl(*VD);
502               return GetAddrOfLocalVar(VD);
503             });
504         assert(IsRegistered && "private var already registered as private");
505         // Silence the warning about unused variable.
506         (void)IsRegistered;
507       }
508       ++IRef;
509     }
510   }
511 }
512 
513 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
514   if (!HaveInsertPoint())
515     return false;
516   // threadprivate_var1 = master_threadprivate_var1;
517   // operator=(threadprivate_var2, master_threadprivate_var2);
518   // ...
519   // __kmpc_barrier(&loc, global_tid);
520   llvm::DenseSet<const VarDecl *> CopiedVars;
521   llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
522   for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
523     auto IRef = C->varlist_begin();
524     auto ISrcRef = C->source_exprs().begin();
525     auto IDestRef = C->destination_exprs().begin();
526     for (auto *AssignOp : C->assignment_ops()) {
527       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
528       QualType Type = VD->getType();
529       if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
530         // Get the address of the master variable. If we are emitting code with
531         // TLS support, the address is passed from the master as field in the
532         // captured declaration.
533         Address MasterAddr = Address::invalid();
534         if (getLangOpts().OpenMPUseTLS &&
535             getContext().getTargetInfo().isTLSSupported()) {
536           assert(CapturedStmtInfo->lookup(VD) &&
537                  "Copyin threadprivates should have been captured!");
538           DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
539                           VK_LValue, (*IRef)->getExprLoc());
540           MasterAddr = EmitLValue(&DRE).getAddress();
541           LocalDeclMap.erase(VD);
542         } else {
543           MasterAddr =
544             Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
545                                         : CGM.GetAddrOfGlobal(VD),
546                     getContext().getDeclAlign(VD));
547         }
548         // Get the address of the threadprivate variable.
549         Address PrivateAddr = EmitLValue(*IRef).getAddress();
550         if (CopiedVars.size() == 1) {
551           // At first check if current thread is a master thread. If it is, no
552           // need to copy data.
553           CopyBegin = createBasicBlock("copyin.not.master");
554           CopyEnd = createBasicBlock("copyin.not.master.end");
555           Builder.CreateCondBr(
556               Builder.CreateICmpNE(
557                   Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
558                   Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
559               CopyBegin, CopyEnd);
560           EmitBlock(CopyBegin);
561         }
562         auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
563         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
564         EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
565       }
566       ++IRef;
567       ++ISrcRef;
568       ++IDestRef;
569     }
570   }
571   if (CopyEnd) {
572     // Exit out of copying procedure for non-master thread.
573     EmitBlock(CopyEnd, /*IsFinished=*/true);
574     return true;
575   }
576   return false;
577 }
578 
579 bool CodeGenFunction::EmitOMPLastprivateClauseInit(
580     const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
581   if (!HaveInsertPoint())
582     return false;
583   bool HasAtLeastOneLastprivate = false;
584   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
585   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
586     HasAtLeastOneLastprivate = true;
587     auto IRef = C->varlist_begin();
588     auto IDestRef = C->destination_exprs().begin();
589     for (auto *IInit : C->private_copies()) {
590       // Keep the address of the original variable for future update at the end
591       // of the loop.
592       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
593       if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
594         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
595         PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
596           DeclRefExpr DRE(
597               const_cast<VarDecl *>(OrigVD),
598               /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
599                   OrigVD) != nullptr,
600               (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
601           return EmitLValue(&DRE).getAddress();
602         });
603         // Check if the variable is also a firstprivate: in this case IInit is
604         // not generated. Initialization of this variable will happen in codegen
605         // for 'firstprivate' clause.
606         if (IInit) {
607           auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
608           bool IsRegistered =
609               PrivateScope.addPrivate(OrigVD, [&]() -> Address {
610                 // Emit private VarDecl with copy init.
611                 EmitDecl(*VD);
612                 return GetAddrOfLocalVar(VD);
613               });
614           assert(IsRegistered &&
615                  "lastprivate var already registered as private");
616           (void)IsRegistered;
617         }
618       }
619       ++IRef;
620       ++IDestRef;
621     }
622   }
623   return HasAtLeastOneLastprivate;
624 }
625 
626 void CodeGenFunction::EmitOMPLastprivateClauseFinal(
627     const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
628   if (!HaveInsertPoint())
629     return;
630   // Emit following code:
631   // if (<IsLastIterCond>) {
632   //   orig_var1 = private_orig_var1;
633   //   ...
634   //   orig_varn = private_orig_varn;
635   // }
636   llvm::BasicBlock *ThenBB = nullptr;
637   llvm::BasicBlock *DoneBB = nullptr;
638   if (IsLastIterCond) {
639     ThenBB = createBasicBlock(".omp.lastprivate.then");
640     DoneBB = createBasicBlock(".omp.lastprivate.done");
641     Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
642     EmitBlock(ThenBB);
643   }
644   llvm::DenseMap<const Decl *, const Expr *> LoopCountersAndUpdates;
645   if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
646     auto IC = LoopDirective->counters().begin();
647     for (auto F : LoopDirective->finals()) {
648       auto *D = cast<DeclRefExpr>(*IC)->getDecl()->getCanonicalDecl();
649       LoopCountersAndUpdates[D] = F;
650       ++IC;
651     }
652   }
653   llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
654   for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
655     auto IRef = C->varlist_begin();
656     auto ISrcRef = C->source_exprs().begin();
657     auto IDestRef = C->destination_exprs().begin();
658     for (auto *AssignOp : C->assignment_ops()) {
659       auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
660       QualType Type = PrivateVD->getType();
661       auto *CanonicalVD = PrivateVD->getCanonicalDecl();
662       if (AlreadyEmittedVars.insert(CanonicalVD).second) {
663         // If lastprivate variable is a loop control variable for loop-based
664         // directive, update its value before copyin back to original
665         // variable.
666         if (auto *UpExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
667           EmitIgnoredExpr(UpExpr);
668         auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
669         auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
670         // Get the address of the original variable.
671         Address OriginalAddr = GetAddrOfLocalVar(DestVD);
672         // Get the address of the private variable.
673         Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
674         if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
675           PrivateAddr =
676               Address(Builder.CreateLoad(PrivateAddr),
677                       getNaturalTypeAlignment(RefTy->getPointeeType()));
678         EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
679       }
680       ++IRef;
681       ++ISrcRef;
682       ++IDestRef;
683     }
684     if (auto *PostUpdate = C->getPostUpdateExpr())
685       EmitIgnoredExpr(PostUpdate);
686   }
687   if (IsLastIterCond)
688     EmitBlock(DoneBB, /*IsFinished=*/true);
689 }
690 
691 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
692                           LValue BaseLV, llvm::Value *Addr) {
693   Address Tmp = Address::invalid();
694   Address TopTmp = Address::invalid();
695   Address MostTopTmp = Address::invalid();
696   BaseTy = BaseTy.getNonReferenceType();
697   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
698          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
699     Tmp = CGF.CreateMemTemp(BaseTy);
700     if (TopTmp.isValid())
701       CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
702     else
703       MostTopTmp = Tmp;
704     TopTmp = Tmp;
705     BaseTy = BaseTy->getPointeeType();
706   }
707   llvm::Type *Ty = BaseLV.getPointer()->getType();
708   if (Tmp.isValid())
709     Ty = Tmp.getElementType();
710   Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
711   if (Tmp.isValid()) {
712     CGF.Builder.CreateStore(Addr, Tmp);
713     return MostTopTmp;
714   }
715   return Address(Addr, BaseLV.getAlignment());
716 }
717 
718 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
719                           LValue BaseLV) {
720   BaseTy = BaseTy.getNonReferenceType();
721   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
722          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
723     if (auto *PtrTy = BaseTy->getAs<PointerType>())
724       BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
725     else {
726       BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
727                                              BaseTy->castAs<ReferenceType>());
728     }
729     BaseTy = BaseTy->getPointeeType();
730   }
731   return CGF.MakeAddrLValue(
732       Address(
733           CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
734               BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
735           BaseLV.getAlignment()),
736       BaseLV.getType(), BaseLV.getAlignmentSource());
737 }
738 
739 void CodeGenFunction::EmitOMPReductionClauseInit(
740     const OMPExecutableDirective &D,
741     CodeGenFunction::OMPPrivateScope &PrivateScope) {
742   if (!HaveInsertPoint())
743     return;
744   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
745     auto ILHS = C->lhs_exprs().begin();
746     auto IRHS = C->rhs_exprs().begin();
747     auto IPriv = C->privates().begin();
748     for (auto IRef : C->varlists()) {
749       auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
750       auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
751       auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
752       if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
753         auto *Base = OASE->getBase()->IgnoreParenImpCasts();
754         while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
755           Base = TempOASE->getBase()->IgnoreParenImpCasts();
756         while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
757           Base = TempASE->getBase()->IgnoreParenImpCasts();
758         auto *DE = cast<DeclRefExpr>(Base);
759         auto *OrigVD = cast<VarDecl>(DE->getDecl());
760         auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
761         auto OASELValueUB =
762             EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
763         auto OriginalBaseLValue = EmitLValue(DE);
764         LValue BaseLValue =
765             loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
766                         OriginalBaseLValue);
767         // Store the address of the original variable associated with the LHS
768         // implicit variable.
769         PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address {
770           return OASELValueLB.getAddress();
771         });
772         // Emit reduction copy.
773         bool IsRegistered = PrivateScope.addPrivate(
774             OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
775                      OASELValueUB, OriginalBaseLValue]() -> Address {
776               // Emit VarDecl with copy init for arrays.
777               // Get the address of the original variable captured in current
778               // captured region.
779               auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
780                                                  OASELValueLB.getPointer());
781               Size = Builder.CreateNUWAdd(
782                   Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
783               CodeGenFunction::OpaqueValueMapping OpaqueMap(
784                   *this, cast<OpaqueValueExpr>(
785                              getContext()
786                                  .getAsVariableArrayType(PrivateVD->getType())
787                                  ->getSizeExpr()),
788                   RValue::get(Size));
789               EmitVariablyModifiedType(PrivateVD->getType());
790               auto Emission = EmitAutoVarAlloca(*PrivateVD);
791               auto Addr = Emission.getAllocatedAddress();
792               auto *Init = PrivateVD->getInit();
793               EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
794               EmitAutoVarCleanups(Emission);
795               // Emit private VarDecl with reduction init.
796               auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
797                                                    OASELValueLB.getPointer());
798               auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
799               return castToBase(*this, OrigVD->getType(),
800                                 OASELValueLB.getType(), OriginalBaseLValue,
801                                 Ptr);
802             });
803         assert(IsRegistered && "private var already registered as private");
804         // Silence the warning about unused variable.
805         (void)IsRegistered;
806         PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
807           return GetAddrOfLocalVar(PrivateVD);
808         });
809       } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
810         auto *Base = ASE->getBase()->IgnoreParenImpCasts();
811         while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
812           Base = TempASE->getBase()->IgnoreParenImpCasts();
813         auto *DE = cast<DeclRefExpr>(Base);
814         auto *OrigVD = cast<VarDecl>(DE->getDecl());
815         auto ASELValue = EmitLValue(ASE);
816         auto OriginalBaseLValue = EmitLValue(DE);
817         LValue BaseLValue = loadToBegin(
818             *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
819         // Store the address of the original variable associated with the LHS
820         // implicit variable.
821         PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address {
822           return ASELValue.getAddress();
823         });
824         // Emit reduction copy.
825         bool IsRegistered = PrivateScope.addPrivate(
826             OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
827                      OriginalBaseLValue]() -> Address {
828               // Emit private VarDecl with reduction init.
829               EmitDecl(*PrivateVD);
830               auto Addr = GetAddrOfLocalVar(PrivateVD);
831               auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
832                                                    ASELValue.getPointer());
833               auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
834               return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
835                                 OriginalBaseLValue, Ptr);
836             });
837         assert(IsRegistered && "private var already registered as private");
838         // Silence the warning about unused variable.
839         (void)IsRegistered;
840         PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
841           return Builder.CreateElementBitCast(
842               GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
843               "rhs.begin");
844         });
845       } else {
846         auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
847         QualType Type = PrivateVD->getType();
848         if (getContext().getAsArrayType(Type)) {
849           // Store the address of the original variable associated with the LHS
850           // implicit variable.
851           DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
852                           CapturedStmtInfo->lookup(OrigVD) != nullptr,
853                           IRef->getType(), VK_LValue, IRef->getExprLoc());
854           Address OriginalAddr = EmitLValue(&DRE).getAddress();
855           PrivateScope.addPrivate(LHSVD, [this, OriginalAddr,
856                                           LHSVD]() -> Address {
857             return Builder.CreateElementBitCast(
858                 OriginalAddr, ConvertTypeForMem(LHSVD->getType()),
859                 "lhs.begin");
860           });
861           bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
862             if (Type->isVariablyModifiedType()) {
863               CodeGenFunction::OpaqueValueMapping OpaqueMap(
864                   *this, cast<OpaqueValueExpr>(
865                              getContext()
866                                  .getAsVariableArrayType(PrivateVD->getType())
867                                  ->getSizeExpr()),
868                   RValue::get(
869                       getTypeSize(OrigVD->getType().getNonReferenceType())));
870               EmitVariablyModifiedType(Type);
871             }
872             auto Emission = EmitAutoVarAlloca(*PrivateVD);
873             auto Addr = Emission.getAllocatedAddress();
874             auto *Init = PrivateVD->getInit();
875             EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), Init);
876             EmitAutoVarCleanups(Emission);
877             return Emission.getAllocatedAddress();
878           });
879           assert(IsRegistered && "private var already registered as private");
880           // Silence the warning about unused variable.
881           (void)IsRegistered;
882           PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
883             return Builder.CreateElementBitCast(
884                 GetAddrOfLocalVar(PrivateVD),
885                 ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
886           });
887         } else {
888           // Store the address of the original variable associated with the LHS
889           // implicit variable.
890           PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> Address {
891             DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
892                             CapturedStmtInfo->lookup(OrigVD) != nullptr,
893                             IRef->getType(), VK_LValue, IRef->getExprLoc());
894             return EmitLValue(&DRE).getAddress();
895           });
896           // Emit reduction copy.
897           bool IsRegistered =
898               PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> Address {
899                 // Emit private VarDecl with reduction init.
900                 EmitDecl(*PrivateVD);
901                 return GetAddrOfLocalVar(PrivateVD);
902               });
903           assert(IsRegistered && "private var already registered as private");
904           // Silence the warning about unused variable.
905           (void)IsRegistered;
906           PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
907             return GetAddrOfLocalVar(PrivateVD);
908           });
909         }
910       }
911       ++ILHS;
912       ++IRHS;
913       ++IPriv;
914     }
915   }
916 }
917 
918 void CodeGenFunction::EmitOMPReductionClauseFinal(
919     const OMPExecutableDirective &D) {
920   if (!HaveInsertPoint())
921     return;
922   llvm::SmallVector<const Expr *, 8> Privates;
923   llvm::SmallVector<const Expr *, 8> LHSExprs;
924   llvm::SmallVector<const Expr *, 8> RHSExprs;
925   llvm::SmallVector<const Expr *, 8> ReductionOps;
926   bool HasAtLeastOneReduction = false;
927   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
928     HasAtLeastOneReduction = true;
929     Privates.append(C->privates().begin(), C->privates().end());
930     LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
931     RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
932     ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
933   }
934   if (HasAtLeastOneReduction) {
935     // Emit nowait reduction if nowait clause is present or directive is a
936     // parallel directive (it always has implicit barrier).
937     CGM.getOpenMPRuntime().emitReduction(
938         *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
939         D.getSingleClause<OMPNowaitClause>() ||
940             isOpenMPParallelDirective(D.getDirectiveKind()) ||
941             D.getDirectiveKind() == OMPD_simd,
942         D.getDirectiveKind() == OMPD_simd);
943   }
944 }
945 
946 static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
947                                            const OMPExecutableDirective &S,
948                                            OpenMPDirectiveKind InnermostKind,
949                                            const RegionCodeGenTy &CodeGen) {
950   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
951   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
952   CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
953   auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
954       S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
955   if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
956     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
957     auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
958                                          /*IgnoreResultAssign*/ true);
959     CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
960         CGF, NumThreads, NumThreadsClause->getLocStart());
961   }
962   if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
963     CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
964     CGF.CGM.getOpenMPRuntime().emitProcBindClause(
965         CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
966   }
967   const Expr *IfCond = nullptr;
968   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
969     if (C->getNameModifier() == OMPD_unknown ||
970         C->getNameModifier() == OMPD_parallel) {
971       IfCond = C->getCondition();
972       break;
973     }
974   }
975   CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
976                                               CapturedVars, IfCond);
977 }
978 
979 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
980   OMPLexicalScope Scope(*this, S);
981   // Emit parallel region as a standalone region.
982   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
983     OMPPrivateScope PrivateScope(CGF);
984     bool Copyins = CGF.EmitOMPCopyinClause(S);
985     (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
986     if (Copyins) {
987       // Emit implicit barrier to synchronize threads and avoid data races on
988       // propagation master's thread values of threadprivate variables to local
989       // instances of that variables of all other implicit threads.
990       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
991           CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
992           /*ForceSimpleCall=*/true);
993     }
994     CGF.EmitOMPPrivateClause(S, PrivateScope);
995     CGF.EmitOMPReductionClauseInit(S, PrivateScope);
996     (void)PrivateScope.Privatize();
997     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
998     CGF.EmitOMPReductionClauseFinal(S);
999   };
1000   emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen);
1001 }
1002 
1003 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
1004                                       JumpDest LoopExit) {
1005   RunCleanupsScope BodyScope(*this);
1006   // Update counters values on current iteration.
1007   for (auto I : D.updates()) {
1008     EmitIgnoredExpr(I);
1009   }
1010   // Update the linear variables.
1011   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1012     for (auto U : C->updates()) {
1013       EmitIgnoredExpr(U);
1014     }
1015   }
1016 
1017   // On a continue in the body, jump to the end.
1018   auto Continue = getJumpDestInCurrentScope("omp.body.continue");
1019   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1020   // Emit loop body.
1021   EmitStmt(D.getBody());
1022   // The end (updates/cleanups).
1023   EmitBlock(Continue.getBlock());
1024   BreakContinueStack.pop_back();
1025 }
1026 
1027 void CodeGenFunction::EmitOMPInnerLoop(
1028     const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
1029     const Expr *IncExpr,
1030     const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
1031     const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
1032   auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
1033 
1034   // Start the loop with a block that tests the condition.
1035   auto CondBlock = createBasicBlock("omp.inner.for.cond");
1036   EmitBlock(CondBlock);
1037   LoopStack.push(CondBlock);
1038 
1039   // If there are any cleanups between here and the loop-exit scope,
1040   // create a block to stage a loop exit along.
1041   auto ExitBlock = LoopExit.getBlock();
1042   if (RequiresCleanup)
1043     ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
1044 
1045   auto LoopBody = createBasicBlock("omp.inner.for.body");
1046 
1047   // Emit condition.
1048   EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
1049   if (ExitBlock != LoopExit.getBlock()) {
1050     EmitBlock(ExitBlock);
1051     EmitBranchThroughCleanup(LoopExit);
1052   }
1053 
1054   EmitBlock(LoopBody);
1055   incrementProfileCounter(&S);
1056 
1057   // Create a block for the increment.
1058   auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
1059   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1060 
1061   BodyGen(*this);
1062 
1063   // Emit "IV = IV + 1" and a back-edge to the condition block.
1064   EmitBlock(Continue.getBlock());
1065   EmitIgnoredExpr(IncExpr);
1066   PostIncGen(*this);
1067   BreakContinueStack.pop_back();
1068   EmitBranch(CondBlock);
1069   LoopStack.pop();
1070   // Emit the fall-through block.
1071   EmitBlock(LoopExit.getBlock());
1072 }
1073 
1074 void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
1075   if (!HaveInsertPoint())
1076     return;
1077   // Emit inits for the linear variables.
1078   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1079     for (auto Init : C->inits()) {
1080       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
1081       auto *OrigVD = cast<VarDecl>(
1082           cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())->getDecl());
1083       DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1084                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
1085                       VD->getInit()->getType(), VK_LValue,
1086                       VD->getInit()->getExprLoc());
1087       AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
1088       EmitExprAsInit(&DRE, VD,
1089                MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()),
1090                      /*capturedByInit=*/false);
1091       EmitAutoVarCleanups(Emission);
1092     }
1093     // Emit the linear steps for the linear clauses.
1094     // If a step is not constant, it is pre-calculated before the loop.
1095     if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
1096       if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
1097         EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
1098         // Emit calculation of the linear step.
1099         EmitIgnoredExpr(CS);
1100       }
1101   }
1102 }
1103 
1104 static void emitLinearClauseFinal(CodeGenFunction &CGF,
1105                                   const OMPLoopDirective &D) {
1106   if (!CGF.HaveInsertPoint())
1107     return;
1108   // Emit the final values of the linear variables.
1109   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1110     auto IC = C->varlist_begin();
1111     for (auto F : C->finals()) {
1112       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
1113       DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1114                       CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
1115                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1116       Address OrigAddr = CGF.EmitLValue(&DRE).getAddress();
1117       CodeGenFunction::OMPPrivateScope VarScope(CGF);
1118       VarScope.addPrivate(OrigVD,
1119                           [OrigAddr]() -> Address { return OrigAddr; });
1120       (void)VarScope.Privatize();
1121       CGF.EmitIgnoredExpr(F);
1122       ++IC;
1123     }
1124   }
1125 }
1126 
1127 static void emitAlignedClause(CodeGenFunction &CGF,
1128                               const OMPExecutableDirective &D) {
1129   if (!CGF.HaveInsertPoint())
1130     return;
1131   for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
1132     unsigned ClauseAlignment = 0;
1133     if (auto AlignmentExpr = Clause->getAlignment()) {
1134       auto AlignmentCI =
1135           cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
1136       ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
1137     }
1138     for (auto E : Clause->varlists()) {
1139       unsigned Alignment = ClauseAlignment;
1140       if (Alignment == 0) {
1141         // OpenMP [2.8.1, Description]
1142         // If no optional parameter is specified, implementation-defined default
1143         // alignments for SIMD instructions on the target platforms are assumed.
1144         Alignment =
1145             CGF.getContext()
1146                 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
1147                     E->getType()->getPointeeType()))
1148                 .getQuantity();
1149       }
1150       assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
1151              "alignment is not power of 2");
1152       if (Alignment != 0) {
1153         llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
1154         CGF.EmitAlignmentAssumption(PtrValue, Alignment);
1155       }
1156     }
1157   }
1158 }
1159 
1160 static void emitPrivateLoopCounters(CodeGenFunction &CGF,
1161                                     CodeGenFunction::OMPPrivateScope &LoopScope,
1162                                     ArrayRef<Expr *> Counters,
1163                                     ArrayRef<Expr *> PrivateCounters) {
1164   if (!CGF.HaveInsertPoint())
1165     return;
1166   auto I = PrivateCounters.begin();
1167   for (auto *E : Counters) {
1168     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1169     auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
1170     Address Addr = Address::invalid();
1171     (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
1172       // Emit var without initialization.
1173       auto VarEmission = CGF.EmitAutoVarAlloca(*PrivateVD);
1174       CGF.EmitAutoVarCleanups(VarEmission);
1175       Addr = VarEmission.getAllocatedAddress();
1176       return Addr;
1177     });
1178     (void)LoopScope.addPrivate(VD, [&]() -> Address { return Addr; });
1179     ++I;
1180   }
1181 }
1182 
1183 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
1184                         const Expr *Cond, llvm::BasicBlock *TrueBlock,
1185                         llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
1186   if (!CGF.HaveInsertPoint())
1187     return;
1188   {
1189     CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
1190     emitPrivateLoopCounters(CGF, PreCondScope, S.counters(),
1191                             S.private_counters());
1192     (void)PreCondScope.Privatize();
1193     // Get initial values of real counters.
1194     for (auto I : S.inits()) {
1195       CGF.EmitIgnoredExpr(I);
1196     }
1197   }
1198   // Check that loop is executed at least one time.
1199   CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
1200 }
1201 
1202 static void
1203 emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
1204                       CodeGenFunction::OMPPrivateScope &PrivateScope) {
1205   if (!CGF.HaveInsertPoint())
1206     return;
1207   for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
1208     auto CurPrivate = C->privates().begin();
1209     for (auto *E : C->varlists()) {
1210       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
1211       auto *PrivateVD =
1212           cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
1213       bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
1214         // Emit private VarDecl with copy init.
1215         CGF.EmitVarDecl(*PrivateVD);
1216         return CGF.GetAddrOfLocalVar(PrivateVD);
1217       });
1218       assert(IsRegistered && "linear var already registered as private");
1219       // Silence the warning about unused variable.
1220       (void)IsRegistered;
1221       ++CurPrivate;
1222     }
1223   }
1224 }
1225 
1226 static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
1227                                      const OMPExecutableDirective &D,
1228                                      bool IsMonotonic) {
1229   if (!CGF.HaveInsertPoint())
1230     return;
1231   if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
1232     RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
1233                                  /*ignoreResult=*/true);
1234     llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1235     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1236     // In presence of finite 'safelen', it may be unsafe to mark all
1237     // the memory instructions parallel, because loop-carried
1238     // dependences of 'safelen' iterations are possible.
1239     if (!IsMonotonic)
1240       CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
1241   } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
1242     RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
1243                                  /*ignoreResult=*/true);
1244     llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
1245     CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
1246     // In presence of finite 'safelen', it may be unsafe to mark all
1247     // the memory instructions parallel, because loop-carried
1248     // dependences of 'safelen' iterations are possible.
1249     CGF.LoopStack.setParallel(false);
1250   }
1251 }
1252 
1253 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
1254                                       bool IsMonotonic) {
1255   // Walk clauses and process safelen/lastprivate.
1256   LoopStack.setParallel(!IsMonotonic);
1257   LoopStack.setVectorizeEnable(true);
1258   emitSimdlenSafelenClause(*this, D, IsMonotonic);
1259 }
1260 
1261 void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) {
1262   if (!HaveInsertPoint())
1263     return;
1264   auto IC = D.counters().begin();
1265   for (auto F : D.finals()) {
1266     auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
1267     if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) {
1268       DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
1269                       CapturedStmtInfo->lookup(OrigVD) != nullptr,
1270                       (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
1271       Address OrigAddr = EmitLValue(&DRE).getAddress();
1272       OMPPrivateScope VarScope(*this);
1273       VarScope.addPrivate(OrigVD,
1274                           [OrigAddr]() -> Address { return OrigAddr; });
1275       (void)VarScope.Privatize();
1276       EmitIgnoredExpr(F);
1277     }
1278     ++IC;
1279   }
1280   emitLinearClauseFinal(*this, D);
1281 }
1282 
1283 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
1284   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1285     // if (PreCond) {
1286     //   for (IV in 0..LastIteration) BODY;
1287     //   <Final counter/linear vars updates>;
1288     // }
1289     //
1290 
1291     // Emit: if (PreCond) - begin.
1292     // If the condition constant folds and can be elided, avoid emitting the
1293     // whole loop.
1294     bool CondConstant;
1295     llvm::BasicBlock *ContBlock = nullptr;
1296     if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1297       if (!CondConstant)
1298         return;
1299     } else {
1300       auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
1301       ContBlock = CGF.createBasicBlock("simd.if.end");
1302       emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
1303                   CGF.getProfileCount(&S));
1304       CGF.EmitBlock(ThenBlock);
1305       CGF.incrementProfileCounter(&S);
1306     }
1307 
1308     // Emit the loop iteration variable.
1309     const Expr *IVExpr = S.getIterationVariable();
1310     const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
1311     CGF.EmitVarDecl(*IVDecl);
1312     CGF.EmitIgnoredExpr(S.getInit());
1313 
1314     // Emit the iterations count variable.
1315     // If it is not a variable, Sema decided to calculate iterations count on
1316     // each iteration (e.g., it is foldable into a constant).
1317     if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1318       CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1319       // Emit calculation of the iterations count.
1320       CGF.EmitIgnoredExpr(S.getCalcLastIteration());
1321     }
1322 
1323     CGF.EmitOMPSimdInit(S);
1324 
1325     emitAlignedClause(CGF, S);
1326     CGF.EmitOMPLinearClauseInit(S);
1327     bool HasLastprivateClause;
1328     {
1329       OMPPrivateScope LoopScope(CGF);
1330       emitPrivateLoopCounters(CGF, LoopScope, S.counters(),
1331                               S.private_counters());
1332       emitPrivateLinearVars(CGF, S, LoopScope);
1333       CGF.EmitOMPPrivateClause(S, LoopScope);
1334       CGF.EmitOMPReductionClauseInit(S, LoopScope);
1335       HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1336       (void)LoopScope.Privatize();
1337       CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1338                            S.getInc(),
1339                            [&S](CodeGenFunction &CGF) {
1340                              CGF.EmitOMPLoopBody(S, JumpDest());
1341                              CGF.EmitStopPoint(&S);
1342                            },
1343                            [](CodeGenFunction &) {});
1344       // Emit final copy of the lastprivate variables at the end of loops.
1345       if (HasLastprivateClause) {
1346         CGF.EmitOMPLastprivateClauseFinal(S);
1347       }
1348       CGF.EmitOMPReductionClauseFinal(S);
1349     }
1350     CGF.EmitOMPSimdFinal(S);
1351     // Emit: if (PreCond) - end.
1352     if (ContBlock) {
1353       CGF.EmitBranch(ContBlock);
1354       CGF.EmitBlock(ContBlock, true);
1355     }
1356   };
1357   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1358 }
1359 
1360 void CodeGenFunction::EmitOMPForOuterLoop(
1361     OpenMPScheduleClauseKind ScheduleKind, bool IsMonotonic,
1362     const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
1363     Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) {
1364   auto &RT = CGM.getOpenMPRuntime();
1365 
1366   // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
1367   const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
1368 
1369   assert((Ordered ||
1370           !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
1371          "static non-chunked schedule does not need outer loop");
1372 
1373   // Emit outer loop.
1374   //
1375   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1376   // When schedule(dynamic,chunk_size) is specified, the iterations are
1377   // distributed to threads in the team in chunks as the threads request them.
1378   // Each thread executes a chunk of iterations, then requests another chunk,
1379   // until no chunks remain to be distributed. Each chunk contains chunk_size
1380   // iterations, except for the last chunk to be distributed, which may have
1381   // fewer iterations. When no chunk_size is specified, it defaults to 1.
1382   //
1383   // When schedule(guided,chunk_size) is specified, the iterations are assigned
1384   // to threads in the team in chunks as the executing threads request them.
1385   // Each thread executes a chunk of iterations, then requests another chunk,
1386   // until no chunks remain to be assigned. For a chunk_size of 1, the size of
1387   // each chunk is proportional to the number of unassigned iterations divided
1388   // by the number of threads in the team, decreasing to 1. For a chunk_size
1389   // with value k (greater than 1), the size of each chunk is determined in the
1390   // same way, with the restriction that the chunks do not contain fewer than k
1391   // iterations (except for the last chunk to be assigned, which may have fewer
1392   // than k iterations).
1393   //
1394   // When schedule(auto) is specified, the decision regarding scheduling is
1395   // delegated to the compiler and/or runtime system. The programmer gives the
1396   // implementation the freedom to choose any possible mapping of iterations to
1397   // threads in the team.
1398   //
1399   // When schedule(runtime) is specified, the decision regarding scheduling is
1400   // deferred until run time, and the schedule and chunk size are taken from the
1401   // run-sched-var ICV. If the ICV is set to auto, the schedule is
1402   // implementation defined
1403   //
1404   // while(__kmpc_dispatch_next(&LB, &UB)) {
1405   //   idx = LB;
1406   //   while (idx <= UB) { BODY; ++idx;
1407   //   __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
1408   //   } // inner loop
1409   // }
1410   //
1411   // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1412   // When schedule(static, chunk_size) is specified, iterations are divided into
1413   // chunks of size chunk_size, and the chunks are assigned to the threads in
1414   // the team in a round-robin fashion in the order of the thread number.
1415   //
1416   // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
1417   //   while (idx <= UB) { BODY; ++idx; } // inner loop
1418   //   LB = LB + ST;
1419   //   UB = UB + ST;
1420   // }
1421   //
1422 
1423   const Expr *IVExpr = S.getIterationVariable();
1424   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1425   const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1426 
1427   if (DynamicOrOrdered) {
1428     llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration());
1429     RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind,
1430                            IVSize, IVSigned, Ordered, UBVal, Chunk);
1431   } else {
1432     RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1433                          IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
1434   }
1435 
1436   auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
1437 
1438   // Start the loop with a block that tests the condition.
1439   auto CondBlock = createBasicBlock("omp.dispatch.cond");
1440   EmitBlock(CondBlock);
1441   LoopStack.push(CondBlock);
1442 
1443   llvm::Value *BoolCondVal = nullptr;
1444   if (!DynamicOrOrdered) {
1445     // UB = min(UB, GlobalUB)
1446     EmitIgnoredExpr(S.getEnsureUpperBound());
1447     // IV = LB
1448     EmitIgnoredExpr(S.getInit());
1449     // IV < UB
1450     BoolCondVal = EvaluateExprAsBool(S.getCond());
1451   } else {
1452     BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
1453                                     IL, LB, UB, ST);
1454   }
1455 
1456   // If there are any cleanups between here and the loop-exit scope,
1457   // create a block to stage a loop exit along.
1458   auto ExitBlock = LoopExit.getBlock();
1459   if (LoopScope.requiresCleanups())
1460     ExitBlock = createBasicBlock("omp.dispatch.cleanup");
1461 
1462   auto LoopBody = createBasicBlock("omp.dispatch.body");
1463   Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
1464   if (ExitBlock != LoopExit.getBlock()) {
1465     EmitBlock(ExitBlock);
1466     EmitBranchThroughCleanup(LoopExit);
1467   }
1468   EmitBlock(LoopBody);
1469 
1470   // Emit "IV = LB" (in case of static schedule, we have already calculated new
1471   // LB for loop condition and emitted it above).
1472   if (DynamicOrOrdered)
1473     EmitIgnoredExpr(S.getInit());
1474 
1475   // Create a block for the increment.
1476   auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
1477   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
1478 
1479   // Generate !llvm.loop.parallel metadata for loads and stores for loops
1480   // with dynamic/guided scheduling and without ordered clause.
1481   if (!isOpenMPSimdDirective(S.getDirectiveKind()))
1482     LoopStack.setParallel(!IsMonotonic);
1483   else
1484     EmitOMPSimdInit(S, IsMonotonic);
1485 
1486   SourceLocation Loc = S.getLocStart();
1487   EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(),
1488                    [&S, LoopExit](CodeGenFunction &CGF) {
1489                      CGF.EmitOMPLoopBody(S, LoopExit);
1490                      CGF.EmitStopPoint(&S);
1491                    },
1492                    [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
1493                      if (Ordered) {
1494                        CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
1495                            CGF, Loc, IVSize, IVSigned);
1496                      }
1497                    });
1498 
1499   EmitBlock(Continue.getBlock());
1500   BreakContinueStack.pop_back();
1501   if (!DynamicOrOrdered) {
1502     // Emit "LB = LB + Stride", "UB = UB + Stride".
1503     EmitIgnoredExpr(S.getNextLowerBound());
1504     EmitIgnoredExpr(S.getNextUpperBound());
1505   }
1506 
1507   EmitBranch(CondBlock);
1508   LoopStack.pop();
1509   // Emit the fall-through block.
1510   EmitBlock(LoopExit.getBlock());
1511 
1512   // Tell the runtime we are done.
1513   if (!DynamicOrOrdered)
1514     RT.emitForStaticFinish(*this, S.getLocEnd());
1515 }
1516 
1517 /// \brief Emit a helper variable and return corresponding lvalue.
1518 static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
1519                                const DeclRefExpr *Helper) {
1520   auto VDecl = cast<VarDecl>(Helper->getDecl());
1521   CGF.EmitVarDecl(*VDecl);
1522   return CGF.EmitLValue(Helper);
1523 }
1524 
1525 namespace {
1526   struct ScheduleKindModifiersTy {
1527     OpenMPScheduleClauseKind Kind;
1528     OpenMPScheduleClauseModifier M1;
1529     OpenMPScheduleClauseModifier M2;
1530     ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
1531                             OpenMPScheduleClauseModifier M1,
1532                             OpenMPScheduleClauseModifier M2)
1533         : Kind(Kind), M1(M1), M2(M2) {}
1534   };
1535 } // namespace
1536 
1537 bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
1538   // Emit the loop iteration variable.
1539   auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1540   auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1541   EmitVarDecl(*IVDecl);
1542 
1543   // Emit the iterations count variable.
1544   // If it is not a variable, Sema decided to calculate iterations count on each
1545   // iteration (e.g., it is foldable into a constant).
1546   if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1547     EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1548     // Emit calculation of the iterations count.
1549     EmitIgnoredExpr(S.getCalcLastIteration());
1550   }
1551 
1552   auto &RT = CGM.getOpenMPRuntime();
1553 
1554   bool HasLastprivateClause;
1555   // Check pre-condition.
1556   {
1557     // Skip the entire loop if we don't meet the precondition.
1558     // If the condition constant folds and can be elided, avoid emitting the
1559     // whole loop.
1560     bool CondConstant;
1561     llvm::BasicBlock *ContBlock = nullptr;
1562     if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1563       if (!CondConstant)
1564         return false;
1565     } else {
1566       auto *ThenBlock = createBasicBlock("omp.precond.then");
1567       ContBlock = createBasicBlock("omp.precond.end");
1568       emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
1569                   getProfileCount(&S));
1570       EmitBlock(ThenBlock);
1571       incrementProfileCounter(&S);
1572     }
1573 
1574     emitAlignedClause(*this, S);
1575     EmitOMPLinearClauseInit(S);
1576     // Emit 'then' code.
1577     {
1578       // Emit helper vars inits.
1579       LValue LB =
1580           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1581       LValue UB =
1582           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1583       LValue ST =
1584           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1585       LValue IL =
1586           EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1587 
1588       OMPPrivateScope LoopScope(*this);
1589       if (EmitOMPFirstprivateClause(S, LoopScope)) {
1590         // Emit implicit barrier to synchronize threads and avoid data races on
1591         // initialization of firstprivate variables and post-update of
1592         // lastprivate variables.
1593         CGM.getOpenMPRuntime().emitBarrierCall(
1594             *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1595             /*ForceSimpleCall=*/true);
1596       }
1597       EmitOMPPrivateClause(S, LoopScope);
1598       HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
1599       EmitOMPReductionClauseInit(S, LoopScope);
1600       emitPrivateLoopCounters(*this, LoopScope, S.counters(),
1601                               S.private_counters());
1602       emitPrivateLinearVars(*this, S, LoopScope);
1603       (void)LoopScope.Privatize();
1604 
1605       // Detect the loop schedule kind and chunk.
1606       llvm::Value *Chunk = nullptr;
1607       OpenMPScheduleClauseKind ScheduleKind = OMPC_SCHEDULE_unknown;
1608       OpenMPScheduleClauseModifier M1 = OMPC_SCHEDULE_MODIFIER_unknown;
1609       OpenMPScheduleClauseModifier M2 = OMPC_SCHEDULE_MODIFIER_unknown;
1610       if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
1611         ScheduleKind = C->getScheduleKind();
1612         M1 = C->getFirstScheduleModifier();
1613         M2 = C->getSecondScheduleModifier();
1614         if (const auto *Ch = C->getChunkSize()) {
1615           Chunk = EmitScalarExpr(Ch);
1616           Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1617                                        S.getIterationVariable()->getType(),
1618                                        S.getLocStart());
1619         }
1620       }
1621       const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1622       const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1623       const bool Ordered = S.getSingleClause<OMPOrderedClause>() != nullptr;
1624       // OpenMP 4.5, 2.7.1 Loop Construct, Description.
1625       // If the static schedule kind is specified or if the ordered clause is
1626       // specified, and if no monotonic modifier is specified, the effect will
1627       // be as if the monotonic modifier was specified.
1628       if (RT.isStaticNonchunked(ScheduleKind,
1629                                 /* Chunked */ Chunk != nullptr) &&
1630           !Ordered) {
1631         if (isOpenMPSimdDirective(S.getDirectiveKind()))
1632           EmitOMPSimdInit(S, /*IsMonotonic=*/true);
1633         // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1634         // When no chunk_size is specified, the iteration space is divided into
1635         // chunks that are approximately equal in size, and at most one chunk is
1636         // distributed to each thread. Note that the size of the chunks is
1637         // unspecified in this case.
1638         RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
1639                              IVSize, IVSigned, Ordered,
1640                              IL.getAddress(), LB.getAddress(),
1641                              UB.getAddress(), ST.getAddress());
1642         auto LoopExit =
1643             getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
1644         // UB = min(UB, GlobalUB);
1645         EmitIgnoredExpr(S.getEnsureUpperBound());
1646         // IV = LB;
1647         EmitIgnoredExpr(S.getInit());
1648         // while (idx <= UB) { BODY; ++idx; }
1649         EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
1650                          S.getInc(),
1651                          [&S, LoopExit](CodeGenFunction &CGF) {
1652                            CGF.EmitOMPLoopBody(S, LoopExit);
1653                            CGF.EmitStopPoint(&S);
1654                          },
1655                          [](CodeGenFunction &) {});
1656         EmitBlock(LoopExit.getBlock());
1657         // Tell the runtime we are done.
1658         RT.emitForStaticFinish(*this, S.getLocStart());
1659       } else {
1660         const bool IsMonotonic = Ordered ||
1661                                  ScheduleKind == OMPC_SCHEDULE_static ||
1662                                  ScheduleKind == OMPC_SCHEDULE_unknown ||
1663                                  M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
1664                                  M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
1665         // Emit the outer loop, which requests its work chunk [LB..UB] from
1666         // runtime and runs the inner loop to process it.
1667         EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
1668                             LB.getAddress(), UB.getAddress(), ST.getAddress(),
1669                             IL.getAddress(), Chunk);
1670       }
1671       EmitOMPReductionClauseFinal(S);
1672       // Emit final copy of the lastprivate variables if IsLastIter != 0.
1673       if (HasLastprivateClause)
1674         EmitOMPLastprivateClauseFinal(
1675             S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
1676     }
1677     if (isOpenMPSimdDirective(S.getDirectiveKind())) {
1678       EmitOMPSimdFinal(S);
1679     }
1680     // We're now done with the loop, so jump to the continuation block.
1681     if (ContBlock) {
1682       EmitBranch(ContBlock);
1683       EmitBlock(ContBlock, true);
1684     }
1685   }
1686   return HasLastprivateClause;
1687 }
1688 
1689 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
1690   bool HasLastprivates = false;
1691   {
1692     OMPLexicalScope Scope(*this, S);
1693     auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1694       HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1695     };
1696     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
1697                                                 S.hasCancel());
1698   }
1699 
1700   // Emit an implicit barrier at the end.
1701   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
1702     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1703   }
1704 }
1705 
1706 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
1707   bool HasLastprivates = false;
1708   {
1709     OMPLexicalScope Scope(*this, S);
1710     auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1711       HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1712     };
1713     CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
1714   }
1715 
1716   // Emit an implicit barrier at the end.
1717   if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
1718     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1719   }
1720 }
1721 
1722 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1723                                 const Twine &Name,
1724                                 llvm::Value *Init = nullptr) {
1725   auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1726   if (Init)
1727     CGF.EmitScalarInit(Init, LVal);
1728   return LVal;
1729 }
1730 
1731 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
1732   auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1733   auto *CS = dyn_cast<CompoundStmt>(Stmt);
1734   bool HasLastprivates = false;
1735   auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF) {
1736     auto &C = CGF.CGM.getContext();
1737     auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1738     // Emit helper vars inits.
1739     LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1740                                   CGF.Builder.getInt32(0));
1741     auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
1742                                       : CGF.Builder.getInt32(0);
1743     LValue UB =
1744         createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1745     LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1746                                   CGF.Builder.getInt32(1));
1747     LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1748                                   CGF.Builder.getInt32(0));
1749     // Loop counter.
1750     LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1751     OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1752     CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
1753     OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
1754     CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
1755     // Generate condition for loop.
1756     BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1757                         OK_Ordinary, S.getLocStart(),
1758                         /*fpContractable=*/false);
1759     // Increment for loop counter.
1760     UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
1761                       S.getLocStart());
1762     auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
1763       // Iterate through all sections and emit a switch construct:
1764       // switch (IV) {
1765       //   case 0:
1766       //     <SectionStmt[0]>;
1767       //     break;
1768       // ...
1769       //   case <NumSection> - 1:
1770       //     <SectionStmt[<NumSection> - 1]>;
1771       //     break;
1772       // }
1773       // .omp.sections.exit:
1774       auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1775       auto *SwitchStmt = CGF.Builder.CreateSwitch(
1776           CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1777           CS == nullptr ? 1 : CS->size());
1778       if (CS) {
1779         unsigned CaseNumber = 0;
1780         for (auto *SubStmt : CS->children()) {
1781           auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1782           CGF.EmitBlock(CaseBB);
1783           SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1784           CGF.EmitStmt(SubStmt);
1785           CGF.EmitBranch(ExitBB);
1786           ++CaseNumber;
1787         }
1788       } else {
1789         auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1790         CGF.EmitBlock(CaseBB);
1791         SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
1792         CGF.EmitStmt(Stmt);
1793         CGF.EmitBranch(ExitBB);
1794       }
1795       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1796     };
1797 
1798     CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1799     if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1800       // Emit implicit barrier to synchronize threads and avoid data races on
1801       // initialization of firstprivate variables and post-update of lastprivate
1802       // variables.
1803       CGF.CGM.getOpenMPRuntime().emitBarrierCall(
1804           CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
1805           /*ForceSimpleCall=*/true);
1806     }
1807     CGF.EmitOMPPrivateClause(S, LoopScope);
1808     HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
1809     CGF.EmitOMPReductionClauseInit(S, LoopScope);
1810     (void)LoopScope.Privatize();
1811 
1812     // Emit static non-chunked loop.
1813     CGF.CGM.getOpenMPRuntime().emitForStaticInit(
1814         CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1815         /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
1816         UB.getAddress(), ST.getAddress());
1817     // UB = min(UB, GlobalUB);
1818     auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1819     auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1820         CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1821     CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1822     // IV = LB;
1823     CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1824     // while (idx <= UB) { BODY; ++idx; }
1825     CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1826                          [](CodeGenFunction &) {});
1827     // Tell the runtime we are done.
1828     CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
1829     CGF.EmitOMPReductionClauseFinal(S);
1830 
1831     // Emit final copy of the lastprivate variables if IsLastIter != 0.
1832     if (HasLastprivates)
1833       CGF.EmitOMPLastprivateClauseFinal(
1834           S, CGF.Builder.CreateIsNotNull(
1835                  CGF.EmitLoadOfScalar(IL, S.getLocStart())));
1836   };
1837 
1838   bool HasCancel = false;
1839   if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
1840     HasCancel = OSD->hasCancel();
1841   else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
1842     HasCancel = OPSD->hasCancel();
1843   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
1844                                               HasCancel);
1845   // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1846   // clause. Otherwise the barrier will be generated by the codegen for the
1847   // directive.
1848   if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
1849     // Emit implicit barrier to synchronize threads and avoid data races on
1850     // initialization of firstprivate variables.
1851     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1852                                            OMPD_unknown);
1853   }
1854 }
1855 
1856 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1857   {
1858     OMPLexicalScope Scope(*this, S);
1859     EmitSections(S);
1860   }
1861   // Emit an implicit barrier at the end.
1862   if (!S.getSingleClause<OMPNowaitClause>()) {
1863     CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1864                                            OMPD_sections);
1865   }
1866 }
1867 
1868 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
1869   OMPLexicalScope Scope(*this, S);
1870   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1871     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1872   };
1873   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
1874                                               S.hasCancel());
1875 }
1876 
1877 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
1878   llvm::SmallVector<const Expr *, 8> CopyprivateVars;
1879   llvm::SmallVector<const Expr *, 8> DestExprs;
1880   llvm::SmallVector<const Expr *, 8> SrcExprs;
1881   llvm::SmallVector<const Expr *, 8> AssignmentOps;
1882   // Check if there are any 'copyprivate' clauses associated with this
1883   // 'single' construct.
1884   // Build a list of copyprivate variables along with helper expressions
1885   // (<source>, <destination>, <destination>=<source> expressions)
1886   for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
1887     CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
1888     DestExprs.append(C->destination_exprs().begin(),
1889                      C->destination_exprs().end());
1890     SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
1891     AssignmentOps.append(C->assignment_ops().begin(),
1892                          C->assignment_ops().end());
1893   }
1894   {
1895     OMPLexicalScope Scope(*this, S);
1896     // Emit code for 'single' region along with 'copyprivate' clauses
1897     auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1898       CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1899       (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
1900       CGF.EmitOMPPrivateClause(S, SingleScope);
1901       (void)SingleScope.Privatize();
1902       CGF.EmitStmt(
1903           cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1904     };
1905     CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
1906                                             CopyprivateVars, DestExprs,
1907                                             SrcExprs, AssignmentOps);
1908   }
1909   // Emit an implicit barrier at the end (to avoid data race on firstprivate
1910   // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1911   if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
1912     CGM.getOpenMPRuntime().emitBarrierCall(
1913         *this, S.getLocStart(),
1914         S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
1915   }
1916 }
1917 
1918 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
1919   OMPLexicalScope Scope(*this, S);
1920   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1921     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1922   };
1923   CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
1924 }
1925 
1926 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
1927   OMPLexicalScope Scope(*this, S);
1928   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1929     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1930   };
1931   Expr *Hint = nullptr;
1932   if (auto *HintClause = S.getSingleClause<OMPHintClause>())
1933     Hint = HintClause->getHint();
1934   CGM.getOpenMPRuntime().emitCriticalRegion(*this,
1935                                             S.getDirectiveName().getAsString(),
1936                                             CodeGen, S.getLocStart(), Hint);
1937 }
1938 
1939 void CodeGenFunction::EmitOMPParallelForDirective(
1940     const OMPParallelForDirective &S) {
1941   // Emit directive as a combined directive that consists of two implicit
1942   // directives: 'parallel' with 'for' directive.
1943   OMPLexicalScope Scope(*this, S);
1944   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1945     CGF.EmitOMPWorksharingLoop(S);
1946   };
1947   emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen);
1948 }
1949 
1950 void CodeGenFunction::EmitOMPParallelForSimdDirective(
1951     const OMPParallelForSimdDirective &S) {
1952   // Emit directive as a combined directive that consists of two implicit
1953   // directives: 'parallel' with 'for' directive.
1954   OMPLexicalScope Scope(*this, S);
1955   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1956     CGF.EmitOMPWorksharingLoop(S);
1957   };
1958   emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen);
1959 }
1960 
1961 void CodeGenFunction::EmitOMPParallelSectionsDirective(
1962     const OMPParallelSectionsDirective &S) {
1963   // Emit directive as a combined directive that consists of two implicit
1964   // directives: 'parallel' with 'sections' directive.
1965   OMPLexicalScope Scope(*this, S);
1966   auto &&CodeGen = [&S](CodeGenFunction &CGF) { CGF.EmitSections(S); };
1967   emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen);
1968 }
1969 
1970 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1971   // Emit outlined function for task construct.
1972   OMPLexicalScope Scope(*this, S);
1973   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1974   auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1975   auto *I = CS->getCapturedDecl()->param_begin();
1976   auto *PartId = std::next(I);
1977   // The first function argument for tasks is a thread id, the second one is a
1978   // part id (0 for tied tasks, >=0 for untied task).
1979   llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
1980   // Get list of private variables.
1981   llvm::SmallVector<const Expr *, 8> PrivateVars;
1982   llvm::SmallVector<const Expr *, 8> PrivateCopies;
1983   for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
1984     auto IRef = C->varlist_begin();
1985     for (auto *IInit : C->private_copies()) {
1986       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1987       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1988         PrivateVars.push_back(*IRef);
1989         PrivateCopies.push_back(IInit);
1990       }
1991       ++IRef;
1992     }
1993   }
1994   EmittedAsPrivate.clear();
1995   // Get list of firstprivate variables.
1996   llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1997   llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1998   llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1999   for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
2000     auto IRef = C->varlist_begin();
2001     auto IElemInitRef = C->inits().begin();
2002     for (auto *IInit : C->private_copies()) {
2003       auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
2004       if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
2005         FirstprivateVars.push_back(*IRef);
2006         FirstprivateCopies.push_back(IInit);
2007         FirstprivateInits.push_back(*IElemInitRef);
2008       }
2009       ++IRef;
2010       ++IElemInitRef;
2011     }
2012   }
2013   // Build list of dependences.
2014   llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8>
2015       Dependences;
2016   for (const auto *C : S.getClausesOfKind<OMPDependClause>()) {
2017     for (auto *IRef : C->varlists()) {
2018       Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
2019     }
2020   }
2021   auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars](
2022       CodeGenFunction &CGF) {
2023     // Set proper addresses for generated private copies.
2024     auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
2025     OMPPrivateScope Scope(CGF);
2026     if (!PrivateVars.empty() || !FirstprivateVars.empty()) {
2027       auto *CopyFn = CGF.Builder.CreateLoad(
2028           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
2029       auto *PrivatesPtr = CGF.Builder.CreateLoad(
2030           CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
2031       // Map privates.
2032       llvm::SmallVector<std::pair<const VarDecl *, Address>, 16>
2033           PrivatePtrs;
2034       llvm::SmallVector<llvm::Value *, 16> CallArgs;
2035       CallArgs.push_back(PrivatesPtr);
2036       for (auto *E : PrivateVars) {
2037         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2038         Address PrivatePtr =
2039             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2040         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2041         CallArgs.push_back(PrivatePtr.getPointer());
2042       }
2043       for (auto *E : FirstprivateVars) {
2044         auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
2045         Address PrivatePtr =
2046             CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()));
2047         PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
2048         CallArgs.push_back(PrivatePtr.getPointer());
2049       }
2050       CGF.EmitRuntimeCall(CopyFn, CallArgs);
2051       for (auto &&Pair : PrivatePtrs) {
2052         Address Replacement(CGF.Builder.CreateLoad(Pair.second),
2053                             CGF.getContext().getDeclAlign(Pair.first));
2054         Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
2055       }
2056     }
2057     (void)Scope.Privatize();
2058     if (*PartId) {
2059       // TODO: emit code for untied tasks.
2060     }
2061     CGF.EmitStmt(CS->getCapturedStmt());
2062   };
2063   auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
2064       S, *I, OMPD_task, CodeGen);
2065   // Check if we should emit tied or untied task.
2066   bool Tied = !S.getSingleClause<OMPUntiedClause>();
2067   // Check if the task is final
2068   llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
2069   if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
2070     // If the condition constant folds and can be elided, try to avoid emitting
2071     // the condition and the dead arm of the if/else.
2072     auto *Cond = Clause->getCondition();
2073     bool CondConstant;
2074     if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
2075       Final.setInt(CondConstant);
2076     else
2077       Final.setPointer(EvaluateExprAsBool(Cond));
2078   } else {
2079     // By default the task is not final.
2080     Final.setInt(/*IntVal=*/false);
2081   }
2082   auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
2083   const Expr *IfCond = nullptr;
2084   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2085     if (C->getNameModifier() == OMPD_unknown ||
2086         C->getNameModifier() == OMPD_task) {
2087       IfCond = C->getCondition();
2088       break;
2089     }
2090   }
2091   CGM.getOpenMPRuntime().emitTaskCall(
2092       *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
2093       CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars,
2094       FirstprivateCopies, FirstprivateInits, Dependences);
2095 }
2096 
2097 void CodeGenFunction::EmitOMPTaskyieldDirective(
2098     const OMPTaskyieldDirective &S) {
2099   CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
2100 }
2101 
2102 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
2103   CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
2104 }
2105 
2106 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
2107   CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
2108 }
2109 
2110 void CodeGenFunction::EmitOMPTaskgroupDirective(
2111     const OMPTaskgroupDirective &S) {
2112   OMPLexicalScope Scope(*this, S);
2113   auto &&CodeGen = [&S](CodeGenFunction &CGF) {
2114     CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2115   };
2116   CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
2117 }
2118 
2119 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
2120   CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
2121     if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
2122       return llvm::makeArrayRef(FlushClause->varlist_begin(),
2123                                 FlushClause->varlist_end());
2124     }
2125     return llvm::None;
2126   }(), S.getLocStart());
2127 }
2128 
2129 void CodeGenFunction::EmitOMPDistributeDirective(
2130     const OMPDistributeDirective &S) {
2131   llvm_unreachable("CodeGen for 'omp distribute' is not supported yet.");
2132 }
2133 
2134 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
2135                                                    const CapturedStmt *S) {
2136   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
2137   CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
2138   CGF.CapturedStmtInfo = &CapStmtInfo;
2139   auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
2140   Fn->addFnAttr(llvm::Attribute::NoInline);
2141   return Fn;
2142 }
2143 
2144 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
2145   if (!S.getAssociatedStmt())
2146     return;
2147   OMPLexicalScope Scope(*this, S);
2148   auto *C = S.getSingleClause<OMPSIMDClause>();
2149   auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF) {
2150     if (C) {
2151       auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2152       llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2153       CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
2154       auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
2155       CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
2156     } else {
2157       CGF.EmitStmt(
2158           cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
2159     }
2160   };
2161   CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
2162 }
2163 
2164 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
2165                                          QualType SrcType, QualType DestType,
2166                                          SourceLocation Loc) {
2167   assert(CGF.hasScalarEvaluationKind(DestType) &&
2168          "DestType must have scalar evaluation kind.");
2169   assert(!Val.isAggregate() && "Must be a scalar or complex.");
2170   return Val.isScalar()
2171              ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
2172                                         Loc)
2173              : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
2174                                                  DestType, Loc);
2175 }
2176 
2177 static CodeGenFunction::ComplexPairTy
2178 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
2179                       QualType DestType, SourceLocation Loc) {
2180   assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
2181          "DestType must have complex evaluation kind.");
2182   CodeGenFunction::ComplexPairTy ComplexVal;
2183   if (Val.isScalar()) {
2184     // Convert the input element to the element type of the complex.
2185     auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2186     auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
2187                                               DestElementType, Loc);
2188     ComplexVal = CodeGenFunction::ComplexPairTy(
2189         ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
2190   } else {
2191     assert(Val.isComplex() && "Must be a scalar or complex.");
2192     auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
2193     auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
2194     ComplexVal.first = CGF.EmitScalarConversion(
2195         Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
2196     ComplexVal.second = CGF.EmitScalarConversion(
2197         Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
2198   }
2199   return ComplexVal;
2200 }
2201 
2202 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
2203                                   LValue LVal, RValue RVal) {
2204   if (LVal.isGlobalReg()) {
2205     CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
2206   } else {
2207     CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
2208                                              : llvm::Monotonic,
2209                         LVal.isVolatile(), /*IsInit=*/false);
2210   }
2211 }
2212 
2213 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
2214                                          QualType RValTy, SourceLocation Loc) {
2215   switch (getEvaluationKind(LVal.getType())) {
2216   case TEK_Scalar:
2217     EmitStoreThroughLValue(RValue::get(convertToScalarValue(
2218                                *this, RVal, RValTy, LVal.getType(), Loc)),
2219                            LVal);
2220     break;
2221   case TEK_Complex:
2222     EmitStoreOfComplex(
2223         convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
2224         /*isInit=*/false);
2225     break;
2226   case TEK_Aggregate:
2227     llvm_unreachable("Must be a scalar or complex.");
2228   }
2229 }
2230 
2231 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
2232                                   const Expr *X, const Expr *V,
2233                                   SourceLocation Loc) {
2234   // v = x;
2235   assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
2236   assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
2237   LValue XLValue = CGF.EmitLValue(X);
2238   LValue VLValue = CGF.EmitLValue(V);
2239   RValue Res = XLValue.isGlobalReg()
2240                    ? CGF.EmitLoadOfLValue(XLValue, Loc)
2241                    : CGF.EmitAtomicLoad(XLValue, Loc,
2242                                         IsSeqCst ? llvm::SequentiallyConsistent
2243                                                  : llvm::Monotonic,
2244                                         XLValue.isVolatile());
2245   // OpenMP, 2.12.6, atomic Construct
2246   // Any atomic construct with a seq_cst clause forces the atomically
2247   // performed operation to include an implicit flush operation without a
2248   // list.
2249   if (IsSeqCst)
2250     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2251   CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
2252 }
2253 
2254 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
2255                                    const Expr *X, const Expr *E,
2256                                    SourceLocation Loc) {
2257   // x = expr;
2258   assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
2259   emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
2260   // OpenMP, 2.12.6, atomic Construct
2261   // Any atomic construct with a seq_cst clause forces the atomically
2262   // performed operation to include an implicit flush operation without a
2263   // list.
2264   if (IsSeqCst)
2265     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2266 }
2267 
2268 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
2269                                                 RValue Update,
2270                                                 BinaryOperatorKind BO,
2271                                                 llvm::AtomicOrdering AO,
2272                                                 bool IsXLHSInRHSPart) {
2273   auto &Context = CGF.CGM.getContext();
2274   // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
2275   // expression is simple and atomic is allowed for the given type for the
2276   // target platform.
2277   if (BO == BO_Comma || !Update.isScalar() ||
2278       !Update.getScalarVal()->getType()->isIntegerTy() ||
2279       !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
2280                         (Update.getScalarVal()->getType() !=
2281                          X.getAddress().getElementType())) ||
2282       !X.getAddress().getElementType()->isIntegerTy() ||
2283       !Context.getTargetInfo().hasBuiltinAtomic(
2284           Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
2285     return std::make_pair(false, RValue::get(nullptr));
2286 
2287   llvm::AtomicRMWInst::BinOp RMWOp;
2288   switch (BO) {
2289   case BO_Add:
2290     RMWOp = llvm::AtomicRMWInst::Add;
2291     break;
2292   case BO_Sub:
2293     if (!IsXLHSInRHSPart)
2294       return std::make_pair(false, RValue::get(nullptr));
2295     RMWOp = llvm::AtomicRMWInst::Sub;
2296     break;
2297   case BO_And:
2298     RMWOp = llvm::AtomicRMWInst::And;
2299     break;
2300   case BO_Or:
2301     RMWOp = llvm::AtomicRMWInst::Or;
2302     break;
2303   case BO_Xor:
2304     RMWOp = llvm::AtomicRMWInst::Xor;
2305     break;
2306   case BO_LT:
2307     RMWOp = X.getType()->hasSignedIntegerRepresentation()
2308                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
2309                                    : llvm::AtomicRMWInst::Max)
2310                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
2311                                    : llvm::AtomicRMWInst::UMax);
2312     break;
2313   case BO_GT:
2314     RMWOp = X.getType()->hasSignedIntegerRepresentation()
2315                 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
2316                                    : llvm::AtomicRMWInst::Min)
2317                 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
2318                                    : llvm::AtomicRMWInst::UMin);
2319     break;
2320   case BO_Assign:
2321     RMWOp = llvm::AtomicRMWInst::Xchg;
2322     break;
2323   case BO_Mul:
2324   case BO_Div:
2325   case BO_Rem:
2326   case BO_Shl:
2327   case BO_Shr:
2328   case BO_LAnd:
2329   case BO_LOr:
2330     return std::make_pair(false, RValue::get(nullptr));
2331   case BO_PtrMemD:
2332   case BO_PtrMemI:
2333   case BO_LE:
2334   case BO_GE:
2335   case BO_EQ:
2336   case BO_NE:
2337   case BO_AddAssign:
2338   case BO_SubAssign:
2339   case BO_AndAssign:
2340   case BO_OrAssign:
2341   case BO_XorAssign:
2342   case BO_MulAssign:
2343   case BO_DivAssign:
2344   case BO_RemAssign:
2345   case BO_ShlAssign:
2346   case BO_ShrAssign:
2347   case BO_Comma:
2348     llvm_unreachable("Unsupported atomic update operation");
2349   }
2350   auto *UpdateVal = Update.getScalarVal();
2351   if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
2352     UpdateVal = CGF.Builder.CreateIntCast(
2353         IC, X.getAddress().getElementType(),
2354         X.getType()->hasSignedIntegerRepresentation());
2355   }
2356   auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
2357   return std::make_pair(true, RValue::get(Res));
2358 }
2359 
2360 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
2361     LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2362     llvm::AtomicOrdering AO, SourceLocation Loc,
2363     const llvm::function_ref<RValue(RValue)> &CommonGen) {
2364   // Update expressions are allowed to have the following forms:
2365   // x binop= expr; -> xrval + expr;
2366   // x++, ++x -> xrval + 1;
2367   // x--, --x -> xrval - 1;
2368   // x = x binop expr; -> xrval binop expr
2369   // x = expr Op x; - > expr binop xrval;
2370   auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
2371   if (!Res.first) {
2372     if (X.isGlobalReg()) {
2373       // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
2374       // 'xrval'.
2375       EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
2376     } else {
2377       // Perform compare-and-swap procedure.
2378       EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
2379     }
2380   }
2381   return Res;
2382 }
2383 
2384 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
2385                                     const Expr *X, const Expr *E,
2386                                     const Expr *UE, bool IsXLHSInRHSPart,
2387                                     SourceLocation Loc) {
2388   assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2389          "Update expr in 'atomic update' must be a binary operator.");
2390   auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2391   // Update expressions are allowed to have the following forms:
2392   // x binop= expr; -> xrval + expr;
2393   // x++, ++x -> xrval + 1;
2394   // x--, --x -> xrval - 1;
2395   // x = x binop expr; -> xrval binop expr
2396   // x = expr Op x; - > expr binop xrval;
2397   assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
2398   LValue XLValue = CGF.EmitLValue(X);
2399   RValue ExprRValue = CGF.EmitAnyExpr(E);
2400   auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2401   auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2402   auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2403   auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2404   auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2405   auto Gen =
2406       [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
2407         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2408         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2409         return CGF.EmitAnyExpr(UE);
2410       };
2411   (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
2412       XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2413   // OpenMP, 2.12.6, atomic Construct
2414   // Any atomic construct with a seq_cst clause forces the atomically
2415   // performed operation to include an implicit flush operation without a
2416   // list.
2417   if (IsSeqCst)
2418     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2419 }
2420 
2421 static RValue convertToType(CodeGenFunction &CGF, RValue Value,
2422                             QualType SourceType, QualType ResType,
2423                             SourceLocation Loc) {
2424   switch (CGF.getEvaluationKind(ResType)) {
2425   case TEK_Scalar:
2426     return RValue::get(
2427         convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
2428   case TEK_Complex: {
2429     auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
2430     return RValue::getComplex(Res.first, Res.second);
2431   }
2432   case TEK_Aggregate:
2433     break;
2434   }
2435   llvm_unreachable("Must be a scalar or complex.");
2436 }
2437 
2438 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
2439                                      bool IsPostfixUpdate, const Expr *V,
2440                                      const Expr *X, const Expr *E,
2441                                      const Expr *UE, bool IsXLHSInRHSPart,
2442                                      SourceLocation Loc) {
2443   assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
2444   assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
2445   RValue NewVVal;
2446   LValue VLValue = CGF.EmitLValue(V);
2447   LValue XLValue = CGF.EmitLValue(X);
2448   RValue ExprRValue = CGF.EmitAnyExpr(E);
2449   auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
2450   QualType NewVValType;
2451   if (UE) {
2452     // 'x' is updated with some additional value.
2453     assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
2454            "Update expr in 'atomic capture' must be a binary operator.");
2455     auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
2456     // Update expressions are allowed to have the following forms:
2457     // x binop= expr; -> xrval + expr;
2458     // x++, ++x -> xrval + 1;
2459     // x--, --x -> xrval - 1;
2460     // x = x binop expr; -> xrval binop expr
2461     // x = expr Op x; - > expr binop xrval;
2462     auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
2463     auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
2464     auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
2465     NewVValType = XRValExpr->getType();
2466     auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
2467     auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
2468                   IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
2469       CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2470       CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
2471       RValue Res = CGF.EmitAnyExpr(UE);
2472       NewVVal = IsPostfixUpdate ? XRValue : Res;
2473       return Res;
2474     };
2475     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2476         XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
2477     if (Res.first) {
2478       // 'atomicrmw' instruction was generated.
2479       if (IsPostfixUpdate) {
2480         // Use old value from 'atomicrmw'.
2481         NewVVal = Res.second;
2482       } else {
2483         // 'atomicrmw' does not provide new value, so evaluate it using old
2484         // value of 'x'.
2485         CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
2486         CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
2487         NewVVal = CGF.EmitAnyExpr(UE);
2488       }
2489     }
2490   } else {
2491     // 'x' is simply rewritten with some 'expr'.
2492     NewVValType = X->getType().getNonReferenceType();
2493     ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
2494                                X->getType().getNonReferenceType(), Loc);
2495     auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
2496       NewVVal = XRValue;
2497       return ExprRValue;
2498     };
2499     // Try to perform atomicrmw xchg, otherwise simple exchange.
2500     auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
2501         XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
2502         Loc, Gen);
2503     if (Res.first) {
2504       // 'atomicrmw' instruction was generated.
2505       NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
2506     }
2507   }
2508   // Emit post-update store to 'v' of old/new 'x' value.
2509   CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
2510   // OpenMP, 2.12.6, atomic Construct
2511   // Any atomic construct with a seq_cst clause forces the atomically
2512   // performed operation to include an implicit flush operation without a
2513   // list.
2514   if (IsSeqCst)
2515     CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
2516 }
2517 
2518 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
2519                               bool IsSeqCst, bool IsPostfixUpdate,
2520                               const Expr *X, const Expr *V, const Expr *E,
2521                               const Expr *UE, bool IsXLHSInRHSPart,
2522                               SourceLocation Loc) {
2523   switch (Kind) {
2524   case OMPC_read:
2525     EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
2526     break;
2527   case OMPC_write:
2528     EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
2529     break;
2530   case OMPC_unknown:
2531   case OMPC_update:
2532     EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
2533     break;
2534   case OMPC_capture:
2535     EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
2536                              IsXLHSInRHSPart, Loc);
2537     break;
2538   case OMPC_if:
2539   case OMPC_final:
2540   case OMPC_num_threads:
2541   case OMPC_private:
2542   case OMPC_firstprivate:
2543   case OMPC_lastprivate:
2544   case OMPC_reduction:
2545   case OMPC_safelen:
2546   case OMPC_simdlen:
2547   case OMPC_collapse:
2548   case OMPC_default:
2549   case OMPC_seq_cst:
2550   case OMPC_shared:
2551   case OMPC_linear:
2552   case OMPC_aligned:
2553   case OMPC_copyin:
2554   case OMPC_copyprivate:
2555   case OMPC_flush:
2556   case OMPC_proc_bind:
2557   case OMPC_schedule:
2558   case OMPC_ordered:
2559   case OMPC_nowait:
2560   case OMPC_untied:
2561   case OMPC_threadprivate:
2562   case OMPC_depend:
2563   case OMPC_mergeable:
2564   case OMPC_device:
2565   case OMPC_threads:
2566   case OMPC_simd:
2567   case OMPC_map:
2568   case OMPC_num_teams:
2569   case OMPC_thread_limit:
2570   case OMPC_priority:
2571   case OMPC_grainsize:
2572   case OMPC_nogroup:
2573   case OMPC_num_tasks:
2574   case OMPC_hint:
2575   case OMPC_dist_schedule:
2576   case OMPC_defaultmap:
2577     llvm_unreachable("Clause is not allowed in 'omp atomic'.");
2578   }
2579 }
2580 
2581 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
2582   bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
2583   OpenMPClauseKind Kind = OMPC_unknown;
2584   for (auto *C : S.clauses()) {
2585     // Find first clause (skip seq_cst clause, if it is first).
2586     if (C->getClauseKind() != OMPC_seq_cst) {
2587       Kind = C->getClauseKind();
2588       break;
2589     }
2590   }
2591 
2592   const auto *CS =
2593       S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
2594   if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
2595     enterFullExpression(EWC);
2596   }
2597   // Processing for statements under 'atomic capture'.
2598   if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
2599     for (const auto *C : Compound->body()) {
2600       if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
2601         enterFullExpression(EWC);
2602       }
2603     }
2604   }
2605 
2606   OMPLexicalScope Scope(*this, S);
2607   auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF) {
2608     CGF.EmitStopPoint(CS);
2609     EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
2610                       S.getV(), S.getExpr(), S.getUpdateExpr(),
2611                       S.isXLHSInRHSPart(), S.getLocStart());
2612   };
2613   CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
2614 }
2615 
2616 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
2617   OMPLexicalScope Scope(*this, S);
2618   const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
2619 
2620   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
2621   GenerateOpenMPCapturedVars(CS, CapturedVars);
2622 
2623   llvm::Function *Fn = nullptr;
2624   llvm::Constant *FnID = nullptr;
2625 
2626   // Check if we have any if clause associated with the directive.
2627   const Expr *IfCond = nullptr;
2628 
2629   if (auto *C = S.getSingleClause<OMPIfClause>()) {
2630     IfCond = C->getCondition();
2631   }
2632 
2633   // Check if we have any device clause associated with the directive.
2634   const Expr *Device = nullptr;
2635   if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
2636     Device = C->getDevice();
2637   }
2638 
2639   // Check if we have an if clause whose conditional always evaluates to false
2640   // or if we do not have any targets specified. If so the target region is not
2641   // an offload entry point.
2642   bool IsOffloadEntry = true;
2643   if (IfCond) {
2644     bool Val;
2645     if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
2646       IsOffloadEntry = false;
2647   }
2648   if (CGM.getLangOpts().OMPTargetTriples.empty())
2649     IsOffloadEntry = false;
2650 
2651   assert(CurFuncDecl && "No parent declaration for target region!");
2652   StringRef ParentName;
2653   // In case we have Ctors/Dtors we use the complete type variant to produce
2654   // the mangling of the device outlined kernel.
2655   if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl))
2656     ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
2657   else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl))
2658     ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
2659   else
2660     ParentName =
2661         CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl)));
2662 
2663   CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
2664                                                     IsOffloadEntry);
2665 
2666   CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device,
2667                                         CapturedVars);
2668 }
2669 
2670 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
2671   llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
2672 }
2673 
2674 void CodeGenFunction::EmitOMPCancellationPointDirective(
2675     const OMPCancellationPointDirective &S) {
2676   CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
2677                                                    S.getCancelRegion());
2678 }
2679 
2680 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
2681   const Expr *IfCond = nullptr;
2682   for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
2683     if (C->getNameModifier() == OMPD_unknown ||
2684         C->getNameModifier() == OMPD_cancel) {
2685       IfCond = C->getCondition();
2686       break;
2687     }
2688   }
2689   CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
2690                                         S.getCancelRegion());
2691 }
2692 
2693 CodeGenFunction::JumpDest
2694 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
2695   if (Kind == OMPD_parallel || Kind == OMPD_task)
2696     return ReturnBlock;
2697   assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
2698          Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for);
2699   return BreakContinueStack.back().BreakBlock;
2700 }
2701 
2702 // Generate the instructions for '#pragma omp target data' directive.
2703 void CodeGenFunction::EmitOMPTargetDataDirective(
2704     const OMPTargetDataDirective &S) {
2705   // emit the code inside the construct for now
2706   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2707   CGM.getOpenMPRuntime().emitInlinedDirective(
2708       *this, OMPD_target_data,
2709       [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2710 }
2711 
2712 void CodeGenFunction::EmitOMPTargetEnterDataDirective(
2713     const OMPTargetEnterDataDirective &S) {
2714   // TODO: codegen for target enter data.
2715 }
2716 
2717 void CodeGenFunction::EmitOMPTargetExitDataDirective(
2718     const OMPTargetExitDataDirective &S) {
2719   // TODO: codegen for target exit data.
2720 }
2721 
2722 void CodeGenFunction::EmitOMPTargetParallelDirective(
2723     const OMPTargetParallelDirective &S) {
2724   // TODO: codegen for target parallel.
2725 }
2726 
2727 void CodeGenFunction::EmitOMPTargetParallelForDirective(
2728     const OMPTargetParallelForDirective &S) {
2729   // TODO: codegen for target parallel for.
2730 }
2731 
2732 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
2733   // emit the code inside the construct for now
2734   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2735   CGM.getOpenMPRuntime().emitInlinedDirective(
2736       *this, OMPD_taskloop,
2737       [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2738 }
2739 
2740 void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
2741     const OMPTaskLoopSimdDirective &S) {
2742   // emit the code inside the construct for now
2743   auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
2744   CGM.getOpenMPRuntime().emitInlinedDirective(
2745       *this, OMPD_taskloop_simd,
2746       [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); });
2747 }
2748 
2749