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