blob: 6a4b5ecaa36fdc2e0570db6b95ecad6b579f9912 [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());
Alexey Bataev61114692015-04-28 13:20:05 +0000581 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000582 // Emit var without initialization.
583 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
584 CGF.EmitAutoVarCleanups(VarEmission);
585 return VarEmission.getAllocatedAddress();
586 });
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000587 }
Alexey Bataev435ad7b2014-10-10 09:48:26 +0000588}
589
Alexey Bataev62dbb972015-04-22 11:59:37 +0000590static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
591 const Expr *Cond, llvm::BasicBlock *TrueBlock,
592 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
593 CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
594 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters());
595 const VarDecl *IVDecl =
596 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl());
597 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{
598 // Emit var without initialization.
599 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl);
600 CGF.EmitAutoVarCleanups(VarEmission);
601 return VarEmission.getAllocatedAddress();
602 });
603 assert(IsRegistered && "counter already registered as private");
604 // Silence the warning about unused variable.
605 (void)IsRegistered;
606 (void)PreCondScope.Privatize();
607 // Initialize internal counter to 0 to calculate initial values of real
608 // counters.
609 LValue IV = CGF.EmitLValue(S.getIterationVariable());
610 CGF.EmitStoreOfScalar(
611 llvm::ConstantInt::getNullValue(
612 IV.getAddress()->getType()->getPointerElementType()),
613 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true);
614 // Get initial values of real counters.
615 for (auto I : S.updates()) {
616 CGF.EmitIgnoredExpr(I);
617 }
618 // Check that loop is executed at least one time.
619 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
620}
621
Alexander Musman3276a272015-03-21 10:12:56 +0000622static void
623EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D,
624 CodeGenFunction::OMPPrivateScope &PrivateScope) {
Alexey Bataevc925aa32015-04-27 08:00:32 +0000625 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) {
626 auto *C = cast<OMPLinearClause>(*I);
627 for (auto *E : C->varlists()) {
Alexander Musman3276a272015-03-21 10:12:56 +0000628 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
629 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * {
630 // Emit var without initialization.
631 auto VarEmission = CGF.EmitAutoVarAlloca(*VD);
632 CGF.EmitAutoVarCleanups(VarEmission);
633 return VarEmission.getAllocatedAddress();
634 });
635 assert(IsRegistered && "linear var already registered as private");
636 // Silence the warning about unused variable.
637 (void)IsRegistered;
638 }
639 }
640}
641
Alexander Musman515ad8c2014-05-22 08:54:05 +0000642void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000643 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
644 // Pragma 'simd' code depends on presence of 'lastprivate'.
645 // If present, we have to separate last iteration of the loop:
646 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000647 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000648 // for (IV in 0..LastIteration-1) BODY;
649 // BODY with updates of lastprivate vars;
650 // <Final counter/linear vars updates>;
651 // }
652 //
653 // otherwise (when there's no lastprivate):
654 //
Alexey Bataev62dbb972015-04-22 11:59:37 +0000655 // if (PreCond) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000656 // for (IV in 0..LastIteration) BODY;
657 // <Final counter/linear vars updates>;
Alexey Bataev62dbb972015-04-22 11:59:37 +0000658 // }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000659 //
Alexander Musmana5f070a2014-10-01 06:03:56 +0000660
Alexey Bataev62dbb972015-04-22 11:59:37 +0000661 // Emit: if (PreCond) - begin.
662 // If the condition constant folds and can be elided, avoid emitting the
663 // whole loop.
664 bool CondConstant;
665 llvm::BasicBlock *ContBlock = nullptr;
666 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
667 if (!CondConstant)
668 return;
669 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000670 auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
671 ContBlock = CGF.createBasicBlock("simd.if.end");
Justin Bogner66242d62015-04-23 23:06:47 +0000672 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
673 CGF.getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000674 CGF.EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000675 CGF.incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000676 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000677 // Walk clauses and process safelen/lastprivate.
678 bool SeparateIter = false;
679 CGF.LoopStack.setParallel();
680 CGF.LoopStack.setVectorizerEnable(true);
681 for (auto C : S.clauses()) {
682 switch (C->getClauseKind()) {
683 case OMPC_safelen: {
684 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(),
685 AggValueSlot::ignored(), true);
686 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
687 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue());
688 // In presence of finite 'safelen', it may be unsafe to mark all
689 // the memory instructions parallel, because loop-carried
690 // dependences of 'safelen' iterations are possible.
691 CGF.LoopStack.setParallel(false);
692 break;
Alexander Musman3276a272015-03-21 10:12:56 +0000693 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000694 case OMPC_aligned:
695 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C));
696 break;
697 case OMPC_lastprivate:
698 SeparateIter = true;
699 break;
700 default:
701 // Not handled yet
702 ;
703 }
704 }
Alexander Musman3276a272015-03-21 10:12:56 +0000705
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000706 // Emit inits for the linear variables.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000707 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
708 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000709 for (auto Init : C->inits()) {
710 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
711 CGF.EmitVarDecl(*D);
712 }
Alexander Musmana5f070a2014-10-01 06:03:56 +0000713 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000714
715 // Emit the loop iteration variable.
716 const Expr *IVExpr = S.getIterationVariable();
717 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
718 CGF.EmitVarDecl(*IVDecl);
719 CGF.EmitIgnoredExpr(S.getInit());
720
721 // Emit the iterations count variable.
722 // If it is not a variable, Sema decided to calculate iterations count on
723 // each
724 // iteration (e.g., it is foldable into a constant).
725 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
726 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
727 // Emit calculation of the iterations count.
728 CGF.EmitIgnoredExpr(S.getCalcLastIteration());
Alexander Musmana5f070a2014-10-01 06:03:56 +0000729 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000730
731 // Emit the linear steps for the linear clauses.
732 // If a step is not constant, it is pre-calculated before the loop.
Alexey Bataevc925aa32015-04-27 08:00:32 +0000733 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) {
734 auto *C = cast<OMPLinearClause>(*I);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000735 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
736 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
737 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
738 // Emit calculation of the linear step.
739 CGF.EmitIgnoredExpr(CS);
740 }
741 }
742
Alexey Bataev62dbb972015-04-22 11:59:37 +0000743 {
744 OMPPrivateScope LoopScope(CGF);
745 EmitPrivateLoopCounters(CGF, LoopScope, S.counters());
746 EmitPrivateLinearVars(CGF, S, LoopScope);
747 CGF.EmitOMPPrivateClause(S, LoopScope);
748 (void)LoopScope.Privatize();
749 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
750 S.getCond(SeparateIter), S.getInc(),
751 [&S](CodeGenFunction &CGF) {
752 CGF.EmitOMPLoopBody(S);
753 CGF.EmitStopPoint(&S);
754 },
755 [](CodeGenFunction &) {});
756 if (SeparateIter) {
757 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000758 }
Alexey Bataev62dbb972015-04-22 11:59:37 +0000759 }
760 CGF.EmitOMPSimdFinal(S);
761 // Emit: if (PreCond) - end.
762 if (ContBlock) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000763 CGF.EmitBranch(ContBlock);
764 CGF.EmitBlock(ContBlock, true);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000765 }
766 };
767 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musman515ad8c2014-05-22 08:54:05 +0000768}
769
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000770void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
771 const OMPLoopDirective &S,
772 OMPPrivateScope &LoopScope,
773 llvm::Value *LB, llvm::Value *UB,
774 llvm::Value *ST, llvm::Value *IL,
775 llvm::Value *Chunk) {
776 auto &RT = CGM.getOpenMPRuntime();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000777
778 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
779 const bool Dynamic = RT.isDynamic(ScheduleKind);
780
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000781 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) &&
782 "static non-chunked schedule does not need outer loop");
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000783
784 // Emit outer loop.
785 //
786 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musman92bdaab2015-03-12 13:37:50 +0000787 // When schedule(dynamic,chunk_size) is specified, the iterations are
788 // distributed to threads in the team in chunks as the threads request them.
789 // Each thread executes a chunk of iterations, then requests another chunk,
790 // until no chunks remain to be distributed. Each chunk contains chunk_size
791 // iterations, except for the last chunk to be distributed, which may have
792 // fewer iterations. When no chunk_size is specified, it defaults to 1.
793 //
794 // When schedule(guided,chunk_size) is specified, the iterations are assigned
795 // to threads in the team in chunks as the executing threads request them.
796 // Each thread executes a chunk of iterations, then requests another chunk,
797 // until no chunks remain to be assigned. For a chunk_size of 1, the size of
798 // each chunk is proportional to the number of unassigned iterations divided
799 // by the number of threads in the team, decreasing to 1. For a chunk_size
800 // with value k (greater than 1), the size of each chunk is determined in the
801 // same way, with the restriction that the chunks do not contain fewer than k
802 // iterations (except for the last chunk to be assigned, which may have fewer
803 // than k iterations).
804 //
805 // When schedule(auto) is specified, the decision regarding scheduling is
806 // delegated to the compiler and/or runtime system. The programmer gives the
807 // implementation the freedom to choose any possible mapping of iterations to
808 // threads in the team.
809 //
810 // When schedule(runtime) is specified, the decision regarding scheduling is
811 // deferred until run time, and the schedule and chunk size are taken from the
812 // run-sched-var ICV. If the ICV is set to auto, the schedule is
813 // implementation defined
814 //
815 // while(__kmpc_dispatch_next(&LB, &UB)) {
816 // idx = LB;
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000817 // while (idx <= UB) { BODY; ++idx;
818 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
819 // } // inner loop
Alexander Musman92bdaab2015-03-12 13:37:50 +0000820 // }
821 //
822 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000823 // When schedule(static, chunk_size) is specified, iterations are divided into
824 // chunks of size chunk_size, and the chunks are assigned to the threads in
825 // the team in a round-robin fashion in the order of the thread number.
826 //
827 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
828 // while (idx <= UB) { BODY; ++idx; } // inner loop
829 // LB = LB + ST;
830 // UB = UB + ST;
831 // }
832 //
Alexander Musman92bdaab2015-03-12 13:37:50 +0000833
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000834 const Expr *IVExpr = S.getIterationVariable();
835 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
836 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
837
Alexander Musman92bdaab2015-03-12 13:37:50 +0000838 RT.emitForInit(
839 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB,
840 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST,
841 Chunk);
842
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000843 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
844
845 // Start the loop with a block that tests the condition.
846 auto CondBlock = createBasicBlock("omp.dispatch.cond");
847 EmitBlock(CondBlock);
848 LoopStack.push(CondBlock);
849
850 llvm::Value *BoolCondVal = nullptr;
Alexander Musman92bdaab2015-03-12 13:37:50 +0000851 if (!Dynamic) {
852 // UB = min(UB, GlobalUB)
853 EmitIgnoredExpr(S.getEnsureUpperBound());
854 // IV = LB
855 EmitIgnoredExpr(S.getInit());
856 // IV < UB
857 BoolCondVal = EvaluateExprAsBool(S.getCond(false));
858 } else {
859 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned,
860 IL, LB, UB, ST);
861 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000862
863 // If there are any cleanups between here and the loop-exit scope,
864 // create a block to stage a loop exit along.
865 auto ExitBlock = LoopExit.getBlock();
866 if (LoopScope.requiresCleanups())
867 ExitBlock = createBasicBlock("omp.dispatch.cleanup");
868
869 auto LoopBody = createBasicBlock("omp.dispatch.body");
870 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
871 if (ExitBlock != LoopExit.getBlock()) {
872 EmitBlock(ExitBlock);
873 EmitBranchThroughCleanup(LoopExit);
874 }
875 EmitBlock(LoopBody);
876
Alexander Musman92bdaab2015-03-12 13:37:50 +0000877 // Emit "IV = LB" (in case of static schedule, we have already calculated new
878 // LB for loop condition and emitted it above).
879 if (Dynamic)
880 EmitIgnoredExpr(S.getInit());
881
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000882 // Create a block for the increment.
883 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
884 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
885
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000886 bool DynamicWithOrderedClause =
887 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr;
888 SourceLocation Loc = S.getLocStart();
889 EmitOMPInnerLoop(
890 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false),
891 S.getInc(),
892 [&S](CodeGenFunction &CGF) {
893 CGF.EmitOMPLoopBody(S);
894 CGF.EmitStopPoint(&S);
895 },
896 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) {
897 if (DynamicWithOrderedClause) {
898 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd(
899 CGF, Loc, IVSize, IVSigned);
900 }
901 });
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000902
903 EmitBlock(Continue.getBlock());
904 BreakContinueStack.pop_back();
Alexander Musman92bdaab2015-03-12 13:37:50 +0000905 if (!Dynamic) {
906 // Emit "LB = LB + Stride", "UB = UB + Stride".
907 EmitIgnoredExpr(S.getNextLowerBound());
908 EmitIgnoredExpr(S.getNextUpperBound());
909 }
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000910
911 EmitBranch(CondBlock);
912 LoopStack.pop();
913 // Emit the fall-through block.
914 EmitBlock(LoopExit.getBlock());
915
916 // Tell the runtime we are done.
Alexander Musman92bdaab2015-03-12 13:37:50 +0000917 if (!Dynamic)
Alexey Bataev98eb6e32015-04-22 11:15:40 +0000918 RT.emitForStaticFinish(*this, S.getLocEnd());
Alexander Musmandf7a8e22015-01-22 08:49:35 +0000919}
920
Alexander Musmanc6388682014-12-15 07:07:06 +0000921/// \brief Emit a helper variable and return corresponding lvalue.
922static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
923 const DeclRefExpr *Helper) {
924 auto VDecl = cast<VarDecl>(Helper->getDecl());
925 CGF.EmitVarDecl(*VDecl);
926 return CGF.EmitLValue(Helper);
927}
928
Alexey Bataev38e89532015-04-16 04:54:05 +0000929bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) {
Alexander Musmanc6388682014-12-15 07:07:06 +0000930 // Emit the loop iteration variable.
931 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
932 auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
933 EmitVarDecl(*IVDecl);
934
935 // Emit the iterations count variable.
936 // If it is not a variable, Sema decided to calculate iterations count on each
937 // iteration (e.g., it is foldable into a constant).
938 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
939 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
940 // Emit calculation of the iterations count.
941 EmitIgnoredExpr(S.getCalcLastIteration());
942 }
943
944 auto &RT = CGM.getOpenMPRuntime();
945
Alexey Bataev38e89532015-04-16 04:54:05 +0000946 bool HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +0000947 // Check pre-condition.
948 {
949 // Skip the entire loop if we don't meet the precondition.
Alexey Bataev62dbb972015-04-22 11:59:37 +0000950 // If the condition constant folds and can be elided, avoid emitting the
951 // whole loop.
952 bool CondConstant;
953 llvm::BasicBlock *ContBlock = nullptr;
954 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
955 if (!CondConstant)
956 return false;
957 } else {
Alexey Bataev62dbb972015-04-22 11:59:37 +0000958 auto *ThenBlock = createBasicBlock("omp.precond.then");
959 ContBlock = createBasicBlock("omp.precond.end");
960 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
Justin Bogner66242d62015-04-23 23:06:47 +0000961 getProfileCount(&S));
Alexey Bataev62dbb972015-04-22 11:59:37 +0000962 EmitBlock(ThenBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000963 incrementProfileCounter(&S);
Alexey Bataev62dbb972015-04-22 11:59:37 +0000964 }
Alexander Musmanc6388682014-12-15 07:07:06 +0000965 // Emit 'then' code.
966 {
967 // Emit helper vars inits.
968 LValue LB =
969 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable()));
970 LValue UB =
971 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable()));
972 LValue ST =
973 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
974 LValue IL =
975 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
976
977 OMPPrivateScope LoopScope(*this);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000978 if (EmitOMPFirstprivateClause(S, LoopScope)) {
979 // Emit implicit barrier to synchronize threads and avoid data races on
980 // initialization of firstprivate variables.
981 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
982 OMPD_unknown);
983 }
Alexey Bataev50a64582015-04-22 12:24:45 +0000984 EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev38e89532015-04-16 04:54:05 +0000985 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +0000986 EmitOMPReductionClauseInit(S, LoopScope);
Alexander Musmanc6388682014-12-15 07:07:06 +0000987 EmitPrivateLoopCounters(*this, LoopScope, S.counters());
Alexander Musman7931b982015-03-16 07:14:41 +0000988 (void)LoopScope.Privatize();
Alexander Musmanc6388682014-12-15 07:07:06 +0000989
990 // Detect the loop schedule kind and chunk.
991 auto ScheduleKind = OMPC_SCHEDULE_unknown;
992 llvm::Value *Chunk = nullptr;
993 if (auto C = cast_or_null<OMPScheduleClause>(
994 S.getSingleClause(OMPC_schedule))) {
995 ScheduleKind = C->getScheduleKind();
996 if (auto Ch = C->getChunkSize()) {
997 Chunk = EmitScalarExpr(Ch);
998 Chunk = EmitScalarConversion(Chunk, Ch->getType(),
999 S.getIterationVariable()->getType());
1000 }
1001 }
1002 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
1003 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
1004 if (RT.isStaticNonchunked(ScheduleKind,
1005 /* Chunked */ Chunk != nullptr)) {
1006 // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
1007 // When no chunk_size is specified, the iteration space is divided into
1008 // chunks that are approximately equal in size, and at most one chunk is
1009 // distributed to each thread. Note that the size of the chunks is
1010 // unspecified in this case.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001011 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
1012 IL.getAddress(), LB.getAddress(), UB.getAddress(),
1013 ST.getAddress());
Alexander Musmanc6388682014-12-15 07:07:06 +00001014 // UB = min(UB, GlobalUB);
1015 EmitIgnoredExpr(S.getEnsureUpperBound());
1016 // IV = LB;
1017 EmitIgnoredExpr(S.getInit());
1018 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001019 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(),
1020 S.getCond(/*SeparateIter=*/false), S.getInc(),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001021 [&S](CodeGenFunction &CGF) {
1022 CGF.EmitOMPLoopBody(S);
1023 CGF.EmitStopPoint(&S);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001024 },
1025 [](CodeGenFunction &) {});
Alexander Musmanc6388682014-12-15 07:07:06 +00001026 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001027 RT.emitForStaticFinish(*this, S.getLocStart());
Alexander Musmandf7a8e22015-01-22 08:49:35 +00001028 } else {
1029 // Emit the outer loop, which requests its work chunk [LB..UB] from
1030 // runtime and runs the inner loop to process it.
1031 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(),
1032 UB.getAddress(), ST.getAddress(), IL.getAddress(),
1033 Chunk);
1034 }
Alexey Bataev7ebe5fd2015-04-22 13:43:03 +00001035 EmitOMPReductionClauseFinal(S);
Alexey Bataev38e89532015-04-16 04:54:05 +00001036 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1037 if (HasLastprivateClause)
1038 EmitOMPLastprivateClauseFinal(
1039 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
Alexander Musmanc6388682014-12-15 07:07:06 +00001040 }
1041 // We're now done with the loop, so jump to the continuation block.
Alexey Bataev62dbb972015-04-22 11:59:37 +00001042 if (ContBlock) {
1043 EmitBranch(ContBlock);
1044 EmitBlock(ContBlock, true);
1045 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001046 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001047 return HasLastprivateClause;
Alexander Musmanc6388682014-12-15 07:07:06 +00001048}
1049
1050void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001051 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev38e89532015-04-16 04:54:05 +00001052 bool HasLastprivates = false;
1053 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) {
1054 HasLastprivates = CGF.EmitOMPWorksharingLoop(S);
1055 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001056 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexander Musmanc6388682014-12-15 07:07:06 +00001057
1058 // Emit an implicit barrier at the end.
Alexey Bataev38e89532015-04-16 04:54:05 +00001059 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001060 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
1061 }
Alexey Bataevf29276e2014-06-18 04:14:57 +00001062}
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001063
Alexander Musmanf82886e2014-09-18 05:12:34 +00001064void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) {
1065 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet.");
1066}
1067
Alexey Bataev2df54a02015-03-12 08:53:29 +00001068static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
1069 const Twine &Name,
1070 llvm::Value *Init = nullptr) {
1071 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
1072 if (Init)
1073 CGF.EmitScalarInit(Init, LVal);
1074 return LVal;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001075}
1076
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001077static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF,
1078 const OMPExecutableDirective &S) {
Alexey Bataev2df54a02015-03-12 08:53:29 +00001079 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
1080 auto *CS = dyn_cast<CompoundStmt>(Stmt);
1081 if (CS && CS->size() > 1) {
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001082 bool HasLastprivates = false;
1083 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001084 auto &C = CGF.CGM.getContext();
1085 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1086 // Emit helper vars inits.
1087 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
1088 CGF.Builder.getInt32(0));
1089 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1);
1090 LValue UB =
1091 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
1092 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
1093 CGF.Builder.getInt32(1));
1094 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
1095 CGF.Builder.getInt32(0));
1096 // Loop counter.
1097 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
1098 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001099 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001100 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001101 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001102 // Generate condition for loop.
1103 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
1104 OK_Ordinary, S.getLocStart(),
1105 /*fpContractable=*/false);
1106 // Increment for loop counter.
1107 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue,
1108 OK_Ordinary, S.getLocStart());
1109 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) {
1110 // Iterate through all sections and emit a switch construct:
1111 // switch (IV) {
1112 // case 0:
1113 // <SectionStmt[0]>;
1114 // break;
1115 // ...
1116 // case <NumSection> - 1:
1117 // <SectionStmt[<NumSection> - 1]>;
1118 // break;
1119 // }
1120 // .omp.sections.exit:
1121 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
1122 auto *SwitchStmt = CGF.Builder.CreateSwitch(
1123 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
1124 CS->size());
1125 unsigned CaseNumber = 0;
1126 for (auto C = CS->children(); C; ++C, ++CaseNumber) {
1127 auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
1128 CGF.EmitBlock(CaseBB);
1129 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
1130 CGF.EmitStmt(*C);
1131 CGF.EmitBranch(ExitBB);
1132 }
1133 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1134 };
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001135
1136 CodeGenFunction::OMPPrivateScope LoopScope(CGF);
1137 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
1138 // Emit implicit barrier to synchronize threads and avoid data races on
1139 // initialization of firstprivate variables.
1140 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1141 OMPD_unknown);
1142 }
Alexey Bataev73870832015-04-27 04:12:12 +00001143 CGF.EmitOMPPrivateClause(S, LoopScope);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001144 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001145 CGF.EmitOMPReductionClauseInit(S, LoopScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001146 (void)LoopScope.Privatize();
1147
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001148 // Emit static non-chunked loop.
1149 CGF.CGM.getOpenMPRuntime().emitForInit(
1150 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32,
1151 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(),
1152 ST.getAddress());
1153 // UB = min(UB, GlobalUB);
1154 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
1155 auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
1156 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
1157 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
1158 // IV = LB;
1159 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
1160 // while (idx <= UB) { BODY; ++idx; }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001161 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
1162 [](CodeGenFunction &) {});
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001163 // Tell the runtime we are done.
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001164 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart());
Alexey Bataeva89adf22015-04-27 05:04:13 +00001165 CGF.EmitOMPReductionClauseFinal(S);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001166
1167 // Emit final copy of the lastprivate variables if IsLastIter != 0.
1168 if (HasLastprivates)
1169 CGF.EmitOMPLastprivateClauseFinal(
1170 S, CGF.Builder.CreateIsNotNull(
1171 CGF.EmitLoadOfScalar(IL, S.getLocStart())));
Alexey Bataev2df54a02015-03-12 08:53:29 +00001172 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001173
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001174 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen);
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001175 // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
1176 // clause. Otherwise the barrier will be generated by the codegen for the
1177 // directive.
1178 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) {
1179 // Emit implicit barrier to synchronize threads and avoid data races on
1180 // initialization of firstprivate variables.
1181 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1182 OMPD_unknown);
1183 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001184 return OMPD_sections;
Alexey Bataev2df54a02015-03-12 08:53:29 +00001185 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001186 // If only one section is found - no need to generate loop, emit as a single
1187 // region.
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001188 bool HasFirstprivates;
Alexey Bataeva89adf22015-04-27 05:04:13 +00001189 // No need to generate reductions for sections with single section region, we
1190 // can use original shared variables for all operations.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001191 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty();
Alexey Bataev9efc03b2015-04-27 04:34:03 +00001192 // No need to generate lastprivates for sections with single section region,
1193 // we can use original shared variable for all calculations with barrier at
1194 // the end of the sections.
Alexey Bataevc925aa32015-04-27 08:00:32 +00001195 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty();
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001196 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) {
1197 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1198 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev73870832015-04-27 04:12:12 +00001199 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001200 (void)SingleScope.Privatize();
1201
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001202 CGF.EmitStmt(Stmt);
1203 CGF.EnsureInsertPoint();
1204 };
1205 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(),
1206 llvm::None, llvm::None,
1207 llvm::None, llvm::None);
Alexey Bataeva89adf22015-04-27 05:04:13 +00001208 // Emit barrier for firstprivates, lastprivates or reductions only if
1209 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be
1210 // generated by the codegen for the directive.
1211 if ((HasFirstprivates || HasLastprivates || HasReductions) &&
1212 S.getSingleClause(OMPC_nowait)) {
Alexey Bataev2cb9b952015-04-24 03:37:03 +00001213 // Emit implicit barrier to synchronize threads and avoid data races on
1214 // initialization of firstprivate variables.
1215 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1216 OMPD_unknown);
1217 }
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001218 return OMPD_single;
1219}
Alexey Bataev2df54a02015-03-12 08:53:29 +00001220
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001221void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
1222 LexicalScope Scope(*this, S.getSourceRange());
1223 OpenMPDirectiveKind EmittedAs = emitSections(*this, S);
Alexey Bataev2df54a02015-03-12 08:53:29 +00001224 // Emit an implicit barrier at the end.
Alexey Bataevf2685682015-03-30 04:30:22 +00001225 if (!S.getSingleClause(OMPC_nowait)) {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001226 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs);
Alexey Bataevf2685682015-03-30 04:30:22 +00001227 }
Alexey Bataev2df54a02015-03-12 08:53:29 +00001228}
1229
1230void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001231 LexicalScope Scope(*this, S.getSourceRange());
1232 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1233 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1234 CGF.EnsureInsertPoint();
1235 };
1236 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001237}
1238
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001239void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001240 llvm::SmallVector<const Expr *, 8> CopyprivateVars;
Alexey Bataev420d45b2015-04-14 05:11:24 +00001241 llvm::SmallVector<const Expr *, 8> DestExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001242 llvm::SmallVector<const Expr *, 8> SrcExprs;
Alexey Bataeva63048e2015-03-23 06:18:07 +00001243 llvm::SmallVector<const Expr *, 8> AssignmentOps;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001244 // Check if there are any 'copyprivate' clauses associated with this
1245 // 'single'
Alexey Bataeva63048e2015-03-23 06:18:07 +00001246 // construct.
Alexey Bataeva63048e2015-03-23 06:18:07 +00001247 // Build a list of copyprivate variables along with helper expressions
1248 // (<source>, <destination>, <destination>=<source> expressions)
Alexey Bataevc925aa32015-04-27 08:00:32 +00001249 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00001250 auto *C = cast<OMPCopyprivateClause>(*I);
1251 CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
Alexey Bataev420d45b2015-04-14 05:11:24 +00001252 DestExprs.append(C->destination_exprs().begin(),
1253 C->destination_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001254 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001255 AssignmentOps.append(C->assignment_ops().begin(),
1256 C->assignment_ops().end());
1257 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001258 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataeva63048e2015-03-23 06:18:07 +00001259 // Emit code for 'single' region along with 'copyprivate' clauses
Alexey Bataev5521d782015-04-24 04:21:15 +00001260 bool HasFirstprivates;
1261 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) {
1262 CodeGenFunction::OMPPrivateScope SingleScope(CGF);
1263 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope);
Alexey Bataev59c654a2015-04-27 03:48:52 +00001264 CGF.EmitOMPPrivateClause(S, SingleScope);
Alexey Bataev5521d782015-04-24 04:21:15 +00001265 (void)SingleScope.Privatize();
1266
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001267 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1268 CGF.EnsureInsertPoint();
1269 };
1270 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00001271 CopyprivateVars, DestExprs, SrcExprs,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001272 AssignmentOps);
Alexey Bataev5521d782015-04-24 04:21:15 +00001273 // Emit an implicit barrier at the end (to avoid data race on firstprivate
1274 // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
1275 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) &&
1276 CopyprivateVars.empty()) {
1277 CGM.getOpenMPRuntime().emitBarrierCall(
1278 *this, S.getLocStart(),
1279 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single);
Alexey Bataevf2685682015-03-30 04:30:22 +00001280 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001281}
1282
Alexey Bataev8d690652014-12-04 07:23:53 +00001283void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001284 LexicalScope Scope(*this, S.getSourceRange());
1285 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1286 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1287 CGF.EnsureInsertPoint();
1288 };
1289 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
Alexander Musman80c22892014-07-17 08:54:58 +00001290}
1291
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001292void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001293 LexicalScope Scope(*this, S.getSourceRange());
1294 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1295 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1296 CGF.EnsureInsertPoint();
1297 };
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001298 CGM.getOpenMPRuntime().emitCriticalRegion(
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001299 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart());
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001300}
1301
Alexey Bataev671605e2015-04-13 05:28:11 +00001302void CodeGenFunction::EmitOMPParallelForDirective(
1303 const OMPParallelForDirective &S) {
1304 // Emit directive as a combined directive that consists of two implicit
1305 // directives: 'parallel' with 'for' directive.
1306 LexicalScope Scope(*this, S.getSourceRange());
1307 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1308 CGF.EmitOMPWorksharingLoop(S);
1309 // Emit implicit barrier at the end of parallel region, but this barrier
1310 // is at the end of 'for' directive, so emit it as the implicit barrier for
1311 // this 'for' directive.
1312 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1313 OMPD_parallel);
1314 };
1315 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev4acb8592014-07-07 13:01:15 +00001316}
1317
Alexander Musmane4e893b2014-09-23 09:33:00 +00001318void CodeGenFunction::EmitOMPParallelForSimdDirective(
1319 const OMPParallelForSimdDirective &) {
1320 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet.");
1321}
1322
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001323void CodeGenFunction::EmitOMPParallelSectionsDirective(
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001324 const OMPParallelSectionsDirective &S) {
1325 // Emit directive as a combined directive that consists of two implicit
1326 // directives: 'parallel' with 'sections' directive.
1327 LexicalScope Scope(*this, S.getSourceRange());
1328 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1329 (void)emitSections(CGF, S);
1330 // Emit implicit barrier at the end of parallel region.
1331 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(),
1332 OMPD_parallel);
1333 };
1334 emitCommonOMPParallelDirective(*this, S, CodeGen);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001335}
1336
Alexey Bataev62b63b12015-03-10 07:28:44 +00001337void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
1338 // Emit outlined function for task construct.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001339 LexicalScope Scope(*this, S.getSourceRange());
Alexey Bataev62b63b12015-03-10 07:28:44 +00001340 auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
1341 auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
1342 auto *I = CS->getCapturedDecl()->param_begin();
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001343 auto *PartId = std::next(I);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001344 // The first function argument for tasks is a thread id, the second one is a
1345 // part id (0 for tied tasks, >=0 for untied task).
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001346 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) {
1347 if (*PartId) {
1348 // TODO: emit code for untied tasks.
1349 }
1350 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1351 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00001352 auto OutlinedFn =
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001353 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001354 // Check if we should emit tied or untied task.
1355 bool Tied = !S.getSingleClause(OMPC_untied);
1356 // Check if the task is final
1357 llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
1358 if (auto *Clause = S.getSingleClause(OMPC_final)) {
1359 // If the condition constant folds and can be elided, try to avoid emitting
1360 // the condition and the dead arm of the if/else.
1361 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition();
1362 bool CondConstant;
1363 if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
1364 Final.setInt(CondConstant);
1365 else
1366 Final.setPointer(EvaluateExprAsBool(Cond));
1367 } else {
1368 // By default the task is not final.
1369 Final.setInt(/*IntVal=*/false);
1370 }
1371 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
Alexey Bataev1d677132015-04-22 13:57:31 +00001372 const Expr *IfCond = nullptr;
1373 if (auto C = S.getSingleClause(OMPC_if)) {
1374 IfCond = cast<OMPIfClause>(C)->getCondition();
1375 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001376 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getLocStart(), Tied, Final,
Alexey Bataev1d677132015-04-22 13:57:31 +00001377 OutlinedFn, SharedsTy, CapturedStruct,
1378 IfCond);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001379}
1380
Alexey Bataev9f797f32015-02-05 05:57:51 +00001381void CodeGenFunction::EmitOMPTaskyieldDirective(
1382 const OMPTaskyieldDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001383 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
Alexey Bataev68446b72014-07-18 07:47:19 +00001384}
1385
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001386void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
Alexey Bataevf2685682015-03-30 04:30:22 +00001387 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001388}
1389
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001390void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
1391 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
Alexey Bataev2df347a2014-07-18 10:17:07 +00001392}
1393
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001394void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001395 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
1396 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) {
1397 auto FlushClause = cast<OMPFlushClause>(C);
1398 return llvm::makeArrayRef(FlushClause->varlist_begin(),
1399 FlushClause->varlist_end());
1400 }
1401 return llvm::None;
1402 }(), S.getLocStart());
Alexey Bataev6125da92014-07-21 11:26:11 +00001403}
1404
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001405void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
1406 LexicalScope Scope(*this, S.getSourceRange());
1407 auto &&CodeGen = [&S](CodeGenFunction &CGF) {
1408 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
1409 CGF.EnsureInsertPoint();
1410 };
1411 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001412}
1413
Alexey Bataevb57056f2015-01-22 06:17:56 +00001414static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
1415 QualType SrcType, QualType DestType) {
1416 assert(CGF.hasScalarEvaluationKind(DestType) &&
1417 "DestType must have scalar evaluation kind.");
1418 assert(!Val.isAggregate() && "Must be a scalar or complex.");
1419 return Val.isScalar()
1420 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType)
1421 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
1422 DestType);
1423}
1424
1425static CodeGenFunction::ComplexPairTy
1426convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
1427 QualType DestType) {
1428 assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
1429 "DestType must have complex evaluation kind.");
1430 CodeGenFunction::ComplexPairTy ComplexVal;
1431 if (Val.isScalar()) {
1432 // Convert the input element to the element type of the complex.
1433 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1434 auto ScalarVal =
1435 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType);
1436 ComplexVal = CodeGenFunction::ComplexPairTy(
1437 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
1438 } else {
1439 assert(Val.isComplex() && "Must be a scalar or complex.");
1440 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
1441 auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
1442 ComplexVal.first = CGF.EmitScalarConversion(
1443 Val.getComplexVal().first, SrcElementType, DestElementType);
1444 ComplexVal.second = CGF.EmitScalarConversion(
1445 Val.getComplexVal().second, SrcElementType, DestElementType);
1446 }
1447 return ComplexVal;
1448}
1449
Alexey Bataev5e018f92015-04-23 06:35:10 +00001450static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
1451 LValue LVal, RValue RVal) {
1452 if (LVal.isGlobalReg()) {
1453 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
1454 } else {
1455 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent
1456 : llvm::Monotonic,
1457 LVal.isVolatile(), /*IsInit=*/false);
1458 }
1459}
1460
1461static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal,
1462 QualType RValTy) {
1463 switch (CGF.getEvaluationKind(LVal.getType())) {
1464 case TEK_Scalar:
1465 CGF.EmitStoreThroughLValue(
1466 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())),
1467 LVal);
1468 break;
1469 case TEK_Complex:
1470 CGF.EmitStoreOfComplex(
1471 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal,
1472 /*isInit=*/false);
1473 break;
1474 case TEK_Aggregate:
1475 llvm_unreachable("Must be a scalar or complex.");
1476 }
1477}
1478
Alexey Bataevb57056f2015-01-22 06:17:56 +00001479static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
1480 const Expr *X, const Expr *V,
1481 SourceLocation Loc) {
1482 // v = x;
1483 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
1484 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
1485 LValue XLValue = CGF.EmitLValue(X);
1486 LValue VLValue = CGF.EmitLValue(V);
David Majnemera5b195a2015-02-14 01:35:12 +00001487 RValue Res = XLValue.isGlobalReg()
1488 ? CGF.EmitLoadOfLValue(XLValue, Loc)
1489 : CGF.EmitAtomicLoad(XLValue, Loc,
1490 IsSeqCst ? llvm::SequentiallyConsistent
Alexey Bataevb8329262015-02-27 06:33:30 +00001491 : llvm::Monotonic,
1492 XLValue.isVolatile());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001493 // OpenMP, 2.12.6, atomic Construct
1494 // Any atomic construct with a seq_cst clause forces the atomically
1495 // performed operation to include an implicit flush operation without a
1496 // list.
1497 if (IsSeqCst)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001498 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001499 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType());
Alexey Bataevb57056f2015-01-22 06:17:56 +00001500}
1501
Alexey Bataevb8329262015-02-27 06:33:30 +00001502static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
1503 const Expr *X, const Expr *E,
1504 SourceLocation Loc) {
1505 // x = expr;
1506 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
Alexey Bataev5e018f92015-04-23 06:35:10 +00001507 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
Alexey Bataevb8329262015-02-27 06:33:30 +00001508 // OpenMP, 2.12.6, atomic Construct
1509 // Any atomic construct with a seq_cst clause forces the atomically
1510 // performed operation to include an implicit flush operation without a
1511 // list.
1512 if (IsSeqCst)
1513 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1514}
1515
Alexey Bataev5e018f92015-04-23 06:35:10 +00001516std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
1517 RValue Update, BinaryOperatorKind BO,
1518 llvm::AtomicOrdering AO,
1519 bool IsXLHSInRHSPart) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001520 auto &Context = CGF.CGM.getContext();
1521 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
Alexey Bataevb4505a72015-03-30 05:20:59 +00001522 // expression is simple and atomic is allowed for the given type for the
1523 // target platform.
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001524 if (BO == BO_Comma || !Update.isScalar() ||
1525 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() ||
1526 (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
1527 (Update.getScalarVal()->getType() !=
1528 X.getAddress()->getType()->getPointerElementType())) ||
1529 !Context.getTargetInfo().hasBuiltinAtomic(
1530 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
Alexey Bataev5e018f92015-04-23 06:35:10 +00001531 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001532
1533 llvm::AtomicRMWInst::BinOp RMWOp;
1534 switch (BO) {
1535 case BO_Add:
1536 RMWOp = llvm::AtomicRMWInst::Add;
1537 break;
1538 case BO_Sub:
1539 if (!IsXLHSInRHSPart)
Alexey Bataev5e018f92015-04-23 06:35:10 +00001540 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001541 RMWOp = llvm::AtomicRMWInst::Sub;
1542 break;
1543 case BO_And:
1544 RMWOp = llvm::AtomicRMWInst::And;
1545 break;
1546 case BO_Or:
1547 RMWOp = llvm::AtomicRMWInst::Or;
1548 break;
1549 case BO_Xor:
1550 RMWOp = llvm::AtomicRMWInst::Xor;
1551 break;
1552 case BO_LT:
1553 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1554 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
1555 : llvm::AtomicRMWInst::Max)
1556 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
1557 : llvm::AtomicRMWInst::UMax);
1558 break;
1559 case BO_GT:
1560 RMWOp = X.getType()->hasSignedIntegerRepresentation()
1561 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
1562 : llvm::AtomicRMWInst::Min)
1563 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
1564 : llvm::AtomicRMWInst::UMin);
1565 break;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001566 case BO_Assign:
1567 RMWOp = llvm::AtomicRMWInst::Xchg;
1568 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001569 case BO_Mul:
1570 case BO_Div:
1571 case BO_Rem:
1572 case BO_Shl:
1573 case BO_Shr:
1574 case BO_LAnd:
1575 case BO_LOr:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001576 return std::make_pair(false, RValue::get(nullptr));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001577 case BO_PtrMemD:
1578 case BO_PtrMemI:
1579 case BO_LE:
1580 case BO_GE:
1581 case BO_EQ:
1582 case BO_NE:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001583 case BO_AddAssign:
1584 case BO_SubAssign:
1585 case BO_AndAssign:
1586 case BO_OrAssign:
1587 case BO_XorAssign:
1588 case BO_MulAssign:
1589 case BO_DivAssign:
1590 case BO_RemAssign:
1591 case BO_ShlAssign:
1592 case BO_ShrAssign:
1593 case BO_Comma:
1594 llvm_unreachable("Unsupported atomic update operation");
1595 }
1596 auto *UpdateVal = Update.getScalarVal();
1597 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
1598 UpdateVal = CGF.Builder.CreateIntCast(
1599 IC, X.getAddress()->getType()->getPointerElementType(),
1600 X.getType()->hasSignedIntegerRepresentation());
1601 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001602 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO);
1603 return std::make_pair(true, RValue::get(Res));
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001604}
1605
Alexey Bataev5e018f92015-04-23 06:35:10 +00001606std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001607 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
1608 llvm::AtomicOrdering AO, SourceLocation Loc,
1609 const llvm::function_ref<RValue(RValue)> &CommonGen) {
1610 // Update expressions are allowed to have the following forms:
1611 // x binop= expr; -> xrval + expr;
1612 // x++, ++x -> xrval + 1;
1613 // x--, --x -> xrval - 1;
1614 // x = x binop expr; -> xrval binop expr
1615 // x = expr Op x; - > expr binop xrval;
Alexey Bataev5e018f92015-04-23 06:35:10 +00001616 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
1617 if (!Res.first) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001618 if (X.isGlobalReg()) {
1619 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
1620 // 'xrval'.
1621 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
1622 } else {
1623 // Perform compare-and-swap procedure.
1624 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
Alexey Bataevb4505a72015-03-30 05:20:59 +00001625 }
1626 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00001627 return Res;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001628}
1629
1630static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
1631 const Expr *X, const Expr *E,
1632 const Expr *UE, bool IsXLHSInRHSPart,
1633 SourceLocation Loc) {
1634 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1635 "Update expr in 'atomic update' must be a binary operator.");
1636 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1637 // Update expressions are allowed to have the following forms:
1638 // x binop= expr; -> xrval + expr;
1639 // x++, ++x -> xrval + 1;
1640 // x--, --x -> xrval - 1;
1641 // x = x binop expr; -> xrval binop expr
1642 // x = expr Op x; - > expr binop xrval;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001643 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
Alexey Bataevb4505a72015-03-30 05:20:59 +00001644 LValue XLValue = CGF.EmitLValue(X);
1645 RValue ExprRValue = CGF.EmitAnyExpr(E);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001646 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001647 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1648 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1649 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1650 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1651 auto Gen =
1652 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
1653 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1654 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1655 return CGF.EmitAnyExpr(UE);
1656 };
Alexey Bataev5e018f92015-04-23 06:35:10 +00001657 (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
1658 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1659 // OpenMP, 2.12.6, atomic Construct
1660 // Any atomic construct with a seq_cst clause forces the atomically
1661 // performed operation to include an implicit flush operation without a
1662 // list.
1663 if (IsSeqCst)
1664 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1665}
1666
1667static RValue convertToType(CodeGenFunction &CGF, RValue Value,
1668 QualType SourceType, QualType ResType) {
1669 switch (CGF.getEvaluationKind(ResType)) {
1670 case TEK_Scalar:
1671 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType));
1672 case TEK_Complex: {
1673 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType);
1674 return RValue::getComplex(Res.first, Res.second);
1675 }
1676 case TEK_Aggregate:
1677 break;
1678 }
1679 llvm_unreachable("Must be a scalar or complex.");
1680}
1681
1682static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
1683 bool IsPostfixUpdate, const Expr *V,
1684 const Expr *X, const Expr *E,
1685 const Expr *UE, bool IsXLHSInRHSPart,
1686 SourceLocation Loc) {
1687 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
1688 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
1689 RValue NewVVal;
1690 LValue VLValue = CGF.EmitLValue(V);
1691 LValue XLValue = CGF.EmitLValue(X);
1692 RValue ExprRValue = CGF.EmitAnyExpr(E);
1693 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic;
1694 QualType NewVValType;
1695 if (UE) {
1696 // 'x' is updated with some additional value.
1697 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
1698 "Update expr in 'atomic capture' must be a binary operator.");
1699 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
1700 // Update expressions are allowed to have the following forms:
1701 // x binop= expr; -> xrval + expr;
1702 // x++, ++x -> xrval + 1;
1703 // x--, --x -> xrval - 1;
1704 // x = x binop expr; -> xrval binop expr
1705 // x = expr Op x; - > expr binop xrval;
1706 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
1707 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
1708 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
1709 NewVValType = XRValExpr->getType();
1710 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
1711 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
1712 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue {
1713 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1714 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
1715 RValue Res = CGF.EmitAnyExpr(UE);
1716 NewVVal = IsPostfixUpdate ? XRValue : Res;
1717 return Res;
1718 };
1719 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1720 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
1721 if (Res.first) {
1722 // 'atomicrmw' instruction was generated.
1723 if (IsPostfixUpdate) {
1724 // Use old value from 'atomicrmw'.
1725 NewVVal = Res.second;
1726 } else {
1727 // 'atomicrmw' does not provide new value, so evaluate it using old
1728 // value of 'x'.
1729 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
1730 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
1731 NewVVal = CGF.EmitAnyExpr(UE);
1732 }
1733 }
1734 } else {
1735 // 'x' is simply rewritten with some 'expr'.
1736 NewVValType = X->getType().getNonReferenceType();
1737 ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
1738 X->getType().getNonReferenceType());
1739 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue {
1740 NewVVal = XRValue;
1741 return ExprRValue;
1742 };
1743 // Try to perform atomicrmw xchg, otherwise simple exchange.
1744 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
1745 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
1746 Loc, Gen);
1747 if (Res.first) {
1748 // 'atomicrmw' instruction was generated.
1749 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
1750 }
1751 }
1752 // Emit post-update store to 'v' of old/new 'x' value.
1753 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001754 // OpenMP, 2.12.6, atomic Construct
1755 // Any atomic construct with a seq_cst clause forces the atomically
1756 // performed operation to include an implicit flush operation without a
1757 // list.
1758 if (IsSeqCst)
1759 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
1760}
1761
Alexey Bataevb57056f2015-01-22 06:17:56 +00001762static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
Alexey Bataev5e018f92015-04-23 06:35:10 +00001763 bool IsSeqCst, bool IsPostfixUpdate,
1764 const Expr *X, const Expr *V, const Expr *E,
1765 const Expr *UE, bool IsXLHSInRHSPart,
1766 SourceLocation Loc) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001767 switch (Kind) {
1768 case OMPC_read:
1769 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
1770 break;
1771 case OMPC_write:
Alexey Bataevb8329262015-02-27 06:33:30 +00001772 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
1773 break;
Alexey Bataevb4505a72015-03-30 05:20:59 +00001774 case OMPC_unknown:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001775 case OMPC_update:
Alexey Bataevb4505a72015-03-30 05:20:59 +00001776 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
1777 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001778 case OMPC_capture:
Alexey Bataev5e018f92015-04-23 06:35:10 +00001779 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
1780 IsXLHSInRHSPart, Loc);
1781 break;
Alexey Bataevb57056f2015-01-22 06:17:56 +00001782 case OMPC_if:
1783 case OMPC_final:
1784 case OMPC_num_threads:
1785 case OMPC_private:
1786 case OMPC_firstprivate:
1787 case OMPC_lastprivate:
1788 case OMPC_reduction:
1789 case OMPC_safelen:
1790 case OMPC_collapse:
1791 case OMPC_default:
1792 case OMPC_seq_cst:
1793 case OMPC_shared:
1794 case OMPC_linear:
1795 case OMPC_aligned:
1796 case OMPC_copyin:
1797 case OMPC_copyprivate:
1798 case OMPC_flush:
1799 case OMPC_proc_bind:
1800 case OMPC_schedule:
1801 case OMPC_ordered:
1802 case OMPC_nowait:
1803 case OMPC_untied:
1804 case OMPC_threadprivate:
1805 case OMPC_mergeable:
Alexey Bataevb57056f2015-01-22 06:17:56 +00001806 llvm_unreachable("Clause is not allowed in 'omp atomic'.");
1807 }
1808}
1809
1810void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
1811 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst);
1812 OpenMPClauseKind Kind = OMPC_unknown;
1813 for (auto *C : S.clauses()) {
1814 // Find first clause (skip seq_cst clause, if it is first).
1815 if (C->getClauseKind() != OMPC_seq_cst) {
1816 Kind = C->getClauseKind();
1817 break;
1818 }
1819 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001820
1821 const auto *CS =
1822 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001823 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
Alexey Bataev10fec572015-03-11 04:48:56 +00001824 enterFullExpression(EWC);
Alexey Bataev5e018f92015-04-23 06:35:10 +00001825 }
1826 // Processing for statements under 'atomic capture'.
1827 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
1828 for (const auto *C : Compound->body()) {
1829 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
1830 enterFullExpression(EWC);
1831 }
1832 }
1833 }
Alexey Bataev10fec572015-03-11 04:48:56 +00001834
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001835 LexicalScope Scope(*this, S.getSourceRange());
1836 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) {
Alexey Bataev5e018f92015-04-23 06:35:10 +00001837 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
1838 S.getV(), S.getExpr(), S.getUpdateExpr(),
1839 S.isXLHSInRHSPart(), S.getLocStart());
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001840 };
1841 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen);
Alexey Bataev0162e452014-07-22 10:10:35 +00001842}
1843
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001844void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) {
1845 llvm_unreachable("CodeGen for 'omp target' is not supported yet.");
1846}
1847
Alexey Bataev13314bf2014-10-09 04:18:56 +00001848void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) {
1849 llvm_unreachable("CodeGen for 'omp teams' is not supported yet.");
1850}