blob: f04a29392cfc396cb94e945097dd59af4b0ba9ce [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit OpenMP nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "clang/AST/Stmt.h"
19#include "clang/AST/StmtOpenMP.h"
20using namespace clang;
21using namespace CodeGen;
22
23//===----------------------------------------------------------------------===//
24// OpenMP Directive Emission
25//===----------------------------------------------------------------------===//
Alexey Bataev420d45b2015-04-14 05:11:24 +000026void CodeGenFunction::EmitOMPAggregateAssign(
27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) {
29 // Perform element-by-element initialization.
30 QualType ElementTy;
31 auto SrcBegin = SrcAddr;
32 auto DestBegin = DestAddr;
33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin);
35 // Cast from pointer to array type to pointer to single element.
36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin,
37 DestBegin->getType());
38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
39 // The basic structure here is a while-do loop.
40 auto BodyBB = createBasicBlock("omp.arraycpy.body");
41 auto DoneBB = createBasicBlock("omp.arraycpy.done");
42 auto IsEmpty =
43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000045
Alexey Bataev420d45b2015-04-14 05:11:24 +000046 // Enter the loop body, making that address the current address.
47 auto EntryBB = Builder.GetInsertBlock();
48 EmitBlock(BodyBB);
49 auto SrcElementCurrent =
50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB);
52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2,
53 "omp.arraycpy.destElementPast");
54 DestElementCurrent->addIncoming(DestBegin, EntryBB);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000055
Alexey Bataev420d45b2015-04-14 05:11:24 +000056 // Emit copy.
57 CopyGen(DestElementCurrent, SrcElementCurrent);
58
59 // Shift the address forward by one element.
60 auto DestElementNext = Builder.CreateConstGEP1_32(
61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element");
62 auto SrcElementNext = Builder.CreateConstGEP1_32(
63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element");
64 // Check whether we've reached the end.
65 auto Done =
66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
67 Builder.CreateCondBr(Done, DoneBB, BodyBB);
68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock());
69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock());
70
71 // Done.
72 EmitBlock(DoneBB, /*IsFinished=*/true);
73}
74
75void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF,
76 QualType OriginalType, llvm::Value *DestAddr,
77 llvm::Value *SrcAddr, const VarDecl *DestVD,
78 const VarDecl *SrcVD, const Expr *Copy) {
79 if (OriginalType->isArrayType()) {
80 auto *BO = dyn_cast<BinaryOperator>(Copy);
81 if (BO && BO->getOpcode() == BO_Assign) {
82 // Perform simple memcpy for simple copying.
83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
84 } else {
85 // For arrays with complex element types perform element by element
86 // copying.
87 CGF.EmitOMPAggregateAssign(
88 DestAddr, SrcAddr, OriginalType,
89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement,
90 llvm::Value *SrcElement) {
91 // Working with the single array element, so have to remap
92 // destination and source variables to corresponding array
93 // elements.
94 CodeGenFunction::OMPPrivateScope Remap(CGF);
95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{
96 return DestElement;
97 });
98 Remap.addPrivate(
99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; });
100 (void)Remap.Privatize();
101 CGF.EmitIgnoredExpr(Copy);
102 });
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000103 }
Alexey Bataev420d45b2015-04-14 05:11:24 +0000104 } else {
105 // Remap pseudo source variable to private copy.
106 CodeGenFunction::OMPPrivateScope Remap(CGF);
107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; });
108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; });
109 (void)Remap.Privatize();
110 // Emit copying of the whole variable.
111 CGF.EmitIgnoredExpr(Copy);
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000112 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000113}
114
Alexey Bataev69c62a92015-04-15 04:52:20 +0000115bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
116 OMPPrivateScope &PrivateScope) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) {
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000119 auto *C = cast<OMPFirstprivateClause>(*I);
120 auto IRef = C->varlist_begin();
121 auto InitsRef = C->inits().begin();
122 for (auto IInit : C->private_copies()) {
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev69c62a92015-04-15 04:52:20 +0000124 if (EmittedAsFirstprivate.count(OrigVD) == 0) {
125 EmittedAsFirstprivate.insert(OrigVD);
126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
128 bool IsRegistered;
129 DeclRefExpr DRE(
130 const_cast<VarDecl *>(OrigVD),
131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
132 OrigVD) != nullptr,
133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
134 auto *OriginalAddr = EmitLValue(&DRE).getAddress();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000135 QualType Type = OrigVD->getType();
136 if (auto *PVD = dyn_cast<ParmVarDecl>(OrigVD)) {
137 Type = PVD->getOriginalType();
138 }
139 if (Type->isArrayType()) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000140 // Emit VarDecl with copy init for arrays.
141 // Get the address of the original variable captured in current
142 // captured region.
143 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
144 auto Emission = EmitAutoVarAlloca(*VD);
145 auto *Init = VD->getInit();
146 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
147 // Perform simple memcpy.
148 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000149 Type);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000150 } else {
151 EmitOMPAggregateAssign(
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000152 Emission.getAllocatedAddress(), OriginalAddr, Type,
Alexey Bataev69c62a92015-04-15 04:52:20 +0000153 [this, VDInit, Init](llvm::Value *DestElement,
154 llvm::Value *SrcElement) {
155 // Clean up any temporaries needed by the initialization.
156 RunCleanupsScope InitScope(*this);
157 // Emit initialization for single element.
158 LocalDeclMap[VDInit] = SrcElement;
159 EmitAnyExprToMem(Init, DestElement,
160 Init->getType().getQualifiers(),
161 /*IsInitializer*/ false);
162 LocalDeclMap.erase(VDInit);
163 });
164 }
165 EmitAutoVarCleanups(Emission);
166 return Emission.getAllocatedAddress();
167 });
168 } else {
169 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
170 // Emit private VarDecl with copy init.
171 // Remap temp VDInit variable to the address of the original
172 // variable
173 // (for proper handling of captured global variables).
174 LocalDeclMap[VDInit] = OriginalAddr;
175 EmitDecl(*VD);
176 LocalDeclMap.erase(VDInit);
177 return GetAddrOfLocalVar(VD);
178 });
179 }
180 assert(IsRegistered &&
181 "firstprivate var already registered as private");
182 // Silence the warning about unused variable.
183 (void)IsRegistered;
184 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000185 ++IRef, ++InitsRef;
186 }
187 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000188 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000189}
190
Alexey Bataev03b340a2014-10-21 03:16:40 +0000191void CodeGenFunction::EmitOMPPrivateClause(
192 const OMPExecutableDirective &D,
193 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000194 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000195 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000196 auto *C = cast<OMPPrivateClause>(*I);
197 auto IRef = C->varlist_begin();
198 for (auto IInit : C->private_copies()) {
199 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000200 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
201 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
202 bool IsRegistered =
203 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
204 // Emit private VarDecl with copy init.
205 EmitDecl(*VD);
206 return GetAddrOfLocalVar(VD);
207 });
208 assert(IsRegistered && "private var already registered as private");
209 // Silence the warning about unused variable.
210 (void)IsRegistered;
211 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000212 ++IRef;
213 }
214 }
215}
216
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000217bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
218 // threadprivate_var1 = master_threadprivate_var1;
219 // operator=(threadprivate_var2, master_threadprivate_var2);
220 // ...
221 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 llvm::DenseSet<const VarDecl *> CopiedVars;
223 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000224 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000225 auto *C = cast<OMPCopyinClause>(*I);
226 auto IRef = C->varlist_begin();
227 auto ISrcRef = C->source_exprs().begin();
228 auto IDestRef = C->destination_exprs().begin();
229 for (auto *AssignOp : C->assignment_ops()) {
230 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000231 QualType Type = VD->getType();
232 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
233 Type = PVD->getOriginalType();
234 }
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000235 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
236 // Get the address of the master variable.
237 auto *MasterAddr = VD->isStaticLocal()
238 ? CGM.getStaticLocalDeclAddress(VD)
239 : CGM.GetAddrOfGlobal(VD);
240 // Get the address of the threadprivate variable.
241 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
242 if (CopiedVars.size() == 1) {
243 // At first check if current thread is a master thread. If it is, no
244 // need to copy data.
245 CopyBegin = createBasicBlock("copyin.not.master");
246 CopyEnd = createBasicBlock("copyin.not.master.end");
247 Builder.CreateCondBr(
248 Builder.CreateICmpNE(
249 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
250 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
251 CopyBegin, CopyEnd);
252 EmitBlock(CopyBegin);
253 }
254 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
255 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000256 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD,
257 AssignOp);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000258 }
259 ++IRef;
260 ++ISrcRef;
261 ++IDestRef;
262 }
263 }
264 if (CopyEnd) {
265 // Exit out of copying procedure for non-master thread.
266 EmitBlock(CopyEnd, /*IsFinished=*/true);
267 return true;
268 }
269 return false;
270}
271
Alexey Bataev38e89532015-04-16 04:54:05 +0000272bool CodeGenFunction::EmitOMPLastprivateClauseInit(
273 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000274 bool HasAtLeastOneLastprivate = false;
275 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000276 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataevd130fd12015-05-13 10:23:02 +0000277 HasAtLeastOneLastprivate = true;
Alexey Bataev38e89532015-04-16 04:54:05 +0000278 auto *C = cast<OMPLastprivateClause>(*I);
279 auto IRef = C->varlist_begin();
280 auto IDestRef = C->destination_exprs().begin();
281 for (auto *IInit : C->private_copies()) {
282 // Keep the address of the original variable for future update at the end
283 // of the loop.
284 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
285 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
286 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
287 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
288 DeclRefExpr DRE(
289 const_cast<VarDecl *>(OrigVD),
290 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
291 OrigVD) != nullptr,
292 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
293 return EmitLValue(&DRE).getAddress();
294 });
295 // Check if the variable is also a firstprivate: in this case IInit is
296 // not generated. Initialization of this variable will happen in codegen
297 // for 'firstprivate' clause.
Alexey Bataevd130fd12015-05-13 10:23:02 +0000298 if (IInit) {
299 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
300 bool IsRegistered =
301 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
302 // Emit private VarDecl with copy init.
303 EmitDecl(*VD);
304 return GetAddrOfLocalVar(VD);
305 });
306 assert(IsRegistered &&
307 "lastprivate var already registered as private");
308 (void)IsRegistered;
309 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000310 }
311 ++IRef, ++IDestRef;
312 }
313 }
314 return HasAtLeastOneLastprivate;
315}
316
317void CodeGenFunction::EmitOMPLastprivateClauseFinal(
318 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
319 // Emit following code:
320 // if (<IsLastIterCond>) {
321 // orig_var1 = private_orig_var1;
322 // ...
323 // orig_varn = private_orig_varn;
324 // }
325 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
326 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
327 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
328 EmitBlock(ThenBB);
329 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000330 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000331 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000332 auto *C = cast<OMPLastprivateClause>(*I);
333 auto IRef = C->varlist_begin();
334 auto ISrcRef = C->source_exprs().begin();
335 auto IDestRef = C->destination_exprs().begin();
336 for (auto *AssignOp : C->assignment_ops()) {
337 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000338 QualType Type = PrivateVD->getType();
339 if (auto *PVD = dyn_cast<ParmVarDecl>(PrivateVD)) {
340 Type = PVD->getOriginalType();
341 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000342 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
343 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
344 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
345 // Get the address of the original variable.
346 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
347 // Get the address of the private variable.
348 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +0000349 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD,
350 AssignOp);
Alexey Bataev38e89532015-04-16 04:54:05 +0000351 }
352 ++IRef;
353 ++ISrcRef;
354 ++IDestRef;
355 }
356 }
357 }
358 EmitBlock(DoneBB, /*IsFinished=*/true);
359}
360
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000361void CodeGenFunction::EmitOMPReductionClauseInit(
362 const OMPExecutableDirective &D,
363 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000364 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000365 auto *C = cast<OMPReductionClause>(*I);
366 auto ILHS = C->lhs_exprs().begin();
367 auto IRHS = C->rhs_exprs().begin();
368 for (auto IRef : C->varlists()) {
369 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
370 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
371 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
372 // Store the address of the original variable associated with the LHS
373 // implicit variable.
374 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
375 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
376 CapturedStmtInfo->lookup(OrigVD) != nullptr,
377 IRef->getType(), VK_LValue, IRef->getExprLoc());
378 return EmitLValue(&DRE).getAddress();
379 });
380 // Emit reduction copy.
381 bool IsRegistered =
382 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
383 // Emit private VarDecl with reduction init.
384 EmitDecl(*PrivateVD);
385 return GetAddrOfLocalVar(PrivateVD);
386 });
387 assert(IsRegistered && "private var already registered as private");
388 // Silence the warning about unused variable.
389 (void)IsRegistered;
390 ++ILHS, ++IRHS;
391 }
392 }
393}
394
395void CodeGenFunction::EmitOMPReductionClauseFinal(
396 const OMPExecutableDirective &D) {
397 llvm::SmallVector<const Expr *, 8> LHSExprs;
398 llvm::SmallVector<const Expr *, 8> RHSExprs;
399 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000400 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000401 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000402 HasAtLeastOneReduction = true;
403 auto *C = cast<OMPReductionClause>(*I);
404 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
405 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
406 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
407 }
408 if (HasAtLeastOneReduction) {
409 // Emit nowait reduction if nowait clause is present or directive is a
410 // parallel directive (it always has implicit barrier).
411 CGM.getOpenMPRuntime().emitReduction(
412 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
413 D.getSingleClause(OMPC_nowait) ||
414 isOpenMPParallelDirective(D.getDirectiveKind()));
415 }
416}
417
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
419 const OMPExecutableDirective &S,
420 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000421 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000422 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
423 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
424 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000425 if (auto C = S.getSingleClause(OMPC_num_threads)) {
426 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
427 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
428 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
429 /*IgnoreResultAssign*/ true);
430 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
431 CGF, NumThreads, NumThreadsClause->getLocStart());
432 }
433 const Expr *IfCond = nullptr;
434 if (auto C = S.getSingleClause(OMPC_if)) {
435 IfCond = cast<OMPIfClause>(C)->getCondition();
436 }
437 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
438 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000439}
440
441void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
442 LexicalScope Scope(*this, S.getSourceRange());
443 // Emit parallel region as a standalone region.
444 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
445 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000446 bool Copyins = CGF.EmitOMPCopyinClause(S);
447 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
448 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000449 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000450 // initialization of firstprivate variables or propagation master's thread
451 // values of threadprivate variables to local instances of that variables
452 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000453 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
454 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000455 }
456 CGF.EmitOMPPrivateClause(S, PrivateScope);
457 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
458 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000459 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000460 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000461 // Emit implicit barrier at the end of the 'parallel' directive.
462 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
463 OMPD_unknown);
464 };
465 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000466}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000467
Alexander Musmand196ef22014-10-07 08:57:09 +0000468void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000469 bool SeparateIter) {
470 RunCleanupsScope BodyScope(*this);
471 // Update counters values on current iteration.
472 for (auto I : S.updates()) {
473 EmitIgnoredExpr(I);
474 }
Alexander Musman3276a272015-03-21 10:12:56 +0000475 // Update the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000476 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
477 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000478 for (auto U : C->updates()) {
479 EmitIgnoredExpr(U);
480 }
481 }
482
Alexander Musmana5f070a2014-10-01 06:03:56 +0000483 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000484 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000485 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
486 // Emit loop body.
487 EmitStmt(S.getBody());
488 // The end (updates/cleanups).
489 EmitBlock(Continue.getBlock());
490 BreakContinueStack.pop_back();
491 if (SeparateIter) {
492 // TODO: Update lastprivates if the SeparateIter flag is true.
493 // This will be implemented in a follow-up OMPLastprivateClause patch, but
494 // result should be still correct without it, as we do not make these
495 // variables private yet.
496 }
497}
498
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000499void CodeGenFunction::EmitOMPInnerLoop(
500 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
501 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000502 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
503 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000504 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000505
506 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000507 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000508 EmitBlock(CondBlock);
509 LoopStack.push(CondBlock);
510
511 // If there are any cleanups between here and the loop-exit scope,
512 // create a block to stage a loop exit along.
513 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000514 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000515 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000516
Alexander Musmand196ef22014-10-07 08:57:09 +0000517 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518
Alexey Bataev2df54a02015-03-12 08:53:29 +0000519 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000520 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521 if (ExitBlock != LoopExit.getBlock()) {
522 EmitBlock(ExitBlock);
523 EmitBranchThroughCleanup(LoopExit);
524 }
525
526 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000527 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000528
529 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000530 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000531 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
532
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000533 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000534
535 // Emit "IV = IV + 1" and a back-edge to the condition block.
536 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000537 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000538 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000539 BreakContinueStack.pop_back();
540 EmitBranch(CondBlock);
541 LoopStack.pop();
542 // Emit the fall-through block.
543 EmitBlock(LoopExit.getBlock());
544}
545
546void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
547 auto IC = S.counters().begin();
548 for (auto F : S.finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000549 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
550 if (LocalDeclMap.lookup(OrigVD)) {
551 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
552 CapturedStmtInfo->lookup(OrigVD) != nullptr,
553 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
554 auto *OrigAddr = EmitLValue(&DRE).getAddress();
555 OMPPrivateScope VarScope(*this);
556 VarScope.addPrivate(OrigVD,
557 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
558 (void)VarScope.Privatize();
Alexander Musmana5f070a2014-10-01 06:03:56 +0000559 EmitIgnoredExpr(F);
560 }
561 ++IC;
562 }
Alexander Musman3276a272015-03-21 10:12:56 +0000563 // Emit the final values of the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000564 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
565 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000566 auto IC = C->varlist_begin();
Alexander Musman3276a272015-03-21 10:12:56 +0000567 for (auto F : C->finals()) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000568 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
569 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
570 CapturedStmtInfo->lookup(OrigVD) != nullptr,
571 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
572 auto *OrigAddr = EmitLValue(&DRE).getAddress();
573 OMPPrivateScope VarScope(*this);
574 VarScope.addPrivate(OrigVD,
575 [OrigAddr]() -> llvm::Value *{ return OrigAddr; });
576 (void)VarScope.Privatize();
Alexander Musman3276a272015-03-21 10:12:56 +0000577 EmitIgnoredExpr(F);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000578 ++IC;
Alexander Musman3276a272015-03-21 10:12:56 +0000579 }
580 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000581}
582
Alexander Musman09184fe2014-09-30 05:29:28 +0000583static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
584 const OMPAlignedClause &Clause) {
585 unsigned ClauseAlignment = 0;
586 if (auto AlignmentExpr = Clause.getAlignment()) {
587 auto AlignmentCI =
588 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
589 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
590 }
591 for (auto E : Clause.varlists()) {
592 unsigned Alignment = ClauseAlignment;
593 if (Alignment == 0) {
594 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000595 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000596 // alignments for SIMD instructions on the target platforms are assumed.
597 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
598 E->getType());
599 }
600 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
601 "alignment is not power of 2");
602 if (Alignment != 0) {
603 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
604 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
605 }
606 }
607}
608
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000609static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
610 CodeGenFunction::OMPPrivateScope &LoopScope,
611 ArrayRef<Expr *> Counters) {
612 for (auto *E : Counters) {
613 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev61114692015-04-28 13:20:05 +0000614 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000615 // Emit var without initialization.
616 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
617 CGF.EmitAutoVarCleanups(VarEmission);
618 return VarEmission.getAllocatedAddress();
619 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000620 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000621}
622
Alexey Bataev62dbb972015-04-22 11:59:37 +0000623static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
624 const Expr *Cond, llvm::BasicBlock *TrueBlock,
625 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
626 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
627 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
628 const VarDecl *IVDecl =
629 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
630 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
631 // Emit var without initialization.
632 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
633 CGF.EmitAutoVarCleanups(VarEmission);
634 return VarEmission.getAllocatedAddress();
635 });
636 assert(IsRegistered && "counter already registered as private");
637 // Silence the warning about unused variable.
638 (void)IsRegistered;
639 (void)PreCondScope.Privatize();
640 // Initialize internal counter to 0 to calculate initial values of real
641 // counters.
642 LValue IV = CGF.EmitLValue(S.getIterationVariable());
643 CGF.EmitStoreOfScalar(
644 llvm::ConstantInt::getNullValue(
645 IV.getAddress()->getType()->getPointerElementType()),
646 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
647 // Get initial values of real counters.
648 for (auto I : S.updates()) {
649 CGF.EmitIgnoredExpr(I);
650 }
651 // Check that loop is executed at least one time.
652 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
653}
654
Alexander Musman3276a272015-03-21 10:12:56 +0000655static void
656EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
657 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000658 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
659 auto *C = cast<OMPLinearClause>(*I);
660 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000661 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
662 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
663 // Emit var without initialization.
664 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
665 CGF.EmitAutoVarCleanups(VarEmission);
666 return VarEmission.getAllocatedAddress();
667 });
668 assert(IsRegistered && "linear var already registered as private");
669 // Silence the warning about unused variable.
670 (void)IsRegistered;
671 }
672 }
673}
674
Alexander Musman515ad8c2014-05-22 08:54:05 +0000675void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000676 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
677 // Pragma 'simd' code depends on presence of 'lastprivate'.
678 // If present, we have to separate last iteration of the loop:
679 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000680 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000681 // for (IV in 0..LastIteration-1) BODY;
682 // BODY with updates of lastprivate vars;
683 // <Final counter/linear vars updates>;
684 // }
685 //
686 // otherwise (when there's no lastprivate):
687 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000688 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000689 // for (IV in 0..LastIteration) BODY;
690 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000691 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000692 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000693
Alexey Bataev62dbb972015-04-22 11:59:37 +0000694 // Emit: if (PreCond) - begin.
695 // If the condition constant folds and can be elided, avoid emitting the
696 // whole loop.
697 bool CondConstant;
698 llvm::BasicBlock *ContBlock = nullptr;
699 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
700 if (!CondConstant)
701 return;
702 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000703 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
704 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000705 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
706 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000707 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000708 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000709 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000710 // Walk clauses and process safelen/lastprivate.
711 bool SeparateIter = false;
712 CGF.LoopStack.setParallel();
713 CGF.LoopStack.setVectorizerEnable(true);
714 for (auto C : S.clauses()) {
715 switch (C->getClauseKind()) {
716 case OMPC_safelen: {
717 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
718 AggValueSlot::ignored(), true);
719 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
720 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
721 // In presence of finite 'safelen', it may be unsafe to mark all
722 // the memory instructions parallel, because loop-carried
723 // dependences of 'safelen' iterations are possible.
724 CGF.LoopStack.setParallel(false);
725 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000726 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000727 case OMPC_aligned:
728 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
729 break;
730 case OMPC_lastprivate:
731 SeparateIter = true;
732 break;
733 default:
734 // Not handled yet
735 ;
736 }
737 }
Alexander Musman3276a272015-03-21 10:12:56 +0000738
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000739 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000740 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
741 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000742 for (auto Init : C->inits()) {
743 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
744 CGF.EmitVarDecl(*D);
745 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000746 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000747
748 // Emit the loop iteration variable.
749 const Expr *IVExpr = S.getIterationVariable();
750 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
751 CGF.EmitVarDecl(*IVDecl);
752 CGF.EmitIgnoredExpr(S.getInit());
753
754 // Emit the iterations count variable.
755 // If it is not a variable, Sema decided to calculate iterations count on
756 // each
757 // iteration (e.g., it is foldable into a constant).
758 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
759 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
760 // Emit calculation of the iterations count.
761 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000762 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000763
764 // Emit the linear steps for the linear clauses.
765 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000766 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
767 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000768 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
769 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
770 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
771 // Emit calculation of the linear step.
772 CGF.EmitIgnoredExpr(CS);
773 }
774 }
775
Alexey Bataev62dbb972015-04-22 11:59:37 +0000776 {
777 OMPPrivateScope LoopScope(CGF);
778 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
779 EmitPrivateLinearVars(CGF, S, LoopScope);
780 CGF.EmitOMPPrivateClause(S, LoopScope);
781 (void)LoopScope.Privatize();
782 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
783 S.getCond(SeparateIter), S.getInc(),
784 [&S](CodeGenFunction &CGF) {
785 CGF.EmitOMPLoopBody(S);
786 CGF.EmitStopPoint(&S);
787 },
788 [](CodeGenFunction &) {});
789 if (SeparateIter) {
790 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000791 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000792 }
793 CGF.EmitOMPSimdFinal(S);
794 // Emit: if (PreCond) - end.
795 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000796 CGF.EmitBranch(ContBlock);
797 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000798 }
799 };
800 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000801}
802
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000803void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
804 const OMPLoopDirective &S,
805 OMPPrivateScope &LoopScope,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000806 bool Ordered, llvm::Value *LB,
807 llvm::Value *UB, llvm::Value *ST,
808 llvm::Value *IL, llvm::Value *Chunk) {
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000809 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000810
811 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000812 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000813
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000814 assert((Ordered ||
815 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) &&
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000816 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000817
818 // Emit outer loop.
819 //
820 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000821 // When schedule(dynamic,chunk_size) is specified, the iterations are
822 // distributed to threads in the team in chunks as the threads request them.
823 // Each thread executes a chunk of iterations, then requests another chunk,
824 // until no chunks remain to be distributed. Each chunk contains chunk_size
825 // iterations, except for the last chunk to be distributed, which may have
826 // fewer iterations. When no chunk_size is specified, it defaults to 1.
827 //
828 // When schedule(guided,chunk_size) is specified, the iterations are assigned
829 // to threads in the team in chunks as the executing threads request them.
830 // Each thread executes a chunk of iterations, then requests another chunk,
831 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
832 // each chunk is proportional to the number of unassigned iterations divided
833 // by the number of threads in the team, decreasing to 1. For a chunk_size
834 // with value k (greater than 1), the size of each chunk is determined in the
835 // same way, with the restriction that the chunks do not contain fewer than k
836 // iterations (except for the last chunk to be assigned, which may have fewer
837 // than k iterations).
838 //
839 // When schedule(auto) is specified, the decision regarding scheduling is
840 // delegated to the compiler and/or runtime system. The programmer gives the
841 // implementation the freedom to choose any possible mapping of iterations to
842 // threads in the team.
843 //
844 // When schedule(runtime) is specified, the decision regarding scheduling is
845 // deferred until run time, and the schedule and chunk size are taken from the
846 // run-sched-var ICV. If the ICV is set to auto, the schedule is
847 // implementation defined
848 //
849 // while(__kmpc_dispatch_next(&LB, &UB)) {
850 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000851 // while (idx <= UB) { BODY; ++idx;
852 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
853 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000854 // }
855 //
856 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000857 // When schedule(static, chunk_size) is specified, iterations are divided into
858 // chunks of size chunk_size, and the chunks are assigned to the threads in
859 // the team in a round-robin fashion in the order of the thread number.
860 //
861 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
862 // while (idx <= UB) { BODY; ++idx; } // inner loop
863 // LB = LB + ST;
864 // UB = UB + ST;
865 // }
866 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000867
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000868 const Expr *IVExpr = S.getIterationVariable();
869 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
870 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
871
Alexander Musman92bdaab2015-03-12 13:37:50 +0000872 RT.emitForInit(
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000873 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB,
874 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal()
875 : UB),
876 ST, Chunk);
Alexander Musman92bdaab2015-03-12 13:37:50 +0000877
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000878 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
879
880 // Start the loop with a block that tests the condition.
881 auto CondBlock = createBasicBlock("omp.dispatch.cond");
882 EmitBlock(CondBlock);
883 LoopStack.push(CondBlock);
884
885 llvm::Value *BoolCondVal = nullptr;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000886 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000887 // UB = min(UB, GlobalUB)
888 EmitIgnoredExpr(S.getEnsureUpperBound());
889 // IV = LB
890 EmitIgnoredExpr(S.getInit());
891 // IV < UB
892 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
893 } else {
894 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
895 IL, LB, UB, ST);
896 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000897
898 // If there are any cleanups between here and the loop-exit scope,
899 // create a block to stage a loop exit along.
900 auto ExitBlock = LoopExit.getBlock();
901 if (LoopScope.requiresCleanups())
902 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
903
904 auto LoopBody = createBasicBlock("omp.dispatch.body");
905 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
906 if (ExitBlock != LoopExit.getBlock()) {
907 EmitBlock(ExitBlock);
908 EmitBranchThroughCleanup(LoopExit);
909 }
910 EmitBlock(LoopBody);
911
Alexander Musman92bdaab2015-03-12 13:37:50 +0000912 // Emit "IV = LB" (in case of static schedule, we have already calculated new
913 // LB for loop condition and emitted it above).
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000914 if (DynamicOrOrdered)
Alexander Musman92bdaab2015-03-12 13:37:50 +0000915 EmitIgnoredExpr(S.getInit());
916
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000917 // Create a block for the increment.
918 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
919 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
920
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000921 SourceLocation Loc = S.getLocStart();
Alexey Bataev53223c92015-05-07 04:25:17 +0000922 // Generate !llvm.loop.parallel metadata for loads and stores for loops with
923 // dynamic/guided scheduling and without ordered clause.
924 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic ||
925 ScheduleKind == OMPC_SCHEDULE_guided) &&
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000926 !Ordered);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000927 EmitOMPInnerLoop(
928 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
929 S.getInc(),
930 [&S](CodeGenFunction &CGF) {
931 CGF.EmitOMPLoopBody(S);
932 CGF.EmitStopPoint(&S);
933 },
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000934 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
935 if (Ordered) {
936 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000937 CGF, Loc, IVSize, IVSigned);
938 }
939 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000940
941 EmitBlock(Continue.getBlock());
942 BreakContinueStack.pop_back();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000943 if (!DynamicOrOrdered) {
Alexander Musman92bdaab2015-03-12 13:37:50 +0000944 // Emit "LB = LB + Stride", "UB = UB + Stride".
945 EmitIgnoredExpr(S.getNextLowerBound());
946 EmitIgnoredExpr(S.getNextUpperBound());
947 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000948
949 EmitBranch(CondBlock);
950 LoopStack.pop();
951 // Emit the fall-through block.
952 EmitBlock(LoopExit.getBlock());
953
954 // Tell the runtime we are done.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +0000955 if (!DynamicOrOrdered)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000956 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000957}
958
Alexander Musmanc6388682014-12-15 07:07:06 +0000959/// \brief Emit a helper variable and return corresponding lvalue.
960static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
961 const DeclRefExpr *Helper) {
962 auto VDecl = cast<VarDecl>(Helper->getDecl());
963 CGF.EmitVarDecl(*VDecl);
964 return CGF.EmitLValue(Helper);
965}
966
Alexey Bataev040d5402015-05-12 08:35:28 +0000967static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind>
968emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S,
969 bool OuterRegion) {
970 // Detect the loop schedule kind and chunk.
971 auto ScheduleKind = OMPC_SCHEDULE_unknown;
972 llvm::Value *Chunk = nullptr;
973 if (auto *C =
974 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) {
975 ScheduleKind = C->getScheduleKind();
976 if (const auto *Ch = C->getChunkSize()) {
977 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) {
978 if (OuterRegion) {
979 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl());
980 CGF.EmitVarDecl(*ImpVar);
981 CGF.EmitStoreThroughLValue(
982 CGF.EmitAnyExpr(Ch),
983 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar),
984 ImpVar->getType()));
985 } else {
986 Ch = ImpRef;
987 }
988 }
989 if (!C->getHelperChunkSize() || !OuterRegion) {
990 Chunk = CGF.EmitScalarExpr(Ch);
991 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(),
992 S.getIterationVariable()->getType());
993 }
994 }
995 }
996 return std::make_pair(Chunk, ScheduleKind);
997}
998
Alexey Bataev38e89532015-04-16 04:54:05 +0000999bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001000 // Emit the loop iteration variable.
1001 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
1002 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
1003 EmitVarDecl(*IVDecl);
1004
1005 // Emit the iterations count variable.
1006 // If it is not a variable, Sema decided to calculate iterations count on each
1007 // iteration (e.g., it is foldable into a constant).
1008 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
1009 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
1010 // Emit calculation of the iterations count.
1011 EmitIgnoredExpr(S.getCalcLastIteration());
1012 }
1013
1014 auto &RT = CGM.getOpenMPRuntime();
1015
Alexey Bataev38e89532015-04-16 04:54:05 +00001016 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001017 // Check pre-condition.
1018 {
1019 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001020 // If the condition constant folds and can be elided, avoid emitting the
1021 // whole loop.
1022 bool CondConstant;
1023 llvm::BasicBlock *ContBlock = nullptr;
1024 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
1025 if (!CondConstant)
1026 return false;
1027 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +00001028 auto *ThenBlock = createBasicBlock("omp.precond.then");
1029 ContBlock = createBasicBlock("omp.precond.end");
1030 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00001031 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +00001032 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001033 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +00001034 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001035 // Emit 'then' code.
1036 {
1037 // Emit helper vars inits.
1038 LValue LB =
1039 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
1040 LValue UB =
1041 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
1042 LValue ST =
1043 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
1044 LValue IL =
1045 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
1046
1047 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +00001048 if (EmitOMPFirstprivateClause(S, LoopScope)) {
1049 // Emit implicit barrier to synchronize threads and avoid data races on
1050 // initialization of firstprivate variables.
1051 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
1052 OMPD_unknown);
1053 }
Alexey Bataev50a64582015-04-22 12:24:45 +00001054 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +00001055 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001056 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +00001057 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +00001058 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +00001059
1060 // Detect the loop schedule kind and chunk.
Alexey Bataev040d5402015-05-12 08:35:28 +00001061 llvm::Value *Chunk;
1062 OpenMPScheduleClauseKind ScheduleKind;
1063 auto ScheduleInfo =
1064 emitScheduleClause(*this, S, /*OuterRegion=*/false);
1065 Chunk = ScheduleInfo.first;
1066 ScheduleKind = ScheduleInfo.second;
Alexander Musmanc6388682014-12-15 07:07:06 +00001067 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1068 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001069 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr;
Alexander Musmanc6388682014-12-15 07:07:06 +00001070 if (RT.isStaticNonchunked(ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001071 /* Chunked */ Chunk != nullptr) &&
1072 !Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00001073 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1074 // When no chunk_size is specified, the iteration space is divided into
1075 // chunks that are approximately equal in size, and at most one chunk is
1076 // distributed to each thread. Note that the size of the chunks is
1077 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001078 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001079 Ordered, IL.getAddress(), LB.getAddress(),
1080 UB.getAddress(), ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001081 // UB = min(UB, GlobalUB);
1082 EmitIgnoredExpr(S.getEnsureUpperBound());
1083 // IV = LB;
1084 EmitIgnoredExpr(S.getInit());
1085 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001086 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1087 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001088 [&S](CodeGenFunction &CGF) {
1089 CGF.EmitOMPLoopBody(S);
1090 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001091 },
1092 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001093 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001094 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001095 } else {
1096 // Emit the outer loop, which requests its work chunk [LB..UB] from
1097 // runtime and runs the inner loop to process it.
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001098 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered,
1099 LB.getAddress(), UB.getAddress(), ST.getAddress(),
1100 IL.getAddress(), Chunk);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001101 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001102 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1104 if (HasLastprivateClause)
1105 EmitOMPLastprivateClauseFinal(
1106 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001107 }
1108 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001109 if (ContBlock) {
1110 EmitBranch(ContBlock);
1111 EmitBlock(ContBlock, true);
1112 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001113 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001114 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001115}
1116
1117void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001118 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001119 bool HasLastprivates = false;
1120 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1121 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1122 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001123 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001124
1125 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001126 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001127 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1128 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001129}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001130
Alexander Musmanf82886e2014-09-18 05:12:34 +00001131void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1132 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1133}
1134
Alexey Bataev2df54a02015-03-12 08:53:29 +00001135static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1136 const Twine &Name,
1137 llvm::Value *Init = nullptr) {
1138 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1139 if (Init)
1140 CGF.EmitScalarInit(Init, LVal);
1141 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001142}
1143
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001144static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1145 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001146 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1147 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1148 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001149 bool HasLastprivates = false;
1150 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001151 auto &C = CGF.CGM.getContext();
1152 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1153 // Emit helper vars inits.
1154 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1155 CGF.Builder.getInt32(0));
1156 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1157 LValue UB =
1158 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1159 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1160 CGF.Builder.getInt32(1));
1161 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1162 CGF.Builder.getInt32(0));
1163 // Loop counter.
1164 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1165 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001166 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001168 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001169 // Generate condition for loop.
1170 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1171 OK_Ordinary, S.getLocStart(),
1172 /*fpContractable=*/false);
1173 // Increment for loop counter.
1174 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1175 OK_Ordinary, S.getLocStart());
1176 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1177 // Iterate through all sections and emit a switch construct:
1178 // switch (IV) {
1179 // case 0:
1180 // <SectionStmt[0]>;
1181 // break;
1182 // ...
1183 // case <NumSection> - 1:
1184 // <SectionStmt[<NumSection> - 1]>;
1185 // break;
1186 // }
1187 // .omp.sections.exit:
1188 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1189 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1190 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1191 CS->size());
1192 unsigned CaseNumber = 0;
1193 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1194 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1195 CGF.EmitBlock(CaseBB);
1196 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1197 CGF.EmitStmt(*C);
1198 CGF.EmitBranch(ExitBB);
1199 }
1200 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1201 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001202
1203 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1204 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1205 // Emit implicit barrier to synchronize threads and avoid data races on
1206 // initialization of firstprivate variables.
1207 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1208 OMPD_unknown);
1209 }
Alexey Bataev73870832015-04-27 04:12:12 +00001210 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001211 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001212 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001213 (void)LoopScope.Privatize();
1214
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001215 // Emit static non-chunked loop.
1216 CGF.CGM.getOpenMPRuntime().emitForInit(
1217 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00001218 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
1219 LB.getAddress(), UB.getAddress(), ST.getAddress());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001220 // UB = min(UB, GlobalUB);
1221 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1222 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1223 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1224 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1225 // IV = LB;
1226 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1227 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001228 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1229 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001230 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001231 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001232 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001233
1234 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1235 if (HasLastprivates)
1236 CGF.EmitOMPLastprivateClauseFinal(
1237 S, CGF.Builder.CreateIsNotNull(
1238 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001239 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001240
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001241 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001242 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1243 // clause. Otherwise the barrier will be generated by the codegen for the
1244 // directive.
1245 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1246 // Emit implicit barrier to synchronize threads and avoid data races on
1247 // initialization of firstprivate variables.
1248 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1249 OMPD_unknown);
1250 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001251 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001252 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001253 // If only one section is found - no need to generate loop, emit as a single
1254 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001255 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001256 // No need to generate reductions for sections with single section region, we
1257 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001258 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001259 // No need to generate lastprivates for sections with single section region,
1260 // we can use original shared variable for all calculations with barrier at
1261 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001262 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001263 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1264 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1265 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001266 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001267 (void)SingleScope.Privatize();
1268
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001269 CGF.EmitStmt(Stmt);
1270 CGF.EnsureInsertPoint();
1271 };
1272 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1273 llvm::None, llvm::None,
1274 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001275 // Emit barrier for firstprivates, lastprivates or reductions only if
1276 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1277 // generated by the codegen for the directive.
1278 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1279 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001280 // Emit implicit barrier to synchronize threads and avoid data races on
1281 // initialization of firstprivate variables.
1282 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1283 OMPD_unknown);
1284 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001285 return OMPD_single;
1286}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001287
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001288void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1289 LexicalScope Scope(*this, S.getSourceRange());
1290 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001291 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001292 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001293 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001294 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001295}
1296
1297void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001298 LexicalScope Scope(*this, S.getSourceRange());
1299 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1300 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1301 CGF.EnsureInsertPoint();
1302 };
1303 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001304}
1305
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001306void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001307 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001308 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001309 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001310 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001311 // Check if there are any 'copyprivate' clauses associated with this
1312 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001313 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001314 // Build a list of copyprivate variables along with helper expressions
1315 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001316 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001317 auto *C = cast<OMPCopyprivateClause>(*I);
1318 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001319 DestExprs.append(C->destination_exprs().begin(),
1320 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001321 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001322 AssignmentOps.append(C->assignment_ops().begin(),
1323 C->assignment_ops().end());
1324 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001325 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001326 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001327 bool HasFirstprivates;
1328 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1329 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1330 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001331 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001332 (void)SingleScope.Privatize();
1333
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001334 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1335 CGF.EnsureInsertPoint();
1336 };
1337 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001338 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001339 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001340 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1341 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1342 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1343 CopyprivateVars.empty()) {
1344 CGM.getOpenMPRuntime().emitBarrierCall(
1345 *this, S.getLocStart(),
1346 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001347 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001348}
1349
Alexey Bataev8d690652014-12-04 07:23:53 +00001350void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001351 LexicalScope Scope(*this, S.getSourceRange());
1352 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1353 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1354 CGF.EnsureInsertPoint();
1355 };
1356 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001357}
1358
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001359void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001360 LexicalScope Scope(*this, S.getSourceRange());
1361 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1362 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1363 CGF.EnsureInsertPoint();
1364 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001365 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001366 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001367}
1368
Alexey Bataev671605e2015-04-13 05:28:11 +00001369void CodeGenFunction::EmitOMPParallelForDirective(
1370 const OMPParallelForDirective &S) {
1371 // Emit directive as a combined directive that consists of two implicit
1372 // directives: 'parallel' with 'for' directive.
1373 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev040d5402015-05-12 08:35:28 +00001374 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true);
Alexey Bataev671605e2015-04-13 05:28:11 +00001375 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1376 CGF.EmitOMPWorksharingLoop(S);
1377 // Emit implicit barrier at the end of parallel region, but this barrier
1378 // is at the end of 'for' directive, so emit it as the implicit barrier for
1379 // this 'for' directive.
1380 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1381 OMPD_parallel);
1382 };
1383 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001384}
1385
Alexander Musmane4e893b2014-09-23 09:33:00 +00001386void CodeGenFunction::EmitOMPParallelForSimdDirective(
1387 const OMPParallelForSimdDirective &) {
1388 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1389}
1390
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001391void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001392 const OMPParallelSectionsDirective &S) {
1393 // Emit directive as a combined directive that consists of two implicit
1394 // directives: 'parallel' with 'sections' directive.
1395 LexicalScope Scope(*this, S.getSourceRange());
1396 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1397 (void)emitSections(CGF, S);
1398 // Emit implicit barrier at the end of parallel region.
1399 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1400 OMPD_parallel);
1401 };
1402 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001403}
1404
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1406 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001407 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001408 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1409 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1410 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001411 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001412 // The first function argument for tasks is a thread id, the second one is a
1413 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001414 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1415 if (*PartId) {
1416 // TODO: emit code for untied tasks.
1417 }
1418 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1419 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001420 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001421 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001422 // Check if we should emit tied or untied task.
1423 bool Tied = !S.getSingleClause(OMPC_untied);
1424 // Check if the task is final
1425 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1426 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1427 // If the condition constant folds and can be elided, try to avoid emitting
1428 // the condition and the dead arm of the if/else.
1429 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1430 bool CondConstant;
1431 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1432 Final.setInt(CondConstant);
1433 else
1434 Final.setPointer(EvaluateExprAsBool(Cond));
1435 } else {
1436 // By default the task is not final.
1437 Final.setInt(/*IntVal=*/false);
1438 }
1439 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001440 const Expr *IfCond = nullptr;
1441 if (auto C = S.getSingleClause(OMPC_if)) {
1442 IfCond = cast<OMPIfClause>(C)->getCondition();
1443 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001444 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001445 // Get list of private variables.
1446 llvm::SmallVector<const Expr *, 8> Privates;
1447 llvm::SmallVector<const Expr *, 8> PrivateCopies;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00001448 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) {
1449 auto *C = cast<OMPPrivateClause>(*I);
1450 auto IRef = C->varlist_begin();
1451 for (auto *IInit : C->private_copies()) {
1452 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1453 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1454 Privates.push_back(*IRef);
1455 PrivateCopies.push_back(IInit);
1456 }
1457 ++IRef;
1458 }
1459 }
Alexey Bataev9e034042015-05-05 04:05:12 +00001460 EmittedAsPrivate.clear();
1461 // Get list of firstprivate variables.
1462 llvm::SmallVector<const Expr *, 8> FirstprivateVars;
1463 llvm::SmallVector<const Expr *, 8> FirstprivateCopies;
1464 llvm::SmallVector<const Expr *, 8> FirstprivateInits;
1465 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) {
1466 auto *C = cast<OMPFirstprivateClause>(*I);
1467 auto IRef = C->varlist_begin();
1468 auto IElemInitRef = C->inits().begin();
1469 for (auto *IInit : C->private_copies()) {
1470 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
1471 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
1472 FirstprivateVars.push_back(*IRef);
1473 FirstprivateCopies.push_back(IInit);
1474 FirstprivateInits.push_back(*IElemInitRef);
1475 }
1476 ++IRef, ++IElemInitRef;
1477 }
1478 }
1479 CGM.getOpenMPRuntime().emitTaskCall(
1480 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy,
1481 CapturedStruct, IfCond, Privates, PrivateCopies, FirstprivateVars,
1482 FirstprivateCopies, FirstprivateInits);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001483}
1484
Alexey Bataev9f797f32015-02-05 05:57:51 +00001485void CodeGenFunction::EmitOMPTaskyieldDirective(
1486 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001487 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001488}
1489
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001490void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001491 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001492}
1493
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001494void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1495 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001496}
1497
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001498void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001499 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1500 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1501 auto FlushClause = cast<OMPFlushClause>(C);
1502 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1503 FlushClause->varlist_end());
1504 }
1505 return llvm::None;
1506 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001507}
1508
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001509void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1510 LexicalScope Scope(*this, S.getSourceRange());
1511 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1512 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1513 CGF.EnsureInsertPoint();
1514 };
1515 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001516}
1517
Alexey Bataevb57056f2015-01-22 06:17:56 +00001518static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1519 QualType SrcType, QualType DestType) {
1520 assert(CGF.hasScalarEvaluationKind(DestType) &&
1521 "DestType must have scalar evaluation kind.");
1522 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1523 return Val.isScalar()
1524 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1525 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1526 DestType);
1527}
1528
1529static CodeGenFunction::ComplexPairTy
1530convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1531 QualType DestType) {
1532 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1533 "DestType must have complex evaluation kind.");
1534 CodeGenFunction::ComplexPairTy ComplexVal;
1535 if (Val.isScalar()) {
1536 // Convert the input element to the element type of the complex.
1537 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1538 auto ScalarVal =
1539 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1540 ComplexVal = CodeGenFunction::ComplexPairTy(
1541 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1542 } else {
1543 assert(Val.isComplex() && "Must be a scalar or complex.");
1544 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1545 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1546 ComplexVal.first = CGF.EmitScalarConversion(
1547 Val.getComplexVal().first, SrcElementType, DestElementType);
1548 ComplexVal.second = CGF.EmitScalarConversion(
1549 Val.getComplexVal().second, SrcElementType, DestElementType);
1550 }
1551 return ComplexVal;
1552}
1553
Alexey Bataev5e018f92015-04-23 06:35:10 +00001554static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1555 LValue LVal, RValue RVal) {
1556 if (LVal.isGlobalReg()) {
1557 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1558 } else {
1559 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1560 : llvm::Monotonic,
1561 LVal.isVolatile(), /*IsInit=*/false);
1562 }
1563}
1564
1565static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1566 QualType RValTy) {
1567 switch (CGF.getEvaluationKind(LVal.getType())) {
1568 case TEK_Scalar:
1569 CGF.EmitStoreThroughLValue(
1570 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1571 LVal);
1572 break;
1573 case TEK_Complex:
1574 CGF.EmitStoreOfComplex(
1575 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1576 /*isInit=*/false);
1577 break;
1578 case TEK_Aggregate:
1579 llvm_unreachable("Must be a scalar or complex.");
1580 }
1581}
1582
Alexey Bataevb57056f2015-01-22 06:17:56 +00001583static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1584 const Expr *X, const Expr *V,
1585 SourceLocation Loc) {
1586 // v = x;
1587 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1588 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1589 LValue XLValue = CGF.EmitLValue(X);
1590 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001591 RValue Res = XLValue.isGlobalReg()
1592 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1593 : CGF.EmitAtomicLoad(XLValue, Loc,
1594 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001595 : llvm::Monotonic,
1596 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001597 // OpenMP, 2.12.6, atomic Construct
1598 // Any atomic construct with a seq_cst clause forces the atomically
1599 // performed operation to include an implicit flush operation without a
1600 // list.
1601 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001602 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001603 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001604}
1605
Alexey Bataevb8329262015-02-27 06:33:30 +00001606static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1607 const Expr *X, const Expr *E,
1608 SourceLocation Loc) {
1609 // x = expr;
1610 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001611 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001612 // OpenMP, 2.12.6, atomic Construct
1613 // Any atomic construct with a seq_cst clause forces the atomically
1614 // performed operation to include an implicit flush operation without a
1615 // list.
1616 if (IsSeqCst)
1617 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1618}
1619
Benjamin Kramer439ee9d2015-05-01 13:59:53 +00001620static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1621 RValue Update,
1622 BinaryOperatorKind BO,
1623 llvm::AtomicOrdering AO,
1624 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001625 auto &Context = CGF.CGM.getContext();
1626 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001627 // expression is simple and atomic is allowed for the given type for the
1628 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001629 if (BO == BO_Comma || !Update.isScalar() ||
Alexey Bataev9d541a72015-05-08 11:47:16 +00001630 !Update.getScalarVal()->getType()->isIntegerTy() ||
1631 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1632 (Update.getScalarVal()->getType() !=
1633 X.getAddress()->getType()->getPointerElementType())) ||
1634 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() ||
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001635 !Context.getTargetInfo().hasBuiltinAtomic(
1636 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001637 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001638
1639 llvm::AtomicRMWInst::BinOp RMWOp;
1640 switch (BO) {
1641 case BO_Add:
1642 RMWOp = llvm::AtomicRMWInst::Add;
1643 break;
1644 case BO_Sub:
1645 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001646 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001647 RMWOp = llvm::AtomicRMWInst::Sub;
1648 break;
1649 case BO_And:
1650 RMWOp = llvm::AtomicRMWInst::And;
1651 break;
1652 case BO_Or:
1653 RMWOp = llvm::AtomicRMWInst::Or;
1654 break;
1655 case BO_Xor:
1656 RMWOp = llvm::AtomicRMWInst::Xor;
1657 break;
1658 case BO_LT:
1659 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1660 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1661 : llvm::AtomicRMWInst::Max)
1662 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1663 : llvm::AtomicRMWInst::UMax);
1664 break;
1665 case BO_GT:
1666 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1667 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1668 : llvm::AtomicRMWInst::Min)
1669 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1670 : llvm::AtomicRMWInst::UMin);
1671 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001672 case BO_Assign:
1673 RMWOp = llvm::AtomicRMWInst::Xchg;
1674 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001675 case BO_Mul:
1676 case BO_Div:
1677 case BO_Rem:
1678 case BO_Shl:
1679 case BO_Shr:
1680 case BO_LAnd:
1681 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001682 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001683 case BO_PtrMemD:
1684 case BO_PtrMemI:
1685 case BO_LE:
1686 case BO_GE:
1687 case BO_EQ:
1688 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001689 case BO_AddAssign:
1690 case BO_SubAssign:
1691 case BO_AndAssign:
1692 case BO_OrAssign:
1693 case BO_XorAssign:
1694 case BO_MulAssign:
1695 case BO_DivAssign:
1696 case BO_RemAssign:
1697 case BO_ShlAssign:
1698 case BO_ShrAssign:
1699 case BO_Comma:
1700 llvm_unreachable("Unsupported atomic update operation");
1701 }
1702 auto *UpdateVal = Update.getScalarVal();
1703 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1704 UpdateVal = CGF.Builder.CreateIntCast(
1705 IC, X.getAddress()->getType()->getPointerElementType(),
1706 X.getType()->hasSignedIntegerRepresentation());
1707 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001708 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1709 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001710}
1711
Alexey Bataev5e018f92015-04-23 06:35:10 +00001712std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001713 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1714 llvm::AtomicOrdering AO, SourceLocation Loc,
1715 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1716 // Update expressions are allowed to have the following forms:
1717 // x binop= expr; -> xrval + expr;
1718 // x++, ++x -> xrval + 1;
1719 // x--, --x -> xrval - 1;
1720 // x = x binop expr; -> xrval binop expr
1721 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001722 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1723 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001724 if (X.isGlobalReg()) {
1725 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1726 // 'xrval'.
1727 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1728 } else {
1729 // Perform compare-and-swap procedure.
1730 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001731 }
1732 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001733 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001734}
1735
1736static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1737 const Expr *X, const Expr *E,
1738 const Expr *UE, bool IsXLHSInRHSPart,
1739 SourceLocation Loc) {
1740 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1741 "Update expr in 'atomic update' must be a binary operator.");
1742 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1743 // Update expressions are allowed to have the following forms:
1744 // x binop= expr; -> xrval + expr;
1745 // x++, ++x -> xrval + 1;
1746 // x--, --x -> xrval - 1;
1747 // x = x binop expr; -> xrval binop expr
1748 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001749 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001750 LValue XLValue = CGF.EmitLValue(X);
1751 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001752 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001753 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1754 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1755 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1756 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1757 auto Gen =
1758 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1759 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1760 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1761 return CGF.EmitAnyExpr(UE);
1762 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001763 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1764 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1765 // OpenMP, 2.12.6, atomic Construct
1766 // Any atomic construct with a seq_cst clause forces the atomically
1767 // performed operation to include an implicit flush operation without a
1768 // list.
1769 if (IsSeqCst)
1770 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1771}
1772
1773static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1774 QualType SourceType, QualType ResType) {
1775 switch (CGF.getEvaluationKind(ResType)) {
1776 case TEK_Scalar:
1777 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1778 case TEK_Complex: {
1779 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1780 return RValue::getComplex(Res.first, Res.second);
1781 }
1782 case TEK_Aggregate:
1783 break;
1784 }
1785 llvm_unreachable("Must be a scalar or complex.");
1786}
1787
1788static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1789 bool IsPostfixUpdate, const Expr *V,
1790 const Expr *X, const Expr *E,
1791 const Expr *UE, bool IsXLHSInRHSPart,
1792 SourceLocation Loc) {
1793 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1794 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1795 RValue NewVVal;
1796 LValue VLValue = CGF.EmitLValue(V);
1797 LValue XLValue = CGF.EmitLValue(X);
1798 RValue ExprRValue = CGF.EmitAnyExpr(E);
1799 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1800 QualType NewVValType;
1801 if (UE) {
1802 // 'x' is updated with some additional value.
1803 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1804 "Update expr in 'atomic capture' must be a binary operator.");
1805 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1806 // Update expressions are allowed to have the following forms:
1807 // x binop= expr; -> xrval + expr;
1808 // x++, ++x -> xrval + 1;
1809 // x--, --x -> xrval - 1;
1810 // x = x binop expr; -> xrval binop expr
1811 // x = expr Op x; - > expr binop xrval;
1812 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1813 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1814 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1815 NewVValType = XRValExpr->getType();
1816 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1817 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1818 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1819 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1820 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1821 RValue Res = CGF.EmitAnyExpr(UE);
1822 NewVVal = IsPostfixUpdate ? XRValue : Res;
1823 return Res;
1824 };
1825 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1826 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1827 if (Res.first) {
1828 // 'atomicrmw' instruction was generated.
1829 if (IsPostfixUpdate) {
1830 // Use old value from 'atomicrmw'.
1831 NewVVal = Res.second;
1832 } else {
1833 // 'atomicrmw' does not provide new value, so evaluate it using old
1834 // value of 'x'.
1835 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1836 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1837 NewVVal = CGF.EmitAnyExpr(UE);
1838 }
1839 }
1840 } else {
1841 // 'x' is simply rewritten with some 'expr'.
1842 NewVValType = X->getType().getNonReferenceType();
1843 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1844 X->getType().getNonReferenceType());
1845 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1846 NewVVal = XRValue;
1847 return ExprRValue;
1848 };
1849 // Try to perform atomicrmw xchg, otherwise simple exchange.
1850 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1851 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1852 Loc, Gen);
1853 if (Res.first) {
1854 // 'atomicrmw' instruction was generated.
1855 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1856 }
1857 }
1858 // Emit post-update store to 'v' of old/new 'x' value.
1859 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001860 // OpenMP, 2.12.6, atomic Construct
1861 // Any atomic construct with a seq_cst clause forces the atomically
1862 // performed operation to include an implicit flush operation without a
1863 // list.
1864 if (IsSeqCst)
1865 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1866}
1867
Alexey Bataevb57056f2015-01-22 06:17:56 +00001868static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001869 bool IsSeqCst, bool IsPostfixUpdate,
1870 const Expr *X, const Expr *V, const Expr *E,
1871 const Expr *UE, bool IsXLHSInRHSPart,
1872 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001873 switch (Kind) {
1874 case OMPC_read:
1875 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1876 break;
1877 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001878 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1879 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001880 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001881 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001882 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1883 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001884 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001885 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1886 IsXLHSInRHSPart, Loc);
1887 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001888 case OMPC_if:
1889 case OMPC_final:
1890 case OMPC_num_threads:
1891 case OMPC_private:
1892 case OMPC_firstprivate:
1893 case OMPC_lastprivate:
1894 case OMPC_reduction:
1895 case OMPC_safelen:
1896 case OMPC_collapse:
1897 case OMPC_default:
1898 case OMPC_seq_cst:
1899 case OMPC_shared:
1900 case OMPC_linear:
1901 case OMPC_aligned:
1902 case OMPC_copyin:
1903 case OMPC_copyprivate:
1904 case OMPC_flush:
1905 case OMPC_proc_bind:
1906 case OMPC_schedule:
1907 case OMPC_ordered:
1908 case OMPC_nowait:
1909 case OMPC_untied:
1910 case OMPC_threadprivate:
1911 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001912 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1913 }
1914}
1915
1916void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1917 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1918 OpenMPClauseKind Kind = OMPC_unknown;
1919 for (auto *C : S.clauses()) {
1920 // Find first clause (skip seq_cst clause, if it is first).
1921 if (C->getClauseKind() != OMPC_seq_cst) {
1922 Kind = C->getClauseKind();
1923 break;
1924 }
1925 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001926
1927 const auto *CS =
1928 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001929 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001930 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001931 }
1932 // Processing for statements under 'atomic capture'.
1933 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1934 for (const auto *C : Compound->body()) {
1935 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1936 enterFullExpression(EWC);
1937 }
1938 }
1939 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001940
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001941 LexicalScope Scope(*this, S.getSourceRange());
1942 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001943 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1944 S.getV(), S.getExpr(), S.getUpdateExpr(),
1945 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001946 };
1947 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001948}
1949
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001950void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1951 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1952}
1953
Alexey Bataev13314bf2014-10-09 04:18:56 +00001954void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1955 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1956}