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