blob: e445e7668ee493dfe0003e4dd00320eb58ec1090 [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();
135 if (OrigVD->getType()->isArrayType()) {
136 // Emit VarDecl with copy init for arrays.
137 // Get the address of the original variable captured in current
138 // captured region.
139 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
140 auto Emission = EmitAutoVarAlloca(*VD);
141 auto *Init = VD->getInit();
142 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
143 // Perform simple memcpy.
144 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
145 (*IRef)->getType());
146 } else {
147 EmitOMPAggregateAssign(
148 Emission.getAllocatedAddress(), OriginalAddr,
149 (*IRef)->getType(),
150 [this, VDInit, Init](llvm::Value *DestElement,
151 llvm::Value *SrcElement) {
152 // Clean up any temporaries needed by the initialization.
153 RunCleanupsScope InitScope(*this);
154 // Emit initialization for single element.
155 LocalDeclMap[VDInit] = SrcElement;
156 EmitAnyExprToMem(Init, DestElement,
157 Init->getType().getQualifiers(),
158 /*IsInitializer*/ false);
159 LocalDeclMap.erase(VDInit);
160 });
161 }
162 EmitAutoVarCleanups(Emission);
163 return Emission.getAllocatedAddress();
164 });
165 } else {
166 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
167 // Emit private VarDecl with copy init.
168 // Remap temp VDInit variable to the address of the original
169 // variable
170 // (for proper handling of captured global variables).
171 LocalDeclMap[VDInit] = OriginalAddr;
172 EmitDecl(*VD);
173 LocalDeclMap.erase(VDInit);
174 return GetAddrOfLocalVar(VD);
175 });
176 }
177 assert(IsRegistered &&
178 "firstprivate var already registered as private");
179 // Silence the warning about unused variable.
180 (void)IsRegistered;
181 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000182 ++IRef, ++InitsRef;
183 }
184 }
Alexey Bataev69c62a92015-04-15 04:52:20 +0000185 return !EmittedAsFirstprivate.empty();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000186}
187
Alexey Bataev03b340a2014-10-21 03:16:40 +0000188void CodeGenFunction::EmitOMPPrivateClause(
189 const OMPExecutableDirective &D,
190 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataev50a64582015-04-22 12:24:45 +0000191 llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000192 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) {
Alexey Bataev03b340a2014-10-21 03:16:40 +0000193 auto *C = cast<OMPPrivateClause>(*I);
194 auto IRef = C->varlist_begin();
195 for (auto IInit : C->private_copies()) {
196 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
Alexey Bataev50a64582015-04-22 12:24:45 +0000197 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
198 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
199 bool IsRegistered =
200 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
201 // Emit private VarDecl with copy init.
202 EmitDecl(*VD);
203 return GetAddrOfLocalVar(VD);
204 });
205 assert(IsRegistered && "private var already registered as private");
206 // Silence the warning about unused variable.
207 (void)IsRegistered;
208 }
Alexey Bataev03b340a2014-10-21 03:16:40 +0000209 ++IRef;
210 }
211 }
212}
213
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000214bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
215 // threadprivate_var1 = master_threadprivate_var1;
216 // operator=(threadprivate_var2, master_threadprivate_var2);
217 // ...
218 // __kmpc_barrier(&loc, global_tid);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000219 llvm::DenseSet<const VarDecl *> CopiedVars;
220 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000221 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) {
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000222 auto *C = cast<OMPCopyinClause>(*I);
223 auto IRef = C->varlist_begin();
224 auto ISrcRef = C->source_exprs().begin();
225 auto IDestRef = C->destination_exprs().begin();
226 for (auto *AssignOp : C->assignment_ops()) {
227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
228 if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
229 // Get the address of the master variable.
230 auto *MasterAddr = VD->isStaticLocal()
231 ? CGM.getStaticLocalDeclAddress(VD)
232 : CGM.GetAddrOfGlobal(VD);
233 // Get the address of the threadprivate variable.
234 auto *PrivateAddr = EmitLValue(*IRef).getAddress();
235 if (CopiedVars.size() == 1) {
236 // At first check if current thread is a master thread. If it is, no
237 // need to copy data.
238 CopyBegin = createBasicBlock("copyin.not.master");
239 CopyEnd = createBasicBlock("copyin.not.master.end");
240 Builder.CreateCondBr(
241 Builder.CreateICmpNE(
242 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy),
243 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)),
244 CopyBegin, CopyEnd);
245 EmitBlock(CopyBegin);
246 }
247 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
248 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
249 EmitOMPCopy(*this, (*IRef)->getType(), PrivateAddr, MasterAddr, DestVD,
250 SrcVD, AssignOp);
251 }
252 ++IRef;
253 ++ISrcRef;
254 ++IDestRef;
255 }
256 }
257 if (CopyEnd) {
258 // Exit out of copying procedure for non-master thread.
259 EmitBlock(CopyEnd, /*IsFinished=*/true);
260 return true;
261 }
262 return false;
263}
264
Alexey Bataev38e89532015-04-16 04:54:05 +0000265bool CodeGenFunction::EmitOMPLastprivateClauseInit(
266 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000267 bool HasAtLeastOneLastprivate = false;
268 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000269 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000270 auto *C = cast<OMPLastprivateClause>(*I);
271 auto IRef = C->varlist_begin();
272 auto IDestRef = C->destination_exprs().begin();
273 for (auto *IInit : C->private_copies()) {
274 // Keep the address of the original variable for future update at the end
275 // of the loop.
276 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
277 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
278 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
279 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{
280 DeclRefExpr DRE(
281 const_cast<VarDecl *>(OrigVD),
282 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
283 OrigVD) != nullptr,
284 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
285 return EmitLValue(&DRE).getAddress();
286 });
287 // Check if the variable is also a firstprivate: in this case IInit is
288 // not generated. Initialization of this variable will happen in codegen
289 // for 'firstprivate' clause.
290 if (!IInit)
291 continue;
292 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
293 bool IsRegistered =
294 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{
295 // Emit private VarDecl with copy init.
296 EmitDecl(*VD);
297 return GetAddrOfLocalVar(VD);
298 });
299 assert(IsRegistered && "lastprivate var already registered as private");
300 HasAtLeastOneLastprivate = HasAtLeastOneLastprivate || IsRegistered;
301 }
302 ++IRef, ++IDestRef;
303 }
304 }
305 return HasAtLeastOneLastprivate;
306}
307
308void CodeGenFunction::EmitOMPLastprivateClauseFinal(
309 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) {
310 // Emit following code:
311 // if (<IsLastIterCond>) {
312 // orig_var1 = private_orig_var1;
313 // ...
314 // orig_varn = private_orig_varn;
315 // }
316 auto *ThenBB = createBasicBlock(".omp.lastprivate.then");
317 auto *DoneBB = createBasicBlock(".omp.lastprivate.done");
318 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
319 EmitBlock(ThenBB);
320 {
Alexey Bataev38e89532015-04-16 04:54:05 +0000321 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000322 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000323 auto *C = cast<OMPLastprivateClause>(*I);
324 auto IRef = C->varlist_begin();
325 auto ISrcRef = C->source_exprs().begin();
326 auto IDestRef = C->destination_exprs().begin();
327 for (auto *AssignOp : C->assignment_ops()) {
328 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
329 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) {
330 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
331 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
332 // Get the address of the original variable.
333 auto *OriginalAddr = GetAddrOfLocalVar(DestVD);
334 // Get the address of the private variable.
335 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD);
336 EmitOMPCopy(*this, (*IRef)->getType(), OriginalAddr, PrivateAddr,
337 DestVD, SrcVD, AssignOp);
338 }
339 ++IRef;
340 ++ISrcRef;
341 ++IDestRef;
342 }
343 }
344 }
345 EmitBlock(DoneBB, /*IsFinished=*/true);
346}
347
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000348void CodeGenFunction::EmitOMPReductionClauseInit(
349 const OMPExecutableDirective &D,
350 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000351 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000352 auto *C = cast<OMPReductionClause>(*I);
353 auto ILHS = C->lhs_exprs().begin();
354 auto IRHS = C->rhs_exprs().begin();
355 for (auto IRef : C->varlists()) {
356 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
357 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
358 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
359 // Store the address of the original variable associated with the LHS
360 // implicit variable.
361 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{
362 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
363 CapturedStmtInfo->lookup(OrigVD) != nullptr,
364 IRef->getType(), VK_LValue, IRef->getExprLoc());
365 return EmitLValue(&DRE).getAddress();
366 });
367 // Emit reduction copy.
368 bool IsRegistered =
369 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{
370 // Emit private VarDecl with reduction init.
371 EmitDecl(*PrivateVD);
372 return GetAddrOfLocalVar(PrivateVD);
373 });
374 assert(IsRegistered && "private var already registered as private");
375 // Silence the warning about unused variable.
376 (void)IsRegistered;
377 ++ILHS, ++IRHS;
378 }
379 }
380}
381
382void CodeGenFunction::EmitOMPReductionClauseFinal(
383 const OMPExecutableDirective &D) {
384 llvm::SmallVector<const Expr *, 8> LHSExprs;
385 llvm::SmallVector<const Expr *, 8> RHSExprs;
386 llvm::SmallVector<const Expr *, 8> ReductionOps;
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000387 bool HasAtLeastOneReduction = false;
Alexey Bataevc925aa32015-04-27 08:00:32 +0000388 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000389 HasAtLeastOneReduction = true;
390 auto *C = cast<OMPReductionClause>(*I);
391 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
392 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
393 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
394 }
395 if (HasAtLeastOneReduction) {
396 // Emit nowait reduction if nowait clause is present or directive is a
397 // parallel directive (it always has implicit barrier).
398 CGM.getOpenMPRuntime().emitReduction(
399 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps,
400 D.getSingleClause(OMPC_nowait) ||
401 isOpenMPParallelDirective(D.getDirectiveKind()));
402 }
403}
404
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405static void emitCommonOMPParallelDirective(CodeGenFunction &CGF,
406 const OMPExecutableDirective &S,
407 const RegionCodeGenTy &CodeGen) {
Alexey Bataev18095712014-10-10 12:19:54 +0000408 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS);
410 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
411 S, *CS->getCapturedDecl()->param_begin(), CodeGen);
Alexey Bataev1d677132015-04-22 13:57:31 +0000412 if (auto C = S.getSingleClause(OMPC_num_threads)) {
413 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
414 auto NumThreadsClause = cast<OMPNumThreadsClause>(C);
415 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
416 /*IgnoreResultAssign*/ true);
417 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
418 CGF, NumThreads, NumThreadsClause->getLocStart());
419 }
420 const Expr *IfCond = nullptr;
421 if (auto C = S.getSingleClause(OMPC_if)) {
422 IfCond = cast<OMPIfClause>(C)->getCondition();
423 }
424 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
425 CapturedStruct, IfCond);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000426}
427
428void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
429 LexicalScope Scope(*this, S.getSourceRange());
430 // Emit parallel region as a standalone region.
431 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
432 OMPPrivateScope PrivateScope(CGF);
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000433 bool Copyins = CGF.EmitOMPCopyinClause(S);
434 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope);
435 if (Copyins || Firstprivates) {
Alexey Bataev69c62a92015-04-15 04:52:20 +0000436 // Emit implicit barrier to synchronize threads and avoid data races on
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000437 // initialization of firstprivate variables or propagation master's thread
438 // values of threadprivate variables to local instances of that variables
439 // of all other implicit threads.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000440 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
441 OMPD_unknown);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000442 }
443 CGF.EmitOMPPrivateClause(S, PrivateScope);
444 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
445 (void)PrivateScope.Privatize();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000446 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
Alexey Bataev794ba0d2015-04-10 10:43:45 +0000447 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000448 // Emit implicit barrier at the end of the 'parallel' directive.
449 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
450 OMPD_unknown);
451 };
452 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev9959db52014-05-06 10:08:46 +0000453}
Alexander Musman515ad8c2014-05-22 08:54:05 +0000454
Alexander Musmand196ef22014-10-07 08:57:09 +0000455void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S,
Alexander Musmana5f070a2014-10-01 06:03:56 +0000456 bool SeparateIter) {
457 RunCleanupsScope BodyScope(*this);
458 // Update counters values on current iteration.
459 for (auto I : S.updates()) {
460 EmitIgnoredExpr(I);
461 }
Alexander Musman3276a272015-03-21 10:12:56 +0000462 // Update the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000463 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
464 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000465 for (auto U : C->updates()) {
466 EmitIgnoredExpr(U);
467 }
468 }
469
Alexander Musmana5f070a2014-10-01 06:03:56 +0000470 // On a continue in the body, jump to the end.
Alexander Musmand196ef22014-10-07 08:57:09 +0000471 auto Continue = getJumpDestInCurrentScope("omp.body.continue");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000472 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue));
473 // Emit loop body.
474 EmitStmt(S.getBody());
475 // The end (updates/cleanups).
476 EmitBlock(Continue.getBlock());
477 BreakContinueStack.pop_back();
478 if (SeparateIter) {
479 // TODO: Update lastprivates if the SeparateIter flag is true.
480 // This will be implemented in a follow-up OMPLastprivateClause patch, but
481 // result should be still correct without it, as we do not make these
482 // variables private yet.
483 }
484}
485
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000486void CodeGenFunction::EmitOMPInnerLoop(
487 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
488 const Expr *IncExpr,
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000489 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
490 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
Alexander Musmand196ef22014-10-07 08:57:09 +0000491 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000492
493 // Start the loop with a block that tests the condition.
Alexander Musmand196ef22014-10-07 08:57:09 +0000494 auto CondBlock = createBasicBlock("omp.inner.for.cond");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000495 EmitBlock(CondBlock);
496 LoopStack.push(CondBlock);
497
498 // If there are any cleanups between here and the loop-exit scope,
499 // create a block to stage a loop exit along.
500 auto ExitBlock = LoopExit.getBlock();
Alexey Bataev2df54a02015-03-12 08:53:29 +0000501 if (RequiresCleanup)
Alexander Musmand196ef22014-10-07 08:57:09 +0000502 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000503
Alexander Musmand196ef22014-10-07 08:57:09 +0000504 auto LoopBody = createBasicBlock("omp.inner.for.body");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000505
Alexey Bataev2df54a02015-03-12 08:53:29 +0000506 // Emit condition.
Justin Bogner66242d62015-04-23 23:06:47 +0000507 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
Alexander Musmana5f070a2014-10-01 06:03:56 +0000508 if (ExitBlock != LoopExit.getBlock()) {
509 EmitBlock(ExitBlock);
510 EmitBranchThroughCleanup(LoopExit);
511 }
512
513 EmitBlock(LoopBody);
Justin Bogner66242d62015-04-23 23:06:47 +0000514 incrementProfileCounter(&S);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000515
516 // Create a block for the increment.
Alexander Musmand196ef22014-10-07 08:57:09 +0000517 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
Alexander Musmana5f070a2014-10-01 06:03:56 +0000518 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
519
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000520 BodyGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000521
522 // Emit "IV = IV + 1" and a back-edge to the condition block.
523 EmitBlock(Continue.getBlock());
Alexey Bataev2df54a02015-03-12 08:53:29 +0000524 EmitIgnoredExpr(IncExpr);
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000525 PostIncGen(*this);
Alexander Musmana5f070a2014-10-01 06:03:56 +0000526 BreakContinueStack.pop_back();
527 EmitBranch(CondBlock);
528 LoopStack.pop();
529 // Emit the fall-through block.
530 EmitBlock(LoopExit.getBlock());
531}
532
533void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) {
534 auto IC = S.counters().begin();
535 for (auto F : S.finals()) {
536 if (LocalDeclMap.lookup(cast<DeclRefExpr>((*IC))->getDecl())) {
537 EmitIgnoredExpr(F);
538 }
539 ++IC;
540 }
Alexander Musman3276a272015-03-21 10:12:56 +0000541 // Emit the final values of the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000542 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
543 auto *C = cast<OMPLinearClause>(*I);
Alexander Musman3276a272015-03-21 10:12:56 +0000544 for (auto F : C->finals()) {
545 EmitIgnoredExpr(F);
546 }
547 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000548}
549
Alexander Musman09184fe2014-09-30 05:29:28 +0000550static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM,
551 const OMPAlignedClause &Clause) {
552 unsigned ClauseAlignment = 0;
553 if (auto AlignmentExpr = Clause.getAlignment()) {
554 auto AlignmentCI =
555 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
556 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
557 }
558 for (auto E : Clause.varlists()) {
559 unsigned Alignment = ClauseAlignment;
560 if (Alignment == 0) {
561 // OpenMP [2.8.1, Description]
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000562 // If no optional parameter is specified, implementation-defined default
Alexander Musman09184fe2014-09-30 05:29:28 +0000563 // alignments for SIMD instructions on the target platforms are assumed.
564 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment(
565 E->getType());
566 }
567 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
568 "alignment is not power of 2");
569 if (Alignment != 0) {
570 llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
571 CGF.EmitAlignmentAssumption(PtrValue, Alignment);
572 }
573 }
574}
575
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000576static void EmitPrivateLoopCounters(CodeGenFunction &CGF,
577 CodeGenFunction::OMPPrivateScope &LoopScope,
578 ArrayRef<Expr *> Counters) {
579 for (auto *E : Counters) {
580 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
581 bool IsRegistered = LoopScope.addPrivate(VD, [&]() -> llvm::Value * {
582 // Emit var without initialization.
583 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
584 CGF.EmitAutoVarCleanups(VarEmission);
585 return VarEmission.getAllocatedAddress();
586 });
587 assert(IsRegistered && "counter already registered as private");
588 // Silence the warning about unused variable.
589 (void)IsRegistered;
590 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000591}
592
Alexey Bataev62dbb972015-04-22 11:59:37 +0000593static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
594 const Expr *Cond, llvm::BasicBlock *TrueBlock,
595 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
596 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
597 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
598 const VarDecl *IVDecl =
599 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
600 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
601 // Emit var without initialization.
602 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
603 CGF.EmitAutoVarCleanups(VarEmission);
604 return VarEmission.getAllocatedAddress();
605 });
606 assert(IsRegistered && "counter already registered as private");
607 // Silence the warning about unused variable.
608 (void)IsRegistered;
609 (void)PreCondScope.Privatize();
610 // Initialize internal counter to 0 to calculate initial values of real
611 // counters.
612 LValue IV = CGF.EmitLValue(S.getIterationVariable());
613 CGF.EmitStoreOfScalar(
614 llvm::ConstantInt::getNullValue(
615 IV.getAddress()->getType()->getPointerElementType()),
616 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
617 // Get initial values of real counters.
618 for (auto I : S.updates()) {
619 CGF.EmitIgnoredExpr(I);
620 }
621 // Check that loop is executed at least one time.
622 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
623}
624
Alexander Musman3276a272015-03-21 10:12:56 +0000625static void
626EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
627 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000628 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
629 auto *C = cast<OMPLinearClause>(*I);
630 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000631 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
632 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
633 // Emit var without initialization.
634 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
635 CGF.EmitAutoVarCleanups(VarEmission);
636 return VarEmission.getAllocatedAddress();
637 });
638 assert(IsRegistered && "linear var already registered as private");
639 // Silence the warning about unused variable.
640 (void)IsRegistered;
641 }
642 }
643}
644
Alexander Musman515ad8c2014-05-22 08:54:05 +0000645void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000646 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
647 // Pragma 'simd' code depends on presence of 'lastprivate'.
648 // If present, we have to separate last iteration of the loop:
649 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000650 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000651 // for (IV in 0..LastIteration-1) BODY;
652 // BODY with updates of lastprivate vars;
653 // <Final counter/linear vars updates>;
654 // }
655 //
656 // otherwise (when there's no lastprivate):
657 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000658 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000659 // for (IV in 0..LastIteration) BODY;
660 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000661 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000662 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000663
Alexey Bataev62dbb972015-04-22 11:59:37 +0000664 // Emit: if (PreCond) - begin.
665 // If the condition constant folds and can be elided, avoid emitting the
666 // whole loop.
667 bool CondConstant;
668 llvm::BasicBlock *ContBlock = nullptr;
669 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
670 if (!CondConstant)
671 return;
672 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000673 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
674 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000675 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
676 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000677 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000678 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000679 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000680 // Walk clauses and process safelen/lastprivate.
681 bool SeparateIter = false;
682 CGF.LoopStack.setParallel();
683 CGF.LoopStack.setVectorizerEnable(true);
684 for (auto C : S.clauses()) {
685 switch (C->getClauseKind()) {
686 case OMPC_safelen: {
687 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
688 AggValueSlot::ignored(), true);
689 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
690 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
691 // In presence of finite 'safelen', it may be unsafe to mark all
692 // the memory instructions parallel, because loop-carried
693 // dependences of 'safelen' iterations are possible.
694 CGF.LoopStack.setParallel(false);
695 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000696 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000697 case OMPC_aligned:
698 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
699 break;
700 case OMPC_lastprivate:
701 SeparateIter = true;
702 break;
703 default:
704 // Not handled yet
705 ;
706 }
707 }
Alexander Musman3276a272015-03-21 10:12:56 +0000708
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000709 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000710 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
711 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000712 for (auto Init : C->inits()) {
713 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
714 CGF.EmitVarDecl(*D);
715 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000716 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000717
718 // Emit the loop iteration variable.
719 const Expr *IVExpr = S.getIterationVariable();
720 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
721 CGF.EmitVarDecl(*IVDecl);
722 CGF.EmitIgnoredExpr(S.getInit());
723
724 // Emit the iterations count variable.
725 // If it is not a variable, Sema decided to calculate iterations count on
726 // each
727 // iteration (e.g., it is foldable into a constant).
728 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
729 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
730 // Emit calculation of the iterations count.
731 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000732 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000733
734 // Emit the linear steps for the linear clauses.
735 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000736 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
737 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000738 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
739 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
740 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
741 // Emit calculation of the linear step.
742 CGF.EmitIgnoredExpr(CS);
743 }
744 }
745
Alexey Bataev62dbb972015-04-22 11:59:37 +0000746 {
747 OMPPrivateScope LoopScope(CGF);
748 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
749 EmitPrivateLinearVars(CGF, S, LoopScope);
750 CGF.EmitOMPPrivateClause(S, LoopScope);
751 (void)LoopScope.Privatize();
752 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
753 S.getCond(SeparateIter), S.getInc(),
754 [&S](CodeGenFunction &CGF) {
755 CGF.EmitOMPLoopBody(S);
756 CGF.EmitStopPoint(&S);
757 },
758 [](CodeGenFunction &) {});
759 if (SeparateIter) {
760 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000761 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000762 }
763 CGF.EmitOMPSimdFinal(S);
764 // Emit: if (PreCond) - end.
765 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000766 CGF.EmitBranch(ContBlock);
767 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000768 }
769 };
770 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000771}
772
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000773void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
774 const OMPLoopDirective &S,
775 OMPPrivateScope &LoopScope,
776 llvm::Value *LB, llvm::Value *UB,
777 llvm::Value *ST, llvm::Value *IL,
778 llvm::Value *Chunk) {
779 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000780
781 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
782 const bool Dynamic = RT.isDynamic(ScheduleKind);
783
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000784 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
785 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000786
787 // Emit outer loop.
788 //
789 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000790 // When schedule(dynamic,chunk_size) is specified, the iterations are
791 // distributed to threads in the team in chunks as the threads request them.
792 // Each thread executes a chunk of iterations, then requests another chunk,
793 // until no chunks remain to be distributed. Each chunk contains chunk_size
794 // iterations, except for the last chunk to be distributed, which may have
795 // fewer iterations. When no chunk_size is specified, it defaults to 1.
796 //
797 // When schedule(guided,chunk_size) is specified, the iterations are assigned
798 // to threads in the team in chunks as the executing threads request them.
799 // Each thread executes a chunk of iterations, then requests another chunk,
800 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
801 // each chunk is proportional to the number of unassigned iterations divided
802 // by the number of threads in the team, decreasing to 1. For a chunk_size
803 // with value k (greater than 1), the size of each chunk is determined in the
804 // same way, with the restriction that the chunks do not contain fewer than k
805 // iterations (except for the last chunk to be assigned, which may have fewer
806 // than k iterations).
807 //
808 // When schedule(auto) is specified, the decision regarding scheduling is
809 // delegated to the compiler and/or runtime system. The programmer gives the
810 // implementation the freedom to choose any possible mapping of iterations to
811 // threads in the team.
812 //
813 // When schedule(runtime) is specified, the decision regarding scheduling is
814 // deferred until run time, and the schedule and chunk size are taken from the
815 // run-sched-var ICV. If the ICV is set to auto, the schedule is
816 // implementation defined
817 //
818 // while(__kmpc_dispatch_next(&LB, &UB)) {
819 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000820 // while (idx <= UB) { BODY; ++idx;
821 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
822 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000823 // }
824 //
825 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000826 // When schedule(static, chunk_size) is specified, iterations are divided into
827 // chunks of size chunk_size, and the chunks are assigned to the threads in
828 // the team in a round-robin fashion in the order of the thread number.
829 //
830 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
831 // while (idx <= UB) { BODY; ++idx; } // inner loop
832 // LB = LB + ST;
833 // UB = UB + ST;
834 // }
835 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000836
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000837 const Expr *IVExpr = S.getIterationVariable();
838 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
839 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
840
Alexander Musman92bdaab2015-03-12 13:37:50 +0000841 RT.emitForInit(
842 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
843 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
844 Chunk);
845
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000846 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
847
848 // Start the loop with a block that tests the condition.
849 auto CondBlock = createBasicBlock("omp.dispatch.cond");
850 EmitBlock(CondBlock);
851 LoopStack.push(CondBlock);
852
853 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000854 if (!Dynamic) {
855 // UB = min(UB, GlobalUB)
856 EmitIgnoredExpr(S.getEnsureUpperBound());
857 // IV = LB
858 EmitIgnoredExpr(S.getInit());
859 // IV < UB
860 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
861 } else {
862 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
863 IL, LB, UB, ST);
864 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000865
866 // If there are any cleanups between here and the loop-exit scope,
867 // create a block to stage a loop exit along.
868 auto ExitBlock = LoopExit.getBlock();
869 if (LoopScope.requiresCleanups())
870 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
871
872 auto LoopBody = createBasicBlock("omp.dispatch.body");
873 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
874 if (ExitBlock != LoopExit.getBlock()) {
875 EmitBlock(ExitBlock);
876 EmitBranchThroughCleanup(LoopExit);
877 }
878 EmitBlock(LoopBody);
879
Alexander Musman92bdaab2015-03-12 13:37:50 +0000880 // Emit "IV = LB" (in case of static schedule, we have already calculated new
881 // LB for loop condition and emitted it above).
882 if (Dynamic)
883 EmitIgnoredExpr(S.getInit());
884
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000885 // Create a block for the increment.
886 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
887 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
888
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000889 bool DynamicWithOrderedClause =
890 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
891 SourceLocation Loc = S.getLocStart();
892 EmitOMPInnerLoop(
893 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
894 S.getInc(),
895 [&S](CodeGenFunction &CGF) {
896 CGF.EmitOMPLoopBody(S);
897 CGF.EmitStopPoint(&S);
898 },
899 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
900 if (DynamicWithOrderedClause) {
901 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
902 CGF, Loc, IVSize, IVSigned);
903 }
904 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000905
906 EmitBlock(Continue.getBlock());
907 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000908 if (!Dynamic) {
909 // Emit "LB = LB + Stride", "UB = UB + Stride".
910 EmitIgnoredExpr(S.getNextLowerBound());
911 EmitIgnoredExpr(S.getNextUpperBound());
912 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000913
914 EmitBranch(CondBlock);
915 LoopStack.pop();
916 // Emit the fall-through block.
917 EmitBlock(LoopExit.getBlock());
918
919 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000920 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000921 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000922}
923
Alexander Musmanc6388682014-12-15 07:07:06 +0000924/// \brief Emit a helper variable and return corresponding lvalue.
925static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
926 const DeclRefExpr *Helper) {
927 auto VDecl = cast<VarDecl>(Helper->getDecl());
928 CGF.EmitVarDecl(*VDecl);
929 return CGF.EmitLValue(Helper);
930}
931
Alexey Bataev38e89532015-04-16 04:54:05 +0000932bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000933 // Emit the loop iteration variable.
934 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
935 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
936 EmitVarDecl(*IVDecl);
937
938 // Emit the iterations count variable.
939 // If it is not a variable, Sema decided to calculate iterations count on each
940 // iteration (e.g., it is foldable into a constant).
941 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
942 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
943 // Emit calculation of the iterations count.
944 EmitIgnoredExpr(S.getCalcLastIteration());
945 }
946
947 auto &RT = CGM.getOpenMPRuntime();
948
Alexey Bataev38e89532015-04-16 04:54:05 +0000949 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +0000950 // Check pre-condition.
951 {
952 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +0000953 // If the condition constant folds and can be elided, avoid emitting the
954 // whole loop.
955 bool CondConstant;
956 llvm::BasicBlock *ContBlock = nullptr;
957 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
958 if (!CondConstant)
959 return false;
960 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000961 auto *ThenBlock = createBasicBlock("omp.precond.then");
962 ContBlock = createBasicBlock("omp.precond.end");
963 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +0000964 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000965 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000966 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000967 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000968 // Emit 'then' code.
969 {
970 // Emit helper vars inits.
971 LValue LB =
972 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
973 LValue UB =
974 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
975 LValue ST =
976 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
977 LValue IL =
978 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
979
980 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000981 if (EmitOMPFirstprivateClause(S, LoopScope)) {
982 // Emit implicit barrier to synchronize threads and avoid data races on
983 // initialization of firstprivate variables.
984 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
985 OMPD_unknown);
986 }
Alexey Bataev50a64582015-04-22 12:24:45 +0000987 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +0000988 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +0000989 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +0000990 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +0000991 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +0000992
993 // Detect the loop schedule kind and chunk.
994 auto ScheduleKind = OMPC_SCHEDULE_unknown;
995 llvm::Value *Chunk = nullptr;
996 if (auto C = cast_or_null<OMPScheduleClause>(
997 S.getSingleClause(OMPC_schedule))) {
998 ScheduleKind = C->getScheduleKind();
999 if (auto Ch = C->getChunkSize()) {
1000 Chunk = EmitScalarExpr(Ch);
1001 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
1002 S.getIterationVariable()->getType());
1003 }
1004 }
1005 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1006 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1007 if (RT.isStaticNonchunked(ScheduleKind,
1008 /* Chunked */ Chunk != nullptr)) {
1009 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1010 // When no chunk_size is specified, the iteration space is divided into
1011 // chunks that are approximately equal in size, and at most one chunk is
1012 // distributed to each thread. Note that the size of the chunks is
1013 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001014 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1015 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1016 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001017 // UB = min(UB, GlobalUB);
1018 EmitIgnoredExpr(S.getEnsureUpperBound());
1019 // IV = LB;
1020 EmitIgnoredExpr(S.getInit());
1021 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001022 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1023 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001024 [&S](CodeGenFunction &CGF) {
1025 CGF.EmitOMPLoopBody(S);
1026 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001027 },
1028 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001029 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001030 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001031 } else {
1032 // Emit the outer loop, which requests its work chunk [LB..UB] from
1033 // runtime and runs the inner loop to process it.
1034 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1035 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1036 Chunk);
1037 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001038 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001039 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1040 if (HasLastprivateClause)
1041 EmitOMPLastprivateClauseFinal(
1042 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001043 }
1044 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001045 if (ContBlock) {
1046 EmitBranch(ContBlock);
1047 EmitBlock(ContBlock, true);
1048 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001049 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001050 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001051}
1052
1053void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001054 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001055 bool HasLastprivates = false;
1056 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1057 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1058 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001059 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001060
1061 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001062 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001063 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1064 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001066
Alexander Musmanf82886e2014-09-18 05:12:34 +00001067void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1068 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1069}
1070
Alexey Bataev2df54a02015-03-12 08:53:29 +00001071static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1072 const Twine &Name,
1073 llvm::Value *Init = nullptr) {
1074 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1075 if (Init)
1076 CGF.EmitScalarInit(Init, LVal);
1077 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001078}
1079
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001080static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1081 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001082 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1083 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1084 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001085 bool HasLastprivates = false;
1086 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001087 auto &C = CGF.CGM.getContext();
1088 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1089 // Emit helper vars inits.
1090 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1091 CGF.Builder.getInt32(0));
1092 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1093 LValue UB =
1094 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1095 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1096 CGF.Builder.getInt32(1));
1097 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1098 CGF.Builder.getInt32(0));
1099 // Loop counter.
1100 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1101 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001102 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001103 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001104 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001105 // Generate condition for loop.
1106 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1107 OK_Ordinary, S.getLocStart(),
1108 /*fpContractable=*/false);
1109 // Increment for loop counter.
1110 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1111 OK_Ordinary, S.getLocStart());
1112 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1113 // Iterate through all sections and emit a switch construct:
1114 // switch (IV) {
1115 // case 0:
1116 // <SectionStmt[0]>;
1117 // break;
1118 // ...
1119 // case <NumSection> - 1:
1120 // <SectionStmt[<NumSection> - 1]>;
1121 // break;
1122 // }
1123 // .omp.sections.exit:
1124 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1125 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1126 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1127 CS->size());
1128 unsigned CaseNumber = 0;
1129 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1130 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1131 CGF.EmitBlock(CaseBB);
1132 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1133 CGF.EmitStmt(*C);
1134 CGF.EmitBranch(ExitBB);
1135 }
1136 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1137 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001138
1139 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1140 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1141 // Emit implicit barrier to synchronize threads and avoid data races on
1142 // initialization of firstprivate variables.
1143 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1144 OMPD_unknown);
1145 }
Alexey Bataev73870832015-04-27 04:12:12 +00001146 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001147 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001148 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001149 (void)LoopScope.Privatize();
1150
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001151 // Emit static non-chunked loop.
1152 CGF.CGM.getOpenMPRuntime().emitForInit(
1153 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1154 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1155 ST.getAddress());
1156 // UB = min(UB, GlobalUB);
1157 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1158 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1159 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1160 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1161 // IV = LB;
1162 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1163 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001164 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1165 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001166 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001167 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001168 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001169
1170 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1171 if (HasLastprivates)
1172 CGF.EmitOMPLastprivateClauseFinal(
1173 S, CGF.Builder.CreateIsNotNull(
1174 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001175 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001176
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001177 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001178 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1179 // clause. Otherwise the barrier will be generated by the codegen for the
1180 // directive.
1181 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1182 // Emit implicit barrier to synchronize threads and avoid data races on
1183 // initialization of firstprivate variables.
1184 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1185 OMPD_unknown);
1186 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001187 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001188 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001189 // If only one section is found - no need to generate loop, emit as a single
1190 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001191 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001192 // No need to generate reductions for sections with single section region, we
1193 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001194 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001195 // No need to generate lastprivates for sections with single section region,
1196 // we can use original shared variable for all calculations with barrier at
1197 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001198 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001199 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1200 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1201 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001202 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001203 (void)SingleScope.Privatize();
1204
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001205 CGF.EmitStmt(Stmt);
1206 CGF.EnsureInsertPoint();
1207 };
1208 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1209 llvm::None, llvm::None,
1210 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001211 // Emit barrier for firstprivates, lastprivates or reductions only if
1212 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1213 // generated by the codegen for the directive.
1214 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1215 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001216 // Emit implicit barrier to synchronize threads and avoid data races on
1217 // initialization of firstprivate variables.
1218 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1219 OMPD_unknown);
1220 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001221 return OMPD_single;
1222}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001223
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001224void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1225 LexicalScope Scope(*this, S.getSourceRange());
1226 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001227 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001228 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001229 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001230 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001231}
1232
1233void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001234 LexicalScope Scope(*this, S.getSourceRange());
1235 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1236 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1237 CGF.EnsureInsertPoint();
1238 };
1239 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001240}
1241
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001242void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001243 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001244 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001245 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001246 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001247 // Check if there are any 'copyprivate' clauses associated with this
1248 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001249 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001250 // Build a list of copyprivate variables along with helper expressions
1251 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001252 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001253 auto *C = cast<OMPCopyprivateClause>(*I);
1254 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001255 DestExprs.append(C->destination_exprs().begin(),
1256 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001257 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001258 AssignmentOps.append(C->assignment_ops().begin(),
1259 C->assignment_ops().end());
1260 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001261 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001262 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001263 bool HasFirstprivates;
1264 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1265 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1266 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001267 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001268 (void)SingleScope.Privatize();
1269
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001270 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1271 CGF.EnsureInsertPoint();
1272 };
1273 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001274 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001275 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001276 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1277 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1278 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1279 CopyprivateVars.empty()) {
1280 CGM.getOpenMPRuntime().emitBarrierCall(
1281 *this, S.getLocStart(),
1282 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001283 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001284}
1285
Alexey Bataev8d690652014-12-04 07:23:53 +00001286void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001287 LexicalScope Scope(*this, S.getSourceRange());
1288 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1289 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1290 CGF.EnsureInsertPoint();
1291 };
1292 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001293}
1294
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001295void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001296 LexicalScope Scope(*this, S.getSourceRange());
1297 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1298 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1299 CGF.EnsureInsertPoint();
1300 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001301 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001302 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001303}
1304
Alexey Bataev671605e2015-04-13 05:28:11 +00001305void CodeGenFunction::EmitOMPParallelForDirective(
1306 const OMPParallelForDirective &S) {
1307 // Emit directive as a combined directive that consists of two implicit
1308 // directives: 'parallel' with 'for' directive.
1309 LexicalScope Scope(*this, S.getSourceRange());
1310 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1311 CGF.EmitOMPWorksharingLoop(S);
1312 // Emit implicit barrier at the end of parallel region, but this barrier
1313 // is at the end of 'for' directive, so emit it as the implicit barrier for
1314 // this 'for' directive.
1315 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1316 OMPD_parallel);
1317 };
1318 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001319}
1320
Alexander Musmane4e893b2014-09-23 09:33:00 +00001321void CodeGenFunction::EmitOMPParallelForSimdDirective(
1322 const OMPParallelForSimdDirective &) {
1323 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1324}
1325
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001326void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001327 const OMPParallelSectionsDirective &S) {
1328 // Emit directive as a combined directive that consists of two implicit
1329 // directives: 'parallel' with 'sections' directive.
1330 LexicalScope Scope(*this, S.getSourceRange());
1331 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1332 (void)emitSections(CGF, S);
1333 // Emit implicit barrier at the end of parallel region.
1334 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1335 OMPD_parallel);
1336 };
1337 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001338}
1339
Alexey Bataev62b63b12015-03-10 07:28:44 +00001340void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1341 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001342 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001343 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1344 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1345 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001346 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001347 // The first function argument for tasks is a thread id, the second one is a
1348 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001349 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1350 if (*PartId) {
1351 // TODO: emit code for untied tasks.
1352 }
1353 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1354 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001355 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001356 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001357 // Check if we should emit tied or untied task.
1358 bool Tied = !S.getSingleClause(OMPC_untied);
1359 // Check if the task is final
1360 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1361 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1362 // If the condition constant folds and can be elided, try to avoid emitting
1363 // the condition and the dead arm of the if/else.
1364 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1365 bool CondConstant;
1366 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1367 Final.setInt(CondConstant);
1368 else
1369 Final.setPointer(EvaluateExprAsBool(Cond));
1370 } else {
1371 // By default the task is not final.
1372 Final.setInt(/*IntVal=*/false);
1373 }
1374 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001375 const Expr *IfCond = nullptr;
1376 if (auto C = S.getSingleClause(OMPC_if)) {
1377 IfCond = cast<OMPIfClause>(C)->getCondition();
1378 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001379 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001380 OutlinedFn, SharedsTy, CapturedStruct,
1381 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001382}
1383
Alexey Bataev9f797f32015-02-05 05:57:51 +00001384void CodeGenFunction::EmitOMPTaskyieldDirective(
1385 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001386 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001387}
1388
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001389void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001390 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001391}
1392
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001393void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1394 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001395}
1396
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001397void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001398 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1399 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1400 auto FlushClause = cast<OMPFlushClause>(C);
1401 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1402 FlushClause->varlist_end());
1403 }
1404 return llvm::None;
1405 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001406}
1407
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001408void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1409 LexicalScope Scope(*this, S.getSourceRange());
1410 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1411 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1412 CGF.EnsureInsertPoint();
1413 };
1414 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001415}
1416
Alexey Bataevb57056f2015-01-22 06:17:56 +00001417static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1418 QualType SrcType, QualType DestType) {
1419 assert(CGF.hasScalarEvaluationKind(DestType) &&
1420 "DestType must have scalar evaluation kind.");
1421 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1422 return Val.isScalar()
1423 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1424 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1425 DestType);
1426}
1427
1428static CodeGenFunction::ComplexPairTy
1429convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1430 QualType DestType) {
1431 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1432 "DestType must have complex evaluation kind.");
1433 CodeGenFunction::ComplexPairTy ComplexVal;
1434 if (Val.isScalar()) {
1435 // Convert the input element to the element type of the complex.
1436 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1437 auto ScalarVal =
1438 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1439 ComplexVal = CodeGenFunction::ComplexPairTy(
1440 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1441 } else {
1442 assert(Val.isComplex() && "Must be a scalar or complex.");
1443 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1444 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1445 ComplexVal.first = CGF.EmitScalarConversion(
1446 Val.getComplexVal().first, SrcElementType, DestElementType);
1447 ComplexVal.second = CGF.EmitScalarConversion(
1448 Val.getComplexVal().second, SrcElementType, DestElementType);
1449 }
1450 return ComplexVal;
1451}
1452
Alexey Bataev5e018f92015-04-23 06:35:10 +00001453static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1454 LValue LVal, RValue RVal) {
1455 if (LVal.isGlobalReg()) {
1456 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1457 } else {
1458 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1459 : llvm::Monotonic,
1460 LVal.isVolatile(), /*IsInit=*/false);
1461 }
1462}
1463
1464static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1465 QualType RValTy) {
1466 switch (CGF.getEvaluationKind(LVal.getType())) {
1467 case TEK_Scalar:
1468 CGF.EmitStoreThroughLValue(
1469 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1470 LVal);
1471 break;
1472 case TEK_Complex:
1473 CGF.EmitStoreOfComplex(
1474 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1475 /*isInit=*/false);
1476 break;
1477 case TEK_Aggregate:
1478 llvm_unreachable("Must be a scalar or complex.");
1479 }
1480}
1481
Alexey Bataevb57056f2015-01-22 06:17:56 +00001482static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1483 const Expr *X, const Expr *V,
1484 SourceLocation Loc) {
1485 // v = x;
1486 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1487 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1488 LValue XLValue = CGF.EmitLValue(X);
1489 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001490 RValue Res = XLValue.isGlobalReg()
1491 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1492 : CGF.EmitAtomicLoad(XLValue, Loc,
1493 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001494 : llvm::Monotonic,
1495 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001496 // OpenMP, 2.12.6, atomic Construct
1497 // Any atomic construct with a seq_cst clause forces the atomically
1498 // performed operation to include an implicit flush operation without a
1499 // list.
1500 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001501 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001502 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001503}
1504
Alexey Bataevb8329262015-02-27 06:33:30 +00001505static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1506 const Expr *X, const Expr *E,
1507 SourceLocation Loc) {
1508 // x = expr;
1509 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001510 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001511 // OpenMP, 2.12.6, atomic Construct
1512 // Any atomic construct with a seq_cst clause forces the atomically
1513 // performed operation to include an implicit flush operation without a
1514 // list.
1515 if (IsSeqCst)
1516 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1517}
1518
Alexey Bataev5e018f92015-04-23 06:35:10 +00001519std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1520 RValue Update, BinaryOperatorKind BO,
1521 llvm::AtomicOrdering AO,
1522 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001523 auto &Context = CGF.CGM.getContext();
1524 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001525 // expression is simple and atomic is allowed for the given type for the
1526 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001527 if (BO == BO_Comma || !Update.isScalar() ||
1528 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1529 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1530 (Update.getScalarVal()->getType() !=
1531 X.getAddress()->getType()->getPointerElementType())) ||
1532 !Context.getTargetInfo().hasBuiltinAtomic(
1533 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001534 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001535
1536 llvm::AtomicRMWInst::BinOp RMWOp;
1537 switch (BO) {
1538 case BO_Add:
1539 RMWOp = llvm::AtomicRMWInst::Add;
1540 break;
1541 case BO_Sub:
1542 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001543 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001544 RMWOp = llvm::AtomicRMWInst::Sub;
1545 break;
1546 case BO_And:
1547 RMWOp = llvm::AtomicRMWInst::And;
1548 break;
1549 case BO_Or:
1550 RMWOp = llvm::AtomicRMWInst::Or;
1551 break;
1552 case BO_Xor:
1553 RMWOp = llvm::AtomicRMWInst::Xor;
1554 break;
1555 case BO_LT:
1556 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1557 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1558 : llvm::AtomicRMWInst::Max)
1559 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1560 : llvm::AtomicRMWInst::UMax);
1561 break;
1562 case BO_GT:
1563 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1564 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1565 : llvm::AtomicRMWInst::Min)
1566 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1567 : llvm::AtomicRMWInst::UMin);
1568 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001569 case BO_Assign:
1570 RMWOp = llvm::AtomicRMWInst::Xchg;
1571 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001572 case BO_Mul:
1573 case BO_Div:
1574 case BO_Rem:
1575 case BO_Shl:
1576 case BO_Shr:
1577 case BO_LAnd:
1578 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001579 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001580 case BO_PtrMemD:
1581 case BO_PtrMemI:
1582 case BO_LE:
1583 case BO_GE:
1584 case BO_EQ:
1585 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001586 case BO_AddAssign:
1587 case BO_SubAssign:
1588 case BO_AndAssign:
1589 case BO_OrAssign:
1590 case BO_XorAssign:
1591 case BO_MulAssign:
1592 case BO_DivAssign:
1593 case BO_RemAssign:
1594 case BO_ShlAssign:
1595 case BO_ShrAssign:
1596 case BO_Comma:
1597 llvm_unreachable("Unsupported atomic update operation");
1598 }
1599 auto *UpdateVal = Update.getScalarVal();
1600 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1601 UpdateVal = CGF.Builder.CreateIntCast(
1602 IC, X.getAddress()->getType()->getPointerElementType(),
1603 X.getType()->hasSignedIntegerRepresentation());
1604 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001605 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1606 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001607}
1608
Alexey Bataev5e018f92015-04-23 06:35:10 +00001609std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001610 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1611 llvm::AtomicOrdering AO, SourceLocation Loc,
1612 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1613 // Update expressions are allowed to have the following forms:
1614 // x binop= expr; -> xrval + expr;
1615 // x++, ++x -> xrval + 1;
1616 // x--, --x -> xrval - 1;
1617 // x = x binop expr; -> xrval binop expr
1618 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001619 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1620 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001621 if (X.isGlobalReg()) {
1622 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1623 // 'xrval'.
1624 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1625 } else {
1626 // Perform compare-and-swap procedure.
1627 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001628 }
1629 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001630 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001631}
1632
1633static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1634 const Expr *X, const Expr *E,
1635 const Expr *UE, bool IsXLHSInRHSPart,
1636 SourceLocation Loc) {
1637 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1638 "Update expr in 'atomic update' must be a binary operator.");
1639 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1640 // Update expressions are allowed to have the following forms:
1641 // x binop= expr; -> xrval + expr;
1642 // x++, ++x -> xrval + 1;
1643 // x--, --x -> xrval - 1;
1644 // x = x binop expr; -> xrval binop expr
1645 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001646 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001647 LValue XLValue = CGF.EmitLValue(X);
1648 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001649 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001650 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1651 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1652 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1653 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1654 auto Gen =
1655 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1656 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1657 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1658 return CGF.EmitAnyExpr(UE);
1659 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001660 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1661 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1662 // OpenMP, 2.12.6, atomic Construct
1663 // Any atomic construct with a seq_cst clause forces the atomically
1664 // performed operation to include an implicit flush operation without a
1665 // list.
1666 if (IsSeqCst)
1667 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1668}
1669
1670static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1671 QualType SourceType, QualType ResType) {
1672 switch (CGF.getEvaluationKind(ResType)) {
1673 case TEK_Scalar:
1674 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1675 case TEK_Complex: {
1676 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1677 return RValue::getComplex(Res.first, Res.second);
1678 }
1679 case TEK_Aggregate:
1680 break;
1681 }
1682 llvm_unreachable("Must be a scalar or complex.");
1683}
1684
1685static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1686 bool IsPostfixUpdate, const Expr *V,
1687 const Expr *X, const Expr *E,
1688 const Expr *UE, bool IsXLHSInRHSPart,
1689 SourceLocation Loc) {
1690 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1691 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1692 RValue NewVVal;
1693 LValue VLValue = CGF.EmitLValue(V);
1694 LValue XLValue = CGF.EmitLValue(X);
1695 RValue ExprRValue = CGF.EmitAnyExpr(E);
1696 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1697 QualType NewVValType;
1698 if (UE) {
1699 // 'x' is updated with some additional value.
1700 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1701 "Update expr in 'atomic capture' must be a binary operator.");
1702 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1703 // Update expressions are allowed to have the following forms:
1704 // x binop= expr; -> xrval + expr;
1705 // x++, ++x -> xrval + 1;
1706 // x--, --x -> xrval - 1;
1707 // x = x binop expr; -> xrval binop expr
1708 // x = expr Op x; - > expr binop xrval;
1709 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1710 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1711 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1712 NewVValType = XRValExpr->getType();
1713 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1714 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1715 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1716 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1717 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1718 RValue Res = CGF.EmitAnyExpr(UE);
1719 NewVVal = IsPostfixUpdate ? XRValue : Res;
1720 return Res;
1721 };
1722 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1723 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1724 if (Res.first) {
1725 // 'atomicrmw' instruction was generated.
1726 if (IsPostfixUpdate) {
1727 // Use old value from 'atomicrmw'.
1728 NewVVal = Res.second;
1729 } else {
1730 // 'atomicrmw' does not provide new value, so evaluate it using old
1731 // value of 'x'.
1732 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1733 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1734 NewVVal = CGF.EmitAnyExpr(UE);
1735 }
1736 }
1737 } else {
1738 // 'x' is simply rewritten with some 'expr'.
1739 NewVValType = X->getType().getNonReferenceType();
1740 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1741 X->getType().getNonReferenceType());
1742 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1743 NewVVal = XRValue;
1744 return ExprRValue;
1745 };
1746 // Try to perform atomicrmw xchg, otherwise simple exchange.
1747 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1748 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1749 Loc, Gen);
1750 if (Res.first) {
1751 // 'atomicrmw' instruction was generated.
1752 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1753 }
1754 }
1755 // Emit post-update store to 'v' of old/new 'x' value.
1756 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001757 // OpenMP, 2.12.6, atomic Construct
1758 // Any atomic construct with a seq_cst clause forces the atomically
1759 // performed operation to include an implicit flush operation without a
1760 // list.
1761 if (IsSeqCst)
1762 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1763}
1764
Alexey Bataevb57056f2015-01-22 06:17:56 +00001765static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001766 bool IsSeqCst, bool IsPostfixUpdate,
1767 const Expr *X, const Expr *V, const Expr *E,
1768 const Expr *UE, bool IsXLHSInRHSPart,
1769 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001770 switch (Kind) {
1771 case OMPC_read:
1772 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1773 break;
1774 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001775 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1776 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001777 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001778 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001779 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1780 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001781 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001782 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1783 IsXLHSInRHSPart, Loc);
1784 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001785 case OMPC_if:
1786 case OMPC_final:
1787 case OMPC_num_threads:
1788 case OMPC_private:
1789 case OMPC_firstprivate:
1790 case OMPC_lastprivate:
1791 case OMPC_reduction:
1792 case OMPC_safelen:
1793 case OMPC_collapse:
1794 case OMPC_default:
1795 case OMPC_seq_cst:
1796 case OMPC_shared:
1797 case OMPC_linear:
1798 case OMPC_aligned:
1799 case OMPC_copyin:
1800 case OMPC_copyprivate:
1801 case OMPC_flush:
1802 case OMPC_proc_bind:
1803 case OMPC_schedule:
1804 case OMPC_ordered:
1805 case OMPC_nowait:
1806 case OMPC_untied:
1807 case OMPC_threadprivate:
1808 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001809 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1810 }
1811}
1812
1813void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1814 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1815 OpenMPClauseKind Kind = OMPC_unknown;
1816 for (auto *C : S.clauses()) {
1817 // Find first clause (skip seq_cst clause, if it is first).
1818 if (C->getClauseKind() != OMPC_seq_cst) {
1819 Kind = C->getClauseKind();
1820 break;
1821 }
1822 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001823
1824 const auto *CS =
1825 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001826 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001827 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001828 }
1829 // Processing for statements under 'atomic capture'.
1830 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1831 for (const auto *C : Compound->body()) {
1832 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1833 enterFullExpression(EWC);
1834 }
1835 }
1836 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001837
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001838 LexicalScope Scope(*this, S.getSourceRange());
1839 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001840 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1841 S.getV(), S.getExpr(), S.getUpdateExpr(),
1842 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001843 };
1844 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001845}
1846
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001847void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1848 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1849}
1850
Alexey Bataev13314bf2014-10-09 04:18:56 +00001851void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1852 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1853}