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